@aztec/end-to-end 0.0.0-test.1 → 0.0.1-fake-ceab37513c

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/dest/bench/client_flows/benchmark.d.ts +60 -0
  2. package/dest/bench/client_flows/benchmark.d.ts.map +1 -0
  3. package/dest/bench/client_flows/benchmark.js +261 -0
  4. package/dest/bench/client_flows/client_flows_benchmark.d.ts +69 -0
  5. package/dest/bench/client_flows/client_flows_benchmark.d.ts.map +1 -0
  6. package/dest/bench/client_flows/client_flows_benchmark.js +315 -0
  7. package/dest/bench/client_flows/config.d.ts +14 -0
  8. package/dest/bench/client_flows/config.d.ts.map +1 -0
  9. package/dest/bench/client_flows/config.js +106 -0
  10. package/dest/bench/client_flows/data_extractor.d.ts +2 -0
  11. package/dest/bench/client_flows/data_extractor.d.ts.map +1 -0
  12. package/dest/bench/client_flows/data_extractor.js +99 -0
  13. package/dest/bench/utils.d.ts +10 -27
  14. package/dest/bench/utils.d.ts.map +1 -1
  15. package/dest/bench/utils.js +27 -43
  16. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.d.ts +15 -7
  17. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.d.ts.map +1 -1
  18. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.js +66 -38
  19. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.d.ts +10 -18
  20. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.d.ts.map +1 -1
  21. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.js +34 -53
  22. package/dest/e2e_deploy_contract/deploy_test.d.ts +4 -2
  23. package/dest/e2e_deploy_contract/deploy_test.d.ts.map +1 -1
  24. package/dest/e2e_deploy_contract/deploy_test.js +9 -6
  25. package/dest/e2e_epochs/epochs_test.d.ts +56 -17
  26. package/dest/e2e_epochs/epochs_test.d.ts.map +1 -1
  27. package/dest/e2e_epochs/epochs_test.js +222 -42
  28. package/dest/e2e_fees/bridging_race.notest.d.ts +2 -0
  29. package/dest/e2e_fees/bridging_race.notest.d.ts.map +1 -0
  30. package/dest/e2e_fees/bridging_race.notest.js +60 -0
  31. package/dest/e2e_fees/fees_test.d.ts +16 -5
  32. package/dest/e2e_fees/fees_test.d.ts.map +1 -1
  33. package/dest/e2e_fees/fees_test.js +87 -88
  34. package/dest/e2e_l1_publisher/write_json.d.ts +8 -0
  35. package/dest/e2e_l1_publisher/write_json.d.ts.map +1 -0
  36. package/dest/e2e_l1_publisher/write_json.js +57 -0
  37. package/dest/e2e_multi_validator/utils.d.ts +12 -0
  38. package/dest/e2e_multi_validator/utils.d.ts.map +1 -0
  39. package/dest/e2e_multi_validator/utils.js +214 -0
  40. package/dest/e2e_nested_contract/nested_contract_test.d.ts +5 -5
  41. package/dest/e2e_nested_contract/nested_contract_test.d.ts.map +1 -1
  42. package/dest/e2e_nested_contract/nested_contract_test.js +19 -14
  43. package/dest/e2e_p2p/inactivity_slash_test.d.ts +31 -0
  44. package/dest/e2e_p2p/inactivity_slash_test.d.ts.map +1 -0
  45. package/dest/e2e_p2p/inactivity_slash_test.js +132 -0
  46. package/dest/e2e_p2p/p2p_network.d.ts +56 -21
  47. package/dest/e2e_p2p/p2p_network.d.ts.map +1 -1
  48. package/dest/e2e_p2p/p2p_network.js +154 -125
  49. package/dest/e2e_p2p/shared.d.ts +41 -3
  50. package/dest/e2e_p2p/shared.d.ts.map +1 -1
  51. package/dest/e2e_p2p/shared.js +146 -6
  52. package/dest/e2e_token_contract/token_contract_test.d.ts +10 -5
  53. package/dest/e2e_token_contract/token_contract_test.d.ts.map +1 -1
  54. package/dest/e2e_token_contract/token_contract_test.js +51 -24
  55. package/dest/{e2e_prover → fixtures}/e2e_prover_test.d.ts +7 -4
  56. package/dest/fixtures/e2e_prover_test.d.ts.map +1 -0
  57. package/dest/{e2e_prover → fixtures}/e2e_prover_test.js +67 -62
  58. package/dest/fixtures/fixtures.d.ts +5 -6
  59. package/dest/fixtures/fixtures.d.ts.map +1 -1
  60. package/dest/fixtures/fixtures.js +4 -3
  61. package/dest/fixtures/get_acvm_config.d.ts.map +1 -1
  62. package/dest/fixtures/get_acvm_config.js +2 -14
  63. package/dest/fixtures/get_bb_config.d.ts.map +1 -1
  64. package/dest/fixtures/get_bb_config.js +8 -15
  65. package/dest/fixtures/l1_to_l2_messaging.d.ts +8 -5
  66. package/dest/fixtures/l1_to_l2_messaging.d.ts.map +1 -1
  67. package/dest/fixtures/l1_to_l2_messaging.js +44 -18
  68. package/dest/fixtures/setup_l1_contracts.d.ts +3 -3
  69. package/dest/fixtures/setup_l1_contracts.d.ts.map +1 -1
  70. package/dest/fixtures/setup_l1_contracts.js +3 -3
  71. package/dest/fixtures/setup_p2p_test.d.ts +14 -6
  72. package/dest/fixtures/setup_p2p_test.d.ts.map +1 -1
  73. package/dest/fixtures/setup_p2p_test.js +73 -21
  74. package/dest/fixtures/snapshot_manager.d.ts +8 -3
  75. package/dest/fixtures/snapshot_manager.d.ts.map +1 -1
  76. package/dest/fixtures/snapshot_manager.js +120 -104
  77. package/dest/fixtures/token_utils.d.ts +4 -3
  78. package/dest/fixtures/token_utils.d.ts.map +1 -1
  79. package/dest/fixtures/token_utils.js +24 -7
  80. package/dest/fixtures/utils.d.ts +65 -22
  81. package/dest/fixtures/utils.d.ts.map +1 -1
  82. package/dest/fixtures/utils.js +439 -318
  83. package/dest/fixtures/web3signer.d.ts +5 -0
  84. package/dest/fixtures/web3signer.d.ts.map +1 -0
  85. package/dest/fixtures/web3signer.js +42 -0
  86. package/dest/shared/cross_chain_test_harness.d.ts +28 -18
  87. package/dest/shared/cross_chain_test_harness.d.ts.map +1 -1
  88. package/dest/shared/cross_chain_test_harness.js +97 -41
  89. package/dest/shared/gas_portal_test_harness.d.ts +23 -18
  90. package/dest/shared/gas_portal_test_harness.d.ts.map +1 -1
  91. package/dest/shared/gas_portal_test_harness.js +43 -25
  92. package/dest/shared/submit-transactions.d.ts.map +1 -1
  93. package/dest/shared/uniswap_l1_l2.d.ts +5 -6
  94. package/dest/shared/uniswap_l1_l2.d.ts.map +1 -1
  95. package/dest/shared/uniswap_l1_l2.js +136 -90
  96. package/dest/simulators/lending_simulator.d.ts +5 -6
  97. package/dest/simulators/lending_simulator.d.ts.map +1 -1
  98. package/dest/simulators/lending_simulator.js +11 -15
  99. package/dest/simulators/token_simulator.d.ts +2 -1
  100. package/dest/simulators/token_simulator.d.ts.map +1 -1
  101. package/dest/simulators/token_simulator.js +16 -13
  102. package/dest/spartan/setup_test_wallets.d.ts +8 -1
  103. package/dest/spartan/setup_test_wallets.d.ts.map +1 -1
  104. package/dest/spartan/setup_test_wallets.js +108 -22
  105. package/dest/spartan/utils.d.ts +60 -307
  106. package/dest/spartan/utils.d.ts.map +1 -1
  107. package/dest/spartan/utils.js +200 -115
  108. package/package.json +60 -56
  109. package/src/bench/client_flows/benchmark.ts +341 -0
  110. package/src/bench/client_flows/client_flows_benchmark.ts +422 -0
  111. package/src/bench/client_flows/config.ts +61 -0
  112. package/src/bench/client_flows/data_extractor.ts +111 -0
  113. package/src/bench/utils.ts +26 -52
  114. package/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts +60 -40
  115. package/src/e2e_cross_chain_messaging/cross_chain_messaging_test.ts +47 -75
  116. package/src/e2e_deploy_contract/deploy_test.ts +11 -8
  117. package/src/e2e_epochs/epochs_test.ts +276 -54
  118. package/src/e2e_fees/bridging_race.notest.ts +75 -0
  119. package/src/e2e_fees/fees_test.ts +121 -108
  120. package/src/e2e_l1_publisher/write_json.ts +74 -0
  121. package/src/e2e_multi_validator/utils.ts +258 -0
  122. package/src/e2e_nested_contract/nested_contract_test.ts +22 -14
  123. package/src/e2e_p2p/inactivity_slash_test.ts +174 -0
  124. package/src/e2e_p2p/p2p_network.ts +212 -144
  125. package/src/e2e_p2p/shared.ts +234 -14
  126. package/src/e2e_token_contract/token_contract_test.ts +42 -38
  127. package/src/fixtures/dumps/epoch_proof_result.json +1 -1
  128. package/src/{e2e_prover → fixtures}/e2e_prover_test.ts +62 -69
  129. package/src/fixtures/fixtures.ts +4 -3
  130. package/src/fixtures/get_acvm_config.ts +2 -10
  131. package/src/fixtures/get_bb_config.ts +15 -11
  132. package/src/fixtures/l1_to_l2_messaging.ts +53 -23
  133. package/src/fixtures/setup_l1_contracts.ts +5 -6
  134. package/src/fixtures/setup_p2p_test.ts +112 -30
  135. package/src/fixtures/snapshot_manager.ts +150 -102
  136. package/src/fixtures/token_utils.ts +33 -8
  137. package/src/fixtures/utils.ts +530 -352
  138. package/src/fixtures/web3signer.ts +46 -0
  139. package/src/guides/up_quick_start.sh +4 -4
  140. package/src/shared/cross_chain_test_harness.ts +92 -52
  141. package/src/shared/gas_portal_test_harness.ts +47 -31
  142. package/src/shared/uniswap_l1_l2.ts +127 -124
  143. package/src/simulators/lending_simulator.ts +11 -15
  144. package/src/simulators/token_simulator.ts +17 -12
  145. package/src/spartan/DEVELOP.md +116 -0
  146. package/src/spartan/setup_test_wallets.ts +144 -29
  147. package/src/spartan/utils.ts +194 -116
  148. package/dest/e2e_prover/e2e_prover_test.d.ts.map +0 -1
  149. package/dest/sample-dapp/connect.js +0 -12
  150. package/dest/sample-dapp/contracts.js +0 -10
  151. package/dest/sample-dapp/deploy.js +0 -35
  152. package/dest/sample-dapp/index.js +0 -98
  153. package/src/sample-dapp/connect.mjs +0 -16
  154. package/src/sample-dapp/contracts.mjs +0 -14
  155. package/src/sample-dapp/deploy.mjs +0 -40
  156. package/src/sample-dapp/index.mjs +0 -128
@@ -9,55 +9,80 @@ import {
9
9
  import { type Archiver, createArchiver } from '@aztec/archiver';
10
10
  import { type AztecNodeConfig, AztecNodeService, getConfigEnvVars } from '@aztec/aztec-node';
11
11
  import {
12
+ AccountManager,
12
13
  type AccountWalletWithSecretKey,
13
- AnvilTestWatcher,
14
14
  type AztecAddress,
15
15
  type AztecNode,
16
16
  BatchCall,
17
- CheatCodes,
18
17
  type ContractMethod,
19
- type DeployL1ContractsReturnType,
20
- FeeJuicePaymentMethod,
21
18
  type Logger,
22
19
  type PXE,
23
- SignerlessWallet,
24
20
  type Wallet,
25
21
  createAztecNodeClient,
26
22
  createLogger,
27
23
  createPXEClient,
28
- deployL1Contracts,
29
24
  makeFetch,
25
+ sleep,
30
26
  waitForPXE,
31
27
  } from '@aztec/aztec.js';
32
- import { deployInstance, registerContractClass } from '@aztec/aztec.js/deployment';
33
- import type { BBNativePrivateKernelProver } from '@aztec/bb-prover';
28
+ import { publishContractClass, publishInstance } from '@aztec/aztec.js/deployment';
29
+ import { AnvilTestWatcher, CheatCodes } from '@aztec/aztec/testing';
34
30
  import { createBlobSinkClient } from '@aztec/blob-sink/client';
35
31
  import { type BlobSinkServer, createBlobSinkServer } from '@aztec/blob-sink/server';
36
- import { FEE_JUICE_INITIAL_MINT, GENESIS_ARCHIVE_ROOT, GENESIS_BLOCK_HASH } from '@aztec/constants';
32
+ import { GENESIS_ARCHIVE_ROOT, SPONSORED_FPC_SALT } from '@aztec/constants';
37
33
  import {
38
34
  type DeployL1ContractsArgs,
39
- ForwarderContract,
35
+ type DeployL1ContractsReturnType,
36
+ FeeAssetArtifact,
40
37
  NULL_KEY,
41
- createL1Clients,
38
+ type Operator,
39
+ RollupContract,
40
+ createExtendedL1Client,
41
+ deployL1Contracts,
42
+ deployMulticall3,
42
43
  getL1ContractsConfigEnvVars,
43
44
  isAnvilTestChain,
44
- l1Artifacts,
45
45
  } from '@aztec/ethereum';
46
- import { DelayedTxUtils, EthCheatCodesWithState, startAnvil } from '@aztec/ethereum/test';
46
+ import {
47
+ DelayedTxUtils,
48
+ EthCheatCodes,
49
+ EthCheatCodesWithState,
50
+ createDelayedL1TxUtilsFromViemWallet,
51
+ startAnvil,
52
+ } from '@aztec/ethereum/test';
53
+ import { SecretValue } from '@aztec/foundation/config';
47
54
  import { randomBytes } from '@aztec/foundation/crypto';
48
55
  import { EthAddress } from '@aztec/foundation/eth-address';
49
56
  import { Fr } from '@aztec/foundation/fields';
57
+ import { tryRmDir } from '@aztec/foundation/fs';
58
+ import { withLogNameSuffix } from '@aztec/foundation/log';
50
59
  import { retryUntil } from '@aztec/foundation/retry';
51
- import { TestDateProvider } from '@aztec/foundation/timer';
52
- import { FeeJuiceContract } from '@aztec/noir-contracts.js/FeeJuice';
60
+ import { DateProvider, TestDateProvider } from '@aztec/foundation/timer';
61
+ import type { DataStoreConfig } from '@aztec/kv-store/config';
62
+ import { SponsoredFPCContract } from '@aztec/noir-contracts.js/SponsoredFPC';
53
63
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
54
- import { ProtocolContractAddress, protocolContractTreeRoot } from '@aztec/protocol-contracts';
55
- import { type ProverNode, type ProverNodeConfig, createProverNode } from '@aztec/prover-node';
56
- import { type PXEService, type PXEServiceConfig, createPXEService, getPXEServiceConfig } from '@aztec/pxe/server';
64
+ import type { P2PClientDeps } from '@aztec/p2p';
65
+ import { MockGossipSubNetwork, getMockPubSubP2PServiceFactory } from '@aztec/p2p/test-helpers';
66
+ import { protocolContractTreeRoot } from '@aztec/protocol-contracts';
67
+ import { type ProverNode, type ProverNodeConfig, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
68
+ import {
69
+ type PXEService,
70
+ type PXEServiceConfig,
71
+ createPXEServiceWithSimulator,
72
+ getPXEServiceConfig,
73
+ } from '@aztec/pxe/server';
57
74
  import type { SequencerClient } from '@aztec/sequencer-client';
58
75
  import type { TestSequencerClient } from '@aztec/sequencer-client/test';
59
- import { getContractClassFromArtifact } from '@aztec/stdlib/contract';
60
- import { Gas } from '@aztec/stdlib/gas';
76
+ import { MemoryCircuitRecorder, SimulatorRecorderWrapper, WASMSimulator } from '@aztec/simulator/client';
77
+ import { FileCircuitRecorder } from '@aztec/simulator/testing';
78
+ import {
79
+ type ContractInstanceWithAddress,
80
+ getContractClassFromArtifact,
81
+ getContractInstanceFromInstantiationParams,
82
+ } from '@aztec/stdlib/contract';
83
+ import type { AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
84
+ import { tryStop } from '@aztec/stdlib/interfaces/server';
85
+ import type { P2PClientType } from '@aztec/stdlib/p2p';
61
86
  import type { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
62
87
  import {
63
88
  type TelemetryClient,
@@ -73,9 +98,8 @@ import fs from 'fs/promises';
73
98
  import getPort from 'get-port';
74
99
  import { tmpdir } from 'os';
75
100
  import * as path from 'path';
76
- import { inspect } from 'util';
77
101
  import { type Chain, type HDAccount, type Hex, type PrivateKeyAccount, getContract } from 'viem';
78
- import { mnemonicToAccount, privateKeyToAccount } from 'viem/accounts';
102
+ import { generatePrivateKey, mnemonicToAccount, privateKeyToAccount } from 'viem/accounts';
79
103
  import { foundry } from 'viem/chains';
80
104
 
81
105
  import { MNEMONIC, TEST_PEER_CHECK_INTERVAL_MS } from './fixtures.js';
@@ -117,14 +141,13 @@ export const setupL1Contracts = async (
117
141
  chain: Chain = foundry,
118
142
  ) => {
119
143
  const l1Data = await deployL1Contracts(l1RpcUrls, account, chain, logger, {
120
- l2FeeJuiceAddress: ProtocolContractAddress.FeeJuice.toField(),
121
144
  vkTreeRoot: getVKTreeRoot(),
122
145
  protocolContractTreeRoot,
123
146
  genesisArchiveRoot: args.genesisArchiveRoot ?? new Fr(GENESIS_ARCHIVE_ROOT),
124
- genesisBlockHash: args.genesisBlockHash ?? new Fr(GENESIS_BLOCK_HASH),
125
147
  salt: args.salt,
126
148
  initialValidators: args.initialValidators,
127
149
  ...getL1ContractsConfigEnvVars(),
150
+ realVerifier: false,
128
151
  ...args,
129
152
  });
130
153
 
@@ -135,18 +158,15 @@ export const setupL1Contracts = async (
135
158
  * Sets up Private eXecution Environment (PXE).
136
159
  * @param aztecNode - An instance of Aztec Node.
137
160
  * @param opts - Partial configuration for the PXE service.
138
- * @param firstPrivKey - The private key of the first account to be created.
139
161
  * @param logger - The logger to be used.
140
162
  * @param useLogSuffix - Whether to add a randomly generated suffix to the PXE debug logs.
141
- * @param proofCreator - An optional proof creator to use
142
- * @returns Private eXecution Environment (PXE), accounts, wallets and logger.
163
+ * @returns Private eXecution Environment (PXE), logger and teardown function.
143
164
  */
144
165
  export async function setupPXEService(
145
166
  aztecNode: AztecNode,
146
167
  opts: Partial<PXEServiceConfig> = {},
147
168
  logger = getLogger(),
148
169
  useLogSuffix = false,
149
- proofCreator?: BBNativePrivateKernelProver,
150
170
  ): Promise<{
151
171
  /**
152
172
  * The PXE instance.
@@ -162,6 +182,8 @@ export async function setupPXEService(
162
182
  teardown: () => Promise<void>;
163
183
  }> {
164
184
  const pxeServiceConfig = { ...getPXEServiceConfig(), ...opts };
185
+ // For tests we only want proving enabled if specifically requested
186
+ pxeServiceConfig.proverEnabled = !!opts.proverEnabled;
165
187
 
166
188
  // If no data directory provided, create a temp directory and clean up afterwards
167
189
  const configuredDataDirectory = pxeServiceConfig.dataDirectory;
@@ -169,17 +191,16 @@ export async function setupPXEService(
169
191
  pxeServiceConfig.dataDirectory = path.join(tmpdir(), randomBytes(8).toString('hex'));
170
192
  }
171
193
 
172
- const pxe = await createPXEService(aztecNode, pxeServiceConfig, useLogSuffix, proofCreator);
194
+ const simulator = new WASMSimulator();
195
+ const recorder = process.env.CIRCUIT_RECORD_DIR
196
+ ? new FileCircuitRecorder(process.env.CIRCUIT_RECORD_DIR)
197
+ : new MemoryCircuitRecorder();
198
+ const simulatorWithRecorder = new SimulatorRecorderWrapper(simulator, recorder);
199
+ const pxe = await createPXEServiceWithSimulator(aztecNode, simulatorWithRecorder, pxeServiceConfig, {
200
+ useLogSuffix,
201
+ });
173
202
 
174
- const teardown = async () => {
175
- if (!configuredDataDirectory) {
176
- try {
177
- await fs.rm(pxeServiceConfig.dataDirectory!, { recursive: true, force: true, maxRetries: 3 });
178
- } catch (err) {
179
- logger.warn(`Failed to delete tmp PXE data directory ${pxeServiceConfig.dataDirectory}: ${err}`);
180
- }
181
- }
182
- };
203
+ const teardown = configuredDataDirectory ? () => Promise.resolve() : () => tryRmDir(pxeServiceConfig.dataDirectory!);
183
204
 
184
205
  return {
185
206
  pxe,
@@ -202,7 +223,7 @@ async function setupWithRemoteEnvironment(
202
223
  config: AztecNodeConfig,
203
224
  logger: Logger,
204
225
  numberOfAccounts: number,
205
- ) {
226
+ ): Promise<EndToEndContext> {
206
227
  // we are setting up against a remote environment, l1 contracts are already deployed
207
228
  const aztecNodeUrl = getAztecUrl();
208
229
  logger.verbose(`Creating Aztec Node client to remote host ${aztecNodeUrl}`);
@@ -212,20 +233,19 @@ async function setupWithRemoteEnvironment(
212
233
  await waitForPXE(pxeClient, logger);
213
234
  logger.verbose('JSON RPC client connected to PXE');
214
235
  logger.verbose(`Retrieving contract addresses from ${PXE_URL}`);
215
- const l1Contracts = (await pxeClient.getNodeInfo()).l1ContractAddresses;
236
+ const { l1ContractAddresses, rollupVersion } = await pxeClient.getNodeInfo();
216
237
 
217
- const { walletClient, publicClient } = createL1Clients(config.l1RpcUrls, account, foundry);
238
+ const l1Client = createExtendedL1Client(config.l1RpcUrls, account, foundry);
218
239
 
219
240
  const deployL1ContractsValues: DeployL1ContractsReturnType = {
220
- l1ContractAddresses: l1Contracts,
221
- walletClient,
222
- publicClient,
241
+ l1ContractAddresses,
242
+ l1Client,
243
+ rollupVersion,
223
244
  };
245
+ const ethCheatCodes = new EthCheatCodes(config.l1RpcUrls);
224
246
  const cheatCodes = await CheatCodes.create(config.l1RpcUrls, pxeClient!);
225
247
  const teardown = () => Promise.resolve();
226
248
 
227
- await setupCanonicalFeeJuice(pxeClient);
228
-
229
249
  logger.verbose('Constructing available wallets from already registered accounts...');
230
250
  const initialFundedAccounts = await getDeployedTestAccounts(pxeClient);
231
251
  const wallets = await getDeployedTestAccountsWallets(pxeClient);
@@ -237,17 +257,21 @@ async function setupWithRemoteEnvironment(
237
257
 
238
258
  return {
239
259
  aztecNode,
260
+ aztecNodeAdmin: undefined,
240
261
  sequencer: undefined,
241
262
  proverNode: undefined,
242
263
  pxe: pxeClient,
243
264
  deployL1ContractsValues,
244
- accounts: await pxeClient!.getRegisteredAccounts(),
245
265
  config,
246
266
  initialFundedAccounts,
267
+ wallets,
247
268
  wallet: wallets[0],
248
- wallets: wallets.slice(0, numberOfAccounts),
269
+ accounts: wallets.slice(0, numberOfAccounts).map(w => w.getAddress()),
249
270
  logger,
250
271
  cheatCodes,
272
+ ethCheatCodes,
273
+ prefilledPublicData: undefined,
274
+ mockGossipSubNetwork: undefined,
251
275
  watcher: undefined,
252
276
  dateProvider: undefined,
253
277
  blobSink: undefined,
@@ -275,7 +299,7 @@ export type SetupOptions = {
275
299
  /** Salt to use in L1 contract deployment */
276
300
  salt?: number;
277
301
  /** An initial set of validators */
278
- initialValidators?: EthAddress[];
302
+ initialValidators?: (Operator & { privateKey: `0x${string}` })[];
279
303
  /** Anvil Start time */
280
304
  l1StartTime?: number;
281
305
  /** The anvil time where we should at the earliest be seeing L2 blocks */
@@ -288,12 +312,28 @@ export type SetupOptions = {
288
312
  telemetryConfig?: Partial<TelemetryClientConfig> & { benchmark?: boolean };
289
313
  /** Public data that will be inserted in the tree in genesis */
290
314
  genesisPublicData?: PublicDataTreeLeaf[];
315
+ /** Specific config for the prover node, if set. */
316
+ proverNodeConfig?: Partial<ProverNodeConfig>;
317
+ /** Whether to use a mock gossip sub network for p2p clients. */
318
+ mockGossipSubNetwork?: boolean;
319
+ /** Whether to disable the anvil test watcher (can still be manually started) */
320
+ disableAnvilTestWatcher?: boolean;
321
+ /** Whether to enable anvil automine during deployment of L1 contracts (consider defaulting this to true). */
322
+ automineL1Setup?: boolean;
323
+ /** How many accounts to seed and unlock in anvil. */
324
+ anvilAccounts?: number;
325
+ /** Port to start anvil (defaults to 8545) */
326
+ anvilPort?: number;
327
+ /** Key to use for publishing L1 contracts */
328
+ l1PublisherKey?: SecretValue<`0x${string}`>;
291
329
  } & Partial<AztecNodeConfig>;
292
330
 
293
331
  /** Context for an end-to-end test as returned by the `setup` function */
294
332
  export type EndToEndContext = {
295
333
  /** The Aztec Node service or client a connected to it. */
296
334
  aztecNode: AztecNode;
335
+ /** Client to the Aztec Node admin interface (undefined if connected to remote environment) */
336
+ aztecNodeAdmin?: AztecNodeAdmin;
297
337
  /** The prover node service (only set if startProverNode is true) */
298
338
  proverNode: ProverNode | undefined;
299
339
  /** A client to the sequencer service (undefined if connected to remote environment) */
@@ -306,14 +346,18 @@ export type EndToEndContext = {
306
346
  config: AztecNodeConfig;
307
347
  /** The data for the initial funded accounts. */
308
348
  initialFundedAccounts: InitialAccountData[];
349
+ /* Wallets created for the initial funded accounts, with secret keys. */
350
+ wallets: AccountWalletWithSecretKey[];
309
351
  /** The first wallet to be used. */
310
352
  wallet: AccountWalletWithSecretKey;
311
- /** The wallets to be used. */
312
- wallets: AccountWalletWithSecretKey[];
353
+ /** The accounts to be used. */
354
+ accounts: AztecAddress[];
313
355
  /** Logger instance named as the current test. */
314
356
  logger: Logger;
315
357
  /** The cheat codes. */
316
358
  cheatCodes: CheatCodes;
359
+ /** The cheat codes for L1 */
360
+ ethCheatCodes: EthCheatCodes;
317
361
  /** The anvil test watcher (undefined if connected to remote environment) */
318
362
  watcher: AnvilTestWatcher | undefined;
319
363
  /** Allows tweaking current system time, used by the epoch cache only (undefined if connected to remote environment) */
@@ -322,6 +366,10 @@ export type EndToEndContext = {
322
366
  blobSink: BlobSinkServer | undefined;
323
367
  /** Telemetry client */
324
368
  telemetryClient: TelemetryClient | undefined;
369
+ /** Mock gossip sub network used for gossipping messages (only if mockGossipSubNetwork was set to true in opts) */
370
+ mockGossipSubNetwork: MockGossipSubNetwork | undefined;
371
+ /** Prefilled public data used for setting up nodes. */
372
+ prefilledPublicData: PublicDataTreeLeaf[] | undefined;
325
373
  /** Function to stop the started services. */
326
374
  teardown: () => Promise<void>;
327
375
  };
@@ -334,267 +382,375 @@ export type EndToEndContext = {
334
382
  */
335
383
  export async function setup(
336
384
  numberOfAccounts = 1,
337
- opts: SetupOptions = {
338
- customForwarderContractAddress: EthAddress.ZERO,
339
- },
385
+ opts: SetupOptions = {},
340
386
  pxeOpts: Partial<PXEServiceConfig> = {},
341
387
  chain: Chain = foundry,
342
388
  ): Promise<EndToEndContext> {
343
- const config = { ...getConfigEnvVars(), ...opts };
344
- config.peerCheckIntervalMS = TEST_PEER_CHECK_INTERVAL_MS;
345
-
346
- const logger = getLogger();
347
-
348
- // Create a temp directory for any services that need it and cleanup later
349
- const directoryToCleanup = path.join(tmpdir(), randomBytes(8).toString('hex'));
350
- await fs.mkdir(directoryToCleanup, { recursive: true });
351
- if (!config.dataDirectory) {
352
- config.dataDirectory = directoryToCleanup;
353
- }
354
-
355
389
  let anvil: Anvil | undefined;
356
-
357
- if (!config.l1RpcUrls?.length) {
358
- if (!isAnvilTestChain(chain.id)) {
359
- throw new Error(`No ETHEREUM_HOSTS set but non anvil chain requested`);
360
- }
361
- if (PXE_URL) {
362
- throw new Error(
363
- `PXE_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`,
364
- );
390
+ try {
391
+ opts.aztecTargetCommitteeSize ??= 0;
392
+ opts.slasherFlavor ??= 'none';
393
+
394
+ const config: AztecNodeConfig & SetupOptions = { ...getConfigEnvVars(), ...opts };
395
+ // use initialValidators for the node config
396
+ config.validatorPrivateKeys = new SecretValue(opts.initialValidators?.map(v => v.privateKey) ?? []);
397
+
398
+ config.peerCheckIntervalMS = TEST_PEER_CHECK_INTERVAL_MS;
399
+ // For tests we only want proving enabled if specifically requested
400
+ config.realProofs = !!opts.realProofs;
401
+ // Only enforce the time table if requested
402
+ config.enforceTimeTable = !!opts.enforceTimeTable;
403
+
404
+ const logger = getLogger();
405
+
406
+ // Create a temp directory for any services that need it and cleanup later
407
+ const directoryToCleanup = path.join(tmpdir(), randomBytes(8).toString('hex'));
408
+ await fs.mkdir(directoryToCleanup, { recursive: true });
409
+ if (!config.dataDirectory) {
410
+ config.dataDirectory = directoryToCleanup;
365
411
  }
366
412
 
367
- const res = await startAnvil({ l1BlockTime: opts.ethereumSlotDuration });
368
- anvil = res.anvil;
369
- config.l1RpcUrls = [res.rpcUrl];
370
- }
413
+ if (!config.l1RpcUrls?.length) {
414
+ if (!isAnvilTestChain(chain.id)) {
415
+ throw new Error(`No ETHEREUM_HOSTS set but non anvil chain requested`);
416
+ }
417
+ if (PXE_URL) {
418
+ throw new Error(
419
+ `PXE_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`,
420
+ );
421
+ }
371
422
 
372
- // Enable logging metrics to a local file named after the test suite
373
- if (isMetricsLoggingRequested()) {
374
- const filename = path.join('log', getJobName() + '.jsonl');
375
- logger.info(`Logging metrics to ${filename}`);
376
- setupMetricsLogger(filename);
377
- }
423
+ const res = await startAnvil({
424
+ l1BlockTime: opts.ethereumSlotDuration,
425
+ accounts: opts.anvilAccounts,
426
+ port: opts.anvilPort,
427
+ });
428
+ anvil = res.anvil;
429
+ config.l1RpcUrls = [res.rpcUrl];
430
+ }
378
431
 
379
- const ethCheatCodes = new EthCheatCodesWithState(config.l1RpcUrls);
432
+ // Enable logging metrics to a local file named after the test suite
433
+ if (isMetricsLoggingRequested()) {
434
+ const filename = path.join('log', getJobName() + '.jsonl');
435
+ logger.info(`Logging metrics to ${filename}`);
436
+ setupMetricsLogger(filename);
437
+ }
380
438
 
381
- if (opts.stateLoad) {
382
- await ethCheatCodes.loadChainState(opts.stateLoad);
383
- }
439
+ const ethCheatCodes = new EthCheatCodesWithState(config.l1RpcUrls);
384
440
 
385
- if (opts.l1StartTime) {
386
- await ethCheatCodes.warp(opts.l1StartTime);
387
- }
441
+ if (opts.stateLoad) {
442
+ await ethCheatCodes.loadChainState(opts.stateLoad);
443
+ }
388
444
 
389
- let publisherPrivKey = undefined;
390
- let publisherHdAccount = undefined;
391
-
392
- if (config.publisherPrivateKey && config.publisherPrivateKey != NULL_KEY) {
393
- publisherHdAccount = privateKeyToAccount(config.publisherPrivateKey);
394
- } else if (!MNEMONIC) {
395
- throw new Error(`Mnemonic not provided and no publisher private key`);
396
- } else {
397
- publisherHdAccount = mnemonicToAccount(MNEMONIC, { addressIndex: 0 });
398
- const publisherPrivKeyRaw = publisherHdAccount.getHdKey().privateKey;
399
- publisherPrivKey = publisherPrivKeyRaw === null ? null : Buffer.from(publisherPrivKeyRaw);
400
- config.publisherPrivateKey = `0x${publisherPrivKey!.toString('hex')}`;
401
- }
445
+ if (opts.l1StartTime) {
446
+ await ethCheatCodes.warp(opts.l1StartTime, { resetBlockInterval: true });
447
+ }
402
448
 
403
- // Made as separate values such that keys can change, but for test they will be the same.
404
- config.validatorPrivateKey = config.publisherPrivateKey;
449
+ let publisherPrivKey = undefined;
450
+ let publisherHdAccount = undefined;
451
+
452
+ if (opts.l1PublisherKey && opts.l1PublisherKey.getValue() && opts.l1PublisherKey.getValue() != NULL_KEY) {
453
+ publisherHdAccount = privateKeyToAccount(opts.l1PublisherKey.getValue());
454
+ } else if (
455
+ config.publisherPrivateKeys &&
456
+ config.publisherPrivateKeys.length > 0 &&
457
+ config.publisherPrivateKeys[0].getValue() != NULL_KEY
458
+ ) {
459
+ publisherHdAccount = privateKeyToAccount(config.publisherPrivateKeys[0].getValue());
460
+ } else if (!MNEMONIC) {
461
+ throw new Error(`Mnemonic not provided and no publisher private key`);
462
+ } else {
463
+ publisherHdAccount = mnemonicToAccount(MNEMONIC, { addressIndex: 0 });
464
+ const publisherPrivKeyRaw = publisherHdAccount.getHdKey().privateKey;
465
+ publisherPrivKey = publisherPrivKeyRaw === null ? null : Buffer.from(publisherPrivKeyRaw);
466
+ config.publisherPrivateKeys = [new SecretValue(`0x${publisherPrivKey!.toString('hex')}` as const)];
467
+ }
405
468
 
406
- if (PXE_URL) {
407
- // we are setting up against a remote environment, l1 contracts are assumed to already be deployed
408
- return await setupWithRemoteEnvironment(publisherHdAccount!, config, logger, numberOfAccounts);
409
- }
469
+ config.coinbase = EthAddress.fromString(publisherHdAccount.address);
410
470
 
411
- // Blob sink service - blobs get posted here and served from here
412
- const blobSinkPort = await getPort();
413
- const blobSink = await createBlobSinkServer({ port: blobSinkPort });
414
- await blobSink.start();
415
- config.blobSinkUrl = `http://localhost:${blobSinkPort}`;
416
-
417
- const initialFundedAccounts =
418
- opts.initialFundedAccounts ??
419
- (await generateSchnorrAccounts(opts.numberOfInitialFundedAccounts ?? numberOfAccounts));
420
- const { genesisBlockHash, genesisArchiveRoot, prefilledPublicData } = await getGenesisValues(
421
- initialFundedAccounts.map(a => a.address),
422
- opts.initialAccountFeeJuice,
423
- opts.genesisPublicData,
424
- );
471
+ if (PXE_URL) {
472
+ // we are setting up against a remote environment, l1 contracts are assumed to already be deployed
473
+ return await setupWithRemoteEnvironment(publisherHdAccount!, config, logger, numberOfAccounts);
474
+ }
425
475
 
426
- const deployL1ContractsValues =
427
- opts.deployL1ContractsValues ??
428
- (await setupL1Contracts(
429
- config.l1RpcUrls,
430
- publisherHdAccount!,
431
- logger,
432
- { ...opts, genesisArchiveRoot, genesisBlockHash },
433
- chain,
434
- ));
476
+ const initialFundedAccounts =
477
+ opts.initialFundedAccounts ??
478
+ (await generateSchnorrAccounts(opts.numberOfInitialFundedAccounts ?? numberOfAccounts));
479
+ const { genesisArchiveRoot, prefilledPublicData, fundingNeeded } = await getGenesisValues(
480
+ initialFundedAccounts.map(a => a.address),
481
+ opts.initialAccountFeeJuice,
482
+ opts.genesisPublicData,
483
+ );
435
484
 
436
- config.l1Contracts = deployL1ContractsValues.l1ContractAddresses;
485
+ const wasAutomining = await ethCheatCodes.isAutoMining();
486
+ const enableAutomine = opts.automineL1Setup && !wasAutomining && isAnvilTestChain(chain.id);
487
+ if (enableAutomine) {
488
+ await ethCheatCodes.setAutomine(true);
489
+ }
437
490
 
438
- if (opts.fundRewardDistributor) {
439
- // Mints block rewards for 10000 blocks to the rewardDistributor contract
491
+ const l1Client = createExtendedL1Client(config.l1RpcUrls, publisherHdAccount!, chain);
492
+ await deployMulticall3(l1Client, logger);
493
+
494
+ const deployL1ContractsValues =
495
+ opts.deployL1ContractsValues ??
496
+ (await setupL1Contracts(
497
+ config.l1RpcUrls,
498
+ publisherHdAccount!,
499
+ logger,
500
+ {
501
+ ...opts,
502
+ genesisArchiveRoot,
503
+ feeJuicePortalInitialBalance: fundingNeeded,
504
+ initialValidators: opts.initialValidators,
505
+ },
506
+ chain,
507
+ ));
508
+
509
+ config.l1Contracts = deployL1ContractsValues.l1ContractAddresses;
510
+ config.rollupVersion = deployL1ContractsValues.rollupVersion;
511
+
512
+ if (opts.fundRewardDistributor) {
513
+ // Mints block rewards for 10000 blocks to the rewardDistributor contract
514
+
515
+ const rollup = new RollupContract(
516
+ deployL1ContractsValues.l1Client,
517
+ deployL1ContractsValues.l1ContractAddresses.rollupAddress,
518
+ );
440
519
 
441
- const rewardDistributor = getContract({
442
- address: deployL1ContractsValues.l1ContractAddresses.rewardDistributorAddress.toString(),
443
- abi: l1Artifacts.rewardDistributor.contractAbi,
444
- client: deployL1ContractsValues.publicClient,
445
- });
520
+ const blockReward = await rollup.getBlockReward();
521
+ const mintAmount = 10_000n * (blockReward as bigint);
446
522
 
447
- const blockReward = await rewardDistributor.read.BLOCK_REWARD();
448
- const mintAmount = 10_000n * (blockReward as bigint);
523
+ const feeJuice = getContract({
524
+ address: deployL1ContractsValues.l1ContractAddresses.feeJuiceAddress.toString(),
525
+ abi: FeeAssetArtifact.contractAbi,
526
+ client: deployL1ContractsValues.l1Client,
527
+ });
449
528
 
450
- const feeJuice = getContract({
451
- address: deployL1ContractsValues.l1ContractAddresses.feeJuiceAddress.toString(),
452
- abi: l1Artifacts.feeAsset.contractAbi,
453
- client: deployL1ContractsValues.walletClient,
454
- });
529
+ const rewardDistributorMintTxHash = await feeJuice.write.mint(
530
+ [deployL1ContractsValues.l1ContractAddresses.rewardDistributorAddress.toString(), mintAmount],
531
+ {} as any,
532
+ );
533
+ await deployL1ContractsValues.l1Client.waitForTransactionReceipt({ hash: rewardDistributorMintTxHash });
534
+ logger.info(`Funding rewardDistributor in ${rewardDistributorMintTxHash}`);
535
+ }
455
536
 
456
- const rewardDistributorMintTxHash = await feeJuice.write.mint([rewardDistributor.address, mintAmount], {} as any);
457
- await deployL1ContractsValues.publicClient.waitForTransactionReceipt({ hash: rewardDistributorMintTxHash });
458
- logger.info(`Funding rewardDistributor in ${rewardDistributorMintTxHash}`);
459
- }
537
+ if (enableAutomine) {
538
+ await ethCheatCodes.setAutomine(false);
539
+ await ethCheatCodes.setIntervalMining(config.ethereumSlotDuration);
540
+ }
460
541
 
461
- if (opts.l2StartTime) {
462
- // This should only be used in synching test or when you need to have a stable
463
- // timestamp for the first l2 block.
464
- await ethCheatCodes.warp(opts.l2StartTime);
465
- }
542
+ if (opts.l2StartTime) {
543
+ // This should only be used in synching test or when you need to have a stable
544
+ // timestamp for the first l2 block.
545
+ await ethCheatCodes.warp(opts.l2StartTime, { resetBlockInterval: true });
546
+ }
466
547
 
467
- const dateProvider = new TestDateProvider();
548
+ const dateProvider = new TestDateProvider();
549
+ dateProvider.setTime((await ethCheatCodes.timestamp()) * 1000);
468
550
 
469
- const watcher = new AnvilTestWatcher(
470
- new EthCheatCodesWithState(config.l1RpcUrls),
471
- deployL1ContractsValues.l1ContractAddresses.rollupAddress,
472
- deployL1ContractsValues.publicClient,
473
- dateProvider,
474
- );
551
+ const watcher = new AnvilTestWatcher(
552
+ new EthCheatCodesWithState(config.l1RpcUrls),
553
+ deployL1ContractsValues.l1ContractAddresses.rollupAddress,
554
+ deployL1ContractsValues.l1Client,
555
+ dateProvider,
556
+ );
557
+ if (!opts.disableAnvilTestWatcher) {
558
+ await watcher.start();
559
+ }
475
560
 
476
- await watcher.start();
561
+ const telemetry = getTelemetryClient(opts.telemetryConfig);
562
+
563
+ // Blob sink service - blobs get posted here and served from here
564
+ const blobSinkPort = await getPort();
565
+ const blobSink = await createBlobSinkServer(
566
+ {
567
+ l1ChainId: config.l1ChainId,
568
+ l1RpcUrls: config.l1RpcUrls,
569
+ l1Contracts: config.l1Contracts,
570
+ port: blobSinkPort,
571
+ dataDirectory: config.dataDirectory,
572
+ dataStoreMapSizeKb: config.dataStoreMapSizeKb,
573
+ },
574
+ telemetry,
575
+ );
576
+ await blobSink.start();
577
+ config.blobSinkUrl = `http://localhost:${blobSinkPort}`;
477
578
 
478
- logger.verbose('Creating and synching an aztec node...');
579
+ logger.verbose('Creating and synching an aztec node', config);
479
580
 
480
- const acvmConfig = await getACVMConfig(logger);
481
- if (acvmConfig) {
482
- config.acvmWorkingDirectory = acvmConfig.acvmWorkingDirectory;
483
- config.acvmBinaryPath = acvmConfig.acvmBinaryPath;
484
- }
581
+ const acvmConfig = await getACVMConfig(logger);
582
+ if (acvmConfig) {
583
+ config.acvmWorkingDirectory = acvmConfig.acvmWorkingDirectory;
584
+ config.acvmBinaryPath = acvmConfig.acvmBinaryPath;
585
+ }
485
586
 
486
- const bbConfig = await getBBConfig(logger);
487
- if (bbConfig) {
488
- config.bbBinaryPath = bbConfig.bbBinaryPath;
489
- config.bbWorkingDirectory = bbConfig.bbWorkingDirectory;
490
- }
491
- config.l1PublishRetryIntervalMS = 100;
587
+ const bbConfig = await getBBConfig(logger);
588
+ if (bbConfig) {
589
+ config.bbBinaryPath = bbConfig.bbBinaryPath;
590
+ config.bbWorkingDirectory = bbConfig.bbWorkingDirectory;
591
+ }
492
592
 
493
- const telemetry = getTelemetryClient(opts.telemetryConfig);
593
+ const blobSinkClient = createBlobSinkClient(config, { logger: createLogger('node:blob-sink:client') });
494
594
 
495
- const blobSinkClient = createBlobSinkClient(config);
496
- const aztecNode = await AztecNodeService.createAndSync(
497
- config,
498
- {
499
- dateProvider,
500
- blobSinkClient,
501
- },
502
- { prefilledPublicData },
503
- );
504
- const sequencer = aztecNode.getSequencer();
595
+ let mockGossipSubNetwork: MockGossipSubNetwork | undefined;
596
+ let p2pClientDeps: P2PClientDeps<P2PClientType.Full> | undefined = undefined;
505
597
 
506
- if (sequencer) {
507
- const publisher = (sequencer as TestSequencerClient).sequencer.publisher;
508
- publisher.l1TxUtils = DelayedTxUtils.fromL1TxUtils(publisher.l1TxUtils, config.ethereumSlotDuration);
509
- }
598
+ if (opts.mockGossipSubNetwork) {
599
+ mockGossipSubNetwork = new MockGossipSubNetwork();
600
+ p2pClientDeps = { p2pServiceFactory: getMockPubSubP2PServiceFactory(mockGossipSubNetwork) };
601
+ }
510
602
 
511
- let proverNode: ProverNode | undefined = undefined;
512
- if (opts.startProverNode) {
513
- logger.verbose('Creating and syncing a simulated prover node...');
514
- const proverNodePrivateKey = getPrivateKeyFromIndex(2);
515
- const proverNodePrivateKeyHex: Hex = `0x${proverNodePrivateKey!.toString('hex')}`;
516
- proverNode = await createAndSyncProverNode(
517
- proverNodePrivateKeyHex,
518
- config,
519
- aztecNode,
520
- path.join(directoryToCleanup, randomBytes(8).toString('hex')),
521
- );
522
- }
603
+ // Transactions built against the genesis state must be included in block 1, otherwise they are dropped.
604
+ // To avoid test failures from dropped transactions, we ensure progression beyond genesis before proceeding.
605
+ // For account deployments, we set minTxsPerBlock=1 and deploy accounts sequentially for guaranteed success.
606
+ // If no accounts need deployment, we await an empty block to confirm network progression. After either path
607
+ // completes, we restore the original minTxsPerBlock setting. The deployment and waiting for empty block is
608
+ // handled by the if-else branches on line 632.
609
+ // For more details on why the tx would be dropped see `validate_include_by_timestamp` function in
610
+ // `noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/components/validation_requests.nr`.
611
+ //
612
+ // Note: If the following seems too convoluted or if it starts making problems, we could drop the "progressing
613
+ // past genesis via an account contract deployment" optimization and just call flush() on the sequencer and wait
614
+ // for an empty block to be mined. This would simplify it all quite a bit but the setup would be slower for tests
615
+ // deploying accounts.
616
+ const originalMinTxsPerBlock = config.minTxsPerBlock;
617
+ if (originalMinTxsPerBlock === undefined) {
618
+ throw new Error('minTxsPerBlock is undefined in e2e test setup');
619
+ }
620
+ config.minTxsPerBlock = numberOfAccounts === 0 ? 0 : 1;
523
621
 
524
- logger.verbose('Creating a pxe...');
525
- const { pxe, teardown: pxeTeardown } = await setupPXEService(aztecNode!, pxeOpts, logger);
622
+ config.p2pEnabled = opts.mockGossipSubNetwork || config.p2pEnabled;
623
+ config.p2pIp = opts.p2pIp ?? config.p2pIp ?? '127.0.0.1';
526
624
 
527
- if (!config.skipProtocolContracts) {
528
- logger.verbose('Setting up Fee Juice...');
529
- await setupCanonicalFeeJuice(pxe);
530
- }
625
+ if (!config.disableValidator) {
626
+ if ((config.validatorPrivateKeys?.getValue().length ?? 0) === 0) {
627
+ config.validatorPrivateKeys = new SecretValue([generatePrivateKey()]);
628
+ }
629
+ }
531
630
 
532
- const accountManagers = await deployFundedSchnorrAccounts(pxe, initialFundedAccounts.slice(0, numberOfAccounts));
533
- const wallets = await Promise.all(accountManagers.map(account => account.getWallet()));
534
- if (initialFundedAccounts.length < numberOfAccounts) {
535
- // TODO: Create (numberOfAccounts - initialFundedAccounts.length) wallets without funds.
536
- throw new Error(
537
- `Unable to deploy ${numberOfAccounts} accounts. Only ${initialFundedAccounts.length} accounts were funded.`,
631
+ const aztecNode = await AztecNodeService.createAndSync(
632
+ config, // REFACTOR: createAndSync mutates this config
633
+ { dateProvider, blobSinkClient, telemetry, p2pClientDeps, logger: createLogger('node:MAIN-aztec-node') },
634
+ { prefilledPublicData },
538
635
  );
539
- }
540
-
541
- const cheatCodes = await CheatCodes.create(config.l1RpcUrls, pxe!);
542
-
543
- const teardown = async () => {
544
- await pxeTeardown();
636
+ const sequencerClient = aztecNode.getSequencer();
545
637
 
546
- if (aztecNode instanceof AztecNodeService) {
547
- await aztecNode?.stop();
638
+ if (sequencerClient) {
639
+ const publisher = (sequencerClient as TestSequencerClient).sequencer.publisher;
640
+ publisher.l1TxUtils = DelayedTxUtils.fromL1TxUtils(publisher.l1TxUtils, config.ethereumSlotDuration, l1Client);
548
641
  }
549
642
 
550
- if (proverNode) {
551
- await proverNode.stop();
643
+ let proverNode: ProverNode | undefined = undefined;
644
+ if (opts.startProverNode) {
645
+ logger.verbose('Creating and syncing a simulated prover node...');
646
+ const proverNodePrivateKey = getPrivateKeyFromIndex(2);
647
+ const proverNodePrivateKeyHex: Hex = `0x${proverNodePrivateKey!.toString('hex')}`;
648
+ const proverNodeDataDirectory = path.join(directoryToCleanup, randomBytes(8).toString('hex'));
649
+ const proverNodeConfig = { ...config.proverNodeConfig, dataDirectory: proverNodeDataDirectory };
650
+ proverNode = await createAndSyncProverNode(
651
+ proverNodePrivateKeyHex,
652
+ config,
653
+ proverNodeConfig,
654
+ aztecNode,
655
+ prefilledPublicData,
656
+ );
552
657
  }
553
658
 
554
- if (acvmConfig?.cleanup) {
555
- // remove the temp directory created for the acvm
556
- logger.verbose(`Cleaning up ACVM state`);
557
- await acvmConfig.cleanup();
659
+ logger.verbose('Creating a pxe...');
660
+ const { pxe, teardown: pxeTeardown } = await setupPXEService(aztecNode!, pxeOpts, logger);
661
+
662
+ const cheatCodes = await CheatCodes.create(config.l1RpcUrls, pxe!);
663
+
664
+ if (
665
+ (opts.aztecTargetCommitteeSize && opts.aztecTargetCommitteeSize > 0) ||
666
+ (opts.initialValidators && opts.initialValidators.length > 0)
667
+ ) {
668
+ // We need to advance such that the committee is set up.
669
+ await cheatCodes.rollup.advanceToEpoch((await cheatCodes.rollup.getEpoch()) + BigInt(config.lagInEpochs + 1), {
670
+ updateDateProvider: dateProvider,
671
+ });
672
+ await cheatCodes.rollup.setupEpoch();
673
+ await cheatCodes.rollup.debugRollup();
558
674
  }
559
675
 
560
- if (bbConfig?.cleanup) {
561
- // remove the temp directory created for the acvm
562
- logger.verbose(`Cleaning up BB state`);
563
- await bbConfig.cleanup();
676
+ // Below we continue with what we described in the long comment on line 571.
677
+ let accountManagers: AccountManager[] = [];
678
+ if (numberOfAccounts === 0) {
679
+ logger.info('No accounts are being deployed, waiting for an empty block 1 to be mined');
680
+ while ((await pxe.getBlockNumber()) === 0) {
681
+ await sleep(2000);
682
+ }
683
+ } else {
684
+ logger.info(
685
+ `${numberOfAccounts} accounts are being deployed. Reliably progressing past genesis by setting minTxsPerBlock to 1 and waiting for the accounts to be deployed`,
686
+ );
687
+ accountManagers = await deployFundedSchnorrAccounts(pxe, initialFundedAccounts.slice(0, numberOfAccounts));
564
688
  }
565
689
 
566
- await anvil?.stop().catch(err => getLogger().error(err));
567
- await watcher.stop();
568
- await blobSink?.stop();
690
+ // Now we restore the original minTxsPerBlock setting.
691
+ sequencerClient!.getSequencer().updateConfig({ minTxsPerBlock: originalMinTxsPerBlock });
569
692
 
570
- if (directoryToCleanup) {
693
+ const wallets = await Promise.all(accountManagers.map(account => account.getWallet()));
694
+ if (initialFundedAccounts.length < numberOfAccounts) {
695
+ // TODO: Create (numberOfAccounts - initialFundedAccounts.length) wallets without funds.
696
+ throw new Error(
697
+ `Unable to deploy ${numberOfAccounts} accounts. Only ${initialFundedAccounts.length} accounts were funded.`,
698
+ );
699
+ }
700
+
701
+ const teardown = async () => {
571
702
  try {
572
- logger.verbose(`Cleaning up data directory at ${directoryToCleanup}`);
573
- await fs.rm(directoryToCleanup, { recursive: true, force: true, maxRetries: 3 });
703
+ await pxeTeardown();
704
+
705
+ await tryStop(aztecNode, logger);
706
+ await tryStop(proverNode, logger);
707
+
708
+ if (acvmConfig?.cleanup) {
709
+ await acvmConfig.cleanup();
710
+ }
711
+
712
+ if (bbConfig?.cleanup) {
713
+ await bbConfig.cleanup();
714
+ }
715
+
716
+ await tryStop(watcher, logger);
717
+ await tryStop(anvil, logger);
718
+
719
+ await tryStop(blobSink, logger);
720
+ await tryRmDir(directoryToCleanup, logger);
574
721
  } catch (err) {
575
- logger.warn(`Failed to delete data directory at ${directoryToCleanup}: ${err}`);
722
+ logger.error(`Error during e2e test teardown`, err);
576
723
  }
577
- }
578
- };
724
+ };
579
725
 
580
- return {
581
- aztecNode,
582
- blobSink,
583
- cheatCodes,
584
- config,
585
- dateProvider,
586
- deployL1ContractsValues,
587
- initialFundedAccounts,
588
- logger,
589
- proverNode,
590
- pxe,
591
- sequencer,
592
- teardown,
593
- telemetryClient: telemetry,
594
- wallet: wallets[0],
595
- wallets,
596
- watcher,
597
- };
726
+ return {
727
+ aztecNode,
728
+ aztecNodeAdmin: aztecNode,
729
+ blobSink,
730
+ cheatCodes,
731
+ ethCheatCodes,
732
+ config,
733
+ dateProvider,
734
+ deployL1ContractsValues,
735
+ initialFundedAccounts,
736
+ logger,
737
+ mockGossipSubNetwork,
738
+ prefilledPublicData,
739
+ proverNode,
740
+ pxe,
741
+ sequencer: sequencerClient,
742
+ teardown,
743
+ telemetryClient: telemetry,
744
+ wallets,
745
+ wallet: wallets[0],
746
+ accounts: wallets.map(w => w.getAddress()),
747
+ watcher,
748
+ };
749
+ } catch (err) {
750
+ // TODO: Just hoisted anvil for now to ensure cleanup. Prob need to hoist the rest.
751
+ await anvil?.stop();
752
+ throw err;
753
+ }
598
754
  }
599
755
 
600
756
  /**
@@ -605,7 +761,7 @@ export async function setup(
605
761
  */
606
762
 
607
763
  // docs:start:public_deploy_accounts
608
- export async function ensureAccountsPubliclyDeployed(sender: Wallet, accountsToDeploy: Wallet[]) {
764
+ export async function ensureAccountContractsPublished(sender: Wallet, accountsToDeploy: Wallet[]) {
609
765
  // We have to check whether the accounts are already deployed. This can happen if the test runs against
610
766
  // the sandbox and the test accounts exist
611
767
  const accountsAndAddresses = await Promise.all(
@@ -613,7 +769,7 @@ export async function ensureAccountsPubliclyDeployed(sender: Wallet, accountsToD
613
769
  const address = account.getAddress();
614
770
  return {
615
771
  address,
616
- deployed: (await sender.getContractMetadata(address)).isContractPubliclyDeployed,
772
+ deployed: (await sender.getContractMetadata(address)).isContractPublished,
617
773
  };
618
774
  }),
619
775
  );
@@ -626,13 +782,13 @@ export async function ensureAccountsPubliclyDeployed(sender: Wallet, accountsToD
626
782
  ).map(contractMetadata => contractMetadata.contractInstance);
627
783
  const contractClass = await getContractClassFromArtifact(SchnorrAccountContractArtifact);
628
784
  if (!(await sender.getContractClassMetadata(contractClass.id, true)).isContractClassPubliclyRegistered) {
629
- await (await registerContractClass(sender, SchnorrAccountContractArtifact)).send().wait();
785
+ await (await publishContractClass(sender, SchnorrAccountContractArtifact))
786
+ .send({ from: accountsToDeploy[0].getAddress() })
787
+ .wait();
630
788
  }
631
- const requests = await Promise.all(
632
- instances.map(async instance => (await deployInstance(sender, instance!)).request()),
633
- );
634
- const batch = new BatchCall(sender, [...requests]);
635
- await batch.send().wait();
789
+ const requests = await Promise.all(instances.map(async instance => await publishInstance(sender, instance!)));
790
+ const batch = new BatchCall(sender, requests);
791
+ await batch.send({ from: accountsToDeploy[0].getAddress() }).wait();
636
792
  }
637
793
  // docs:end:public_deploy_accounts
638
794
 
@@ -672,11 +828,12 @@ export type BalancesFn = ReturnType<typeof getBalancesFn>;
672
828
  export function getBalancesFn(
673
829
  symbol: string,
674
830
  method: ContractMethod,
831
+ from: AztecAddress,
675
832
  logger: any,
676
833
  ): (...addresses: (AztecAddress | { address: AztecAddress })[]) => Promise<bigint[]> {
677
834
  const balances = async (...addressLikes: (AztecAddress | { address: AztecAddress })[]) => {
678
835
  const addresses = addressLikes.map(addressLike => ('address' in addressLike ? addressLike.address : addressLike));
679
- const b = await Promise.all(addresses.map(address => method(address).simulate()));
836
+ const b = await Promise.all(addresses.map(address => method(address).simulate({ from })));
680
837
  const debugString = `${symbol} balances: ${addresses.map((address, i) => `${address}: ${b[i]}`).join(', ')}`;
681
838
  logger.verbose(debugString);
682
839
  return b;
@@ -712,24 +869,47 @@ export async function expectMappingDelta<K, V extends number | bigint>(
712
869
  }
713
870
 
714
871
  /**
715
- * Deploy the protocol contracts to a running instance.
872
+ * Computes the address of the "canonical" SponosoredFPCContract. This is not a protocol contract
873
+ * but by conventions its address is computed with a salt of 0.
874
+ * @returns The address of the sponsored FPC contract
716
875
  */
717
- export async function setupCanonicalFeeJuice(pxe: PXE) {
718
- // "deploy" the Fee Juice as it contains public functions
719
- const feeJuicePortalAddress = (await pxe.getNodeInfo()).l1ContractAddresses.feeJuicePortalAddress;
720
- const wallet = new SignerlessWallet(pxe);
721
- const feeJuice = await FeeJuiceContract.at(ProtocolContractAddress.FeeJuice, wallet);
876
+ export function getSponsoredFPCInstance(): Promise<ContractInstanceWithAddress> {
877
+ return Promise.resolve(
878
+ getContractInstanceFromInstantiationParams(SponsoredFPCContract.artifact, {
879
+ salt: new Fr(SPONSORED_FPC_SALT),
880
+ }),
881
+ );
882
+ }
722
883
 
723
- try {
724
- const paymentMethod = new FeeJuicePaymentMethod(ProtocolContractAddress.FeeJuice);
725
- await feeJuice.methods
726
- .initialize(feeJuicePortalAddress, FEE_JUICE_INITIAL_MINT)
727
- .send({ fee: { paymentMethod, gasSettings: { teardownGasLimits: Gas.empty() } } })
728
- .wait();
729
- getLogger().info(`Fee Juice successfully setup. Portal address: ${feeJuicePortalAddress}`);
730
- } catch (error) {
731
- getLogger().warn(`Fee Juice might have already been setup. Got error: ${inspect(error)}.`);
732
- }
884
+ /**
885
+ * Computes the address of the "canonical" SponosoredFPCContract. This is not a protocol contract
886
+ * but by conventions its address is computed with a salt of 0.
887
+ * @returns The address of the sponsored FPC contract
888
+ */
889
+ export async function getSponsoredFPCAddress() {
890
+ const sponsoredFPCInstance = await getSponsoredFPCInstance();
891
+ return sponsoredFPCInstance.address;
892
+ }
893
+
894
+ /**
895
+ * Deploy a sponsored FPC contract to a running instance.
896
+ */
897
+ export async function setupSponsoredFPC(pxe: PXE) {
898
+ const instance = await getContractInstanceFromInstantiationParams(SponsoredFPCContract.artifact, {
899
+ salt: new Fr(SPONSORED_FPC_SALT),
900
+ });
901
+
902
+ await pxe.registerContract({ instance, artifact: SponsoredFPCContract.artifact });
903
+ getLogger().info(`SponsoredFPC: ${instance.address}`);
904
+ return instance;
905
+ }
906
+
907
+ /**
908
+ * Registers the SponsoredFPC in this PXE instance
909
+ * @param pxe - The pxe client
910
+ */
911
+ export async function registerSponsoredFPC(pxe: PXE): Promise<void> {
912
+ await pxe.registerContract({ instance: await getSponsoredFPCInstance(), artifact: SponsoredFPCContract.artifact });
733
913
  }
734
914
 
735
915
  export async function waitForProvenChain(node: AztecNode, targetBlock?: number, timeoutSec = 60, intervalSec = 1) {
@@ -743,81 +923,79 @@ export async function waitForProvenChain(node: AztecNode, targetBlock?: number,
743
923
  );
744
924
  }
745
925
 
746
- export async function createAndSyncProverNode(
926
+ export function createAndSyncProverNode(
747
927
  proverNodePrivateKey: `0x${string}`,
748
928
  aztecNodeConfig: AztecNodeConfig,
749
- aztecNode: AztecNode,
750
- dataDirectory: string,
929
+ proverNodeConfig: Partial<ProverNodeConfig> & Pick<DataStoreConfig, 'dataDirectory'> & { dontStart?: boolean },
930
+ aztecNode: AztecNode | undefined,
751
931
  prefilledPublicData: PublicDataTreeLeaf[] = [],
932
+ proverNodeDeps: ProverNodeDeps = {},
752
933
  ) {
753
- // Disable stopping the aztec node as the prover coordination test will kill it otherwise
754
- // This is only required when stopping the prover node for testing
755
- const aztecNodeWithoutStop = {
756
- getTxByHash: aztecNode.getTxByHash.bind(aztecNode),
757
- getTxsByHash: aztecNode.getTxsByHash.bind(aztecNode),
758
- stop: () => Promise.resolve(),
759
- };
934
+ return withLogNameSuffix('prover-node', async () => {
935
+ // Disable stopping the aztec node as the prover coordination test will kill it otherwise
936
+ // This is only required when stopping the prover node for testing
937
+ const aztecNodeTxProvider = aztecNode && {
938
+ getTxByHash: aztecNode.getTxByHash.bind(aztecNode),
939
+ getTxsByHash: aztecNode.getTxsByHash.bind(aztecNode),
940
+ stop: () => Promise.resolve(),
941
+ };
942
+
943
+ const blobSinkClient = createBlobSinkClient(aztecNodeConfig);
944
+
945
+ // Creating temp store and archiver for simulated prover node
946
+ const archiverConfig = { ...aztecNodeConfig, dataDirectory: proverNodeConfig.dataDirectory };
947
+ const archiver = await createArchiver(archiverConfig, { blobSinkClient }, { blockUntilSync: true });
948
+
949
+ // Prover node config is for simulated proofs
950
+ const proverConfig: ProverNodeConfig = {
951
+ ...aztecNodeConfig,
952
+ txCollectionNodeRpcUrls: [],
953
+ realProofs: false,
954
+ proverAgentCount: 2,
955
+ publisherPrivateKeys: [new SecretValue(proverNodePrivateKey)],
956
+ proverNodeMaxPendingJobs: 10,
957
+ proverNodeMaxParallelBlocksPerEpoch: 32,
958
+ proverNodePollingIntervalMs: 200,
959
+ txGatheringIntervalMs: 1000,
960
+ txGatheringBatchSize: 10,
961
+ txGatheringMaxParallelRequestsPerNode: 10,
962
+ txGatheringTimeoutMs: 24_000,
963
+ proverNodeFailedEpochStore: undefined,
964
+ proverId: EthAddress.fromNumber(1),
965
+ proverNodeEpochProvingDelayMs: undefined,
966
+ ...proverNodeConfig,
967
+ };
968
+
969
+ const l1TxUtils = createDelayedL1TxUtils(
970
+ aztecNodeConfig,
971
+ proverNodePrivateKey,
972
+ 'prover-node',
973
+ proverNodeDeps.dateProvider,
974
+ );
760
975
 
761
- const blobSinkClient = createBlobSinkClient(aztecNodeConfig);
762
- // Creating temp store and archiver for simulated prover node
763
- const archiverConfig = { ...aztecNodeConfig, dataDirectory };
764
- const archiver = await createArchiver(archiverConfig, blobSinkClient, {
765
- blockUntilSync: true,
976
+ const proverNode = await createProverNode(
977
+ proverConfig,
978
+ { ...proverNodeDeps, aztecNodeTxProvider, archiver: archiver as Archiver, l1TxUtils },
979
+ { prefilledPublicData },
980
+ );
981
+ getLogger().info(`Created and synced prover node`, { publisherAddress: l1TxUtils.client.account!.address });
982
+ if (!proverNodeConfig.dontStart) {
983
+ await proverNode.start();
984
+ }
985
+ return proverNode;
766
986
  });
767
-
768
- // Prover node config is for simulated proofs
769
- const proverConfig: ProverNodeConfig = {
770
- ...aztecNodeConfig,
771
- proverCoordinationNodeUrl: undefined,
772
- dataDirectory: undefined,
773
- realProofs: false,
774
- proverAgentCount: 2,
775
- publisherPrivateKey: proverNodePrivateKey,
776
- proverNodeMaxPendingJobs: 10,
777
- proverNodeMaxParallelBlocksPerEpoch: 32,
778
- proverNodePollingIntervalMs: 200,
779
- txGatheringTimeoutMs: 60000,
780
- txGatheringIntervalMs: 1000,
781
- txGatheringMaxParallelRequests: 100,
782
- };
783
-
784
- const l1TxUtils = createDelayedL1TxUtils(aztecNodeConfig, proverNodePrivateKey, 'prover-node');
785
-
786
- const proverNode = await createProverNode(
787
- proverConfig,
788
- {
789
- aztecNodeTxProvider: aztecNodeWithoutStop,
790
- archiver: archiver as Archiver,
791
- l1TxUtils,
792
- },
793
- { prefilledPublicData },
794
- );
795
- getLogger().info(`Created and synced prover node`, { publisherAddress: l1TxUtils.walletClient.account.address });
796
- proverNode.start();
797
- return proverNode;
798
987
  }
799
988
 
800
- function createDelayedL1TxUtils(aztecNodeConfig: AztecNodeConfig, privateKey: `0x${string}`, logName: string) {
801
- const { publicClient, walletClient } = createL1Clients(aztecNodeConfig.l1RpcUrls, privateKey, foundry);
989
+ function createDelayedL1TxUtils(
990
+ aztecNodeConfig: AztecNodeConfig,
991
+ privateKey: `0x${string}`,
992
+ logName: string,
993
+ dateProvider?: DateProvider,
994
+ ) {
995
+ const l1Client = createExtendedL1Client(aztecNodeConfig.l1RpcUrls, privateKey, foundry);
802
996
 
803
997
  const log = createLogger(logName);
804
- const l1TxUtils = new DelayedTxUtils(publicClient, walletClient, log, aztecNodeConfig);
998
+ const l1TxUtils = createDelayedL1TxUtilsFromViemWallet(l1Client, log, dateProvider, aztecNodeConfig);
805
999
  l1TxUtils.enableDelayer(aztecNodeConfig.ethereumSlotDuration);
806
1000
  return l1TxUtils;
807
1001
  }
808
-
809
- export async function createForwarderContract(
810
- aztecNodeConfig: AztecNodeConfig,
811
- privateKey: `0x${string}`,
812
- rollupAddress: Hex,
813
- ) {
814
- const { walletClient, publicClient } = createL1Clients(aztecNodeConfig.l1RpcUrls, privateKey, foundry);
815
- const forwarderContract = await ForwarderContract.create(
816
- walletClient.account.address,
817
- walletClient,
818
- publicClient,
819
- createLogger('forwarder'),
820
- rollupAddress,
821
- );
822
- return forwarderContract;
823
- }