@aztec/aztec 0.0.1-commit.b655e406 → 0.0.1-commit.b9865e97

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 (190) hide show
  1. package/README.md +1 -1
  2. package/dest/bin/index.d.ts +1 -1
  3. package/dest/bin/index.js +13 -6
  4. package/dest/cli/admin_api_key_store.d.ts +45 -0
  5. package/dest/cli/admin_api_key_store.d.ts.map +1 -0
  6. package/dest/cli/admin_api_key_store.js +98 -0
  7. package/dest/cli/aztec_start_action.d.ts +1 -1
  8. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  9. package/dest/cli/aztec_start_action.js +90 -31
  10. package/dest/cli/aztec_start_options.d.ts +2 -2
  11. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  12. package/dest/cli/aztec_start_options.js +60 -53
  13. package/dest/cli/cli.d.ts +1 -1
  14. package/dest/cli/cli.js +7 -7
  15. package/dest/cli/cmds/compile.d.ts +4 -0
  16. package/dest/cli/cmds/compile.d.ts.map +1 -0
  17. package/dest/cli/cmds/compile.js +166 -0
  18. package/dest/cli/cmds/migrate_ha_db.d.ts +3 -0
  19. package/dest/cli/cmds/migrate_ha_db.d.ts.map +1 -0
  20. package/dest/cli/cmds/migrate_ha_db.js +27 -0
  21. package/dest/cli/cmds/profile.d.ts +4 -0
  22. package/dest/cli/cmds/profile.d.ts.map +1 -0
  23. package/dest/cli/cmds/profile.js +8 -0
  24. package/dest/cli/cmds/profile_flamegraph.d.ts +4 -0
  25. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -0
  26. package/dest/cli/cmds/profile_flamegraph.js +52 -0
  27. package/dest/cli/cmds/profile_gates.d.ts +4 -0
  28. package/dest/cli/cmds/profile_gates.d.ts.map +1 -0
  29. package/dest/cli/cmds/profile_gates.js +76 -0
  30. package/dest/cli/cmds/profile_utils.d.ts +18 -0
  31. package/dest/cli/cmds/profile_utils.d.ts.map +1 -0
  32. package/dest/cli/cmds/profile_utils.js +50 -0
  33. package/dest/cli/cmds/standby.d.ts +30 -0
  34. package/dest/cli/cmds/standby.d.ts.map +1 -0
  35. package/dest/cli/cmds/standby.js +97 -0
  36. package/dest/cli/cmds/start_bot.d.ts +3 -3
  37. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  38. package/dest/cli/cmds/start_bot.js +13 -9
  39. package/dest/cli/cmds/start_node.d.ts +3 -2
  40. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  41. package/dest/cli/cmds/start_node.js +79 -39
  42. package/dest/cli/cmds/start_p2p_bootstrap.d.ts +2 -2
  43. package/dest/cli/cmds/start_p2p_bootstrap.d.ts.map +1 -1
  44. package/dest/cli/cmds/start_p2p_bootstrap.js +2 -3
  45. package/dest/cli/cmds/start_prover_agent.d.ts +1 -1
  46. package/dest/cli/cmds/start_prover_agent.d.ts.map +1 -1
  47. package/dest/cli/cmds/start_prover_agent.js +8 -20
  48. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  49. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  50. package/dest/cli/cmds/start_prover_broker.js +25 -16
  51. package/dest/cli/cmds/start_txe.d.ts +2 -2
  52. package/dest/cli/cmds/start_txe.d.ts.map +1 -1
  53. package/dest/cli/cmds/start_txe.js +6 -5
  54. package/dest/cli/cmds/utils/artifacts.d.ts +21 -0
  55. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -0
  56. package/dest/cli/cmds/utils/artifacts.js +24 -0
  57. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts +21 -0
  58. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts.map +1 -0
  59. package/dest/cli/cmds/utils/collect_crate_dirs.js +114 -0
  60. package/dest/cli/cmds/utils/needs_recompile.d.ts +10 -0
  61. package/dest/cli/cmds/utils/needs_recompile.d.ts.map +1 -0
  62. package/dest/cli/cmds/utils/needs_recompile.js +90 -0
  63. package/dest/cli/cmds/utils/spawn.d.ts +3 -0
  64. package/dest/cli/cmds/utils/spawn.d.ts.map +1 -0
  65. package/dest/cli/cmds/utils/spawn.js +16 -0
  66. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts +4 -0
  67. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts.map +1 -0
  68. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.js +61 -0
  69. package/dest/cli/index.d.ts +1 -1
  70. package/dest/cli/preload_crs.d.ts +1 -1
  71. package/dest/cli/util.d.ts +12 -23
  72. package/dest/cli/util.d.ts.map +1 -1
  73. package/dest/cli/util.js +57 -91
  74. package/dest/cli/versioning.d.ts +1 -1
  75. package/dest/examples/token.d.ts +1 -1
  76. package/dest/examples/token.js +10 -10
  77. package/dest/examples/util.d.ts +2 -2
  78. package/dest/examples/util.d.ts.map +1 -1
  79. package/dest/index.d.ts +2 -2
  80. package/dest/index.d.ts.map +1 -1
  81. package/dest/index.js +1 -1
  82. package/dest/local-network/auth_registry.d.ts +5 -0
  83. package/dest/local-network/auth_registry.d.ts.map +1 -0
  84. package/dest/local-network/auth_registry.js +17 -0
  85. package/dest/local-network/banana_fpc.d.ts +11 -0
  86. package/dest/local-network/banana_fpc.d.ts.map +1 -0
  87. package/dest/{sandbox → local-network}/banana_fpc.js +14 -10
  88. package/dest/local-network/index.d.ts +4 -0
  89. package/dest/local-network/index.d.ts.map +1 -0
  90. package/dest/{sandbox → local-network}/index.js +1 -1
  91. package/dest/local-network/local-network.d.ts +50 -0
  92. package/dest/local-network/local-network.d.ts.map +1 -0
  93. package/dest/local-network/local-network.js +248 -0
  94. package/dest/local-network/sponsored_fpc.d.ts +5 -0
  95. package/dest/local-network/sponsored_fpc.d.ts.map +1 -0
  96. package/dest/mnemonic.d.ts +1 -1
  97. package/dest/splash.d.ts +1 -1
  98. package/dest/testing/anvil_test_watcher.d.ts +26 -6
  99. package/dest/testing/anvil_test_watcher.d.ts.map +1 -1
  100. package/dest/testing/anvil_test_watcher.js +128 -35
  101. package/dest/testing/cheat_codes.d.ts +18 -17
  102. package/dest/testing/cheat_codes.d.ts.map +1 -1
  103. package/dest/testing/cheat_codes.js +72 -36
  104. package/dest/testing/epoch_test_settler.d.ts +19 -0
  105. package/dest/testing/epoch_test_settler.d.ts.map +1 -0
  106. package/dest/testing/epoch_test_settler.js +63 -0
  107. package/dest/testing/index.d.ts +4 -2
  108. package/dest/testing/index.d.ts.map +1 -1
  109. package/dest/testing/index.js +2 -0
  110. package/dest/testing/token_allowed_setup.d.ts +7 -0
  111. package/dest/testing/token_allowed_setup.d.ts.map +1 -0
  112. package/dest/testing/token_allowed_setup.js +20 -0
  113. package/package.json +42 -37
  114. package/scripts/add_crate.sh +53 -0
  115. package/scripts/aztec.sh +73 -0
  116. package/scripts/init.sh +39 -0
  117. package/scripts/new.sh +83 -0
  118. package/scripts/setup_workspace.sh +69 -0
  119. package/scripts/templates/blank/contract/Nargo.toml +6 -0
  120. package/scripts/templates/blank/contract/src/main.nr +10 -0
  121. package/scripts/templates/blank/test/Nargo.toml +7 -0
  122. package/scripts/templates/blank/test/src/lib.nr +11 -0
  123. package/scripts/templates/counter/contract/Nargo.toml +7 -0
  124. package/scripts/templates/counter/contract/src/main.nr +48 -0
  125. package/scripts/templates/counter/test/Nargo.toml +7 -0
  126. package/scripts/templates/counter/test/src/lib.nr +32 -0
  127. package/src/bin/index.ts +14 -6
  128. package/src/cli/admin_api_key_store.ts +128 -0
  129. package/src/cli/aztec_start_action.ts +83 -26
  130. package/src/cli/aztec_start_options.ts +68 -59
  131. package/src/cli/cli.ts +11 -11
  132. package/src/cli/cmds/compile.ts +192 -0
  133. package/src/cli/cmds/migrate_ha_db.ts +43 -0
  134. package/src/cli/cmds/profile.ts +26 -0
  135. package/src/cli/cmds/profile_flamegraph.ts +64 -0
  136. package/src/cli/cmds/profile_gates.ts +84 -0
  137. package/src/cli/cmds/profile_utils.ts +58 -0
  138. package/src/cli/cmds/standby.ts +132 -0
  139. package/src/cli/cmds/start_bot.ts +12 -11
  140. package/src/cli/cmds/start_node.ts +90 -44
  141. package/src/cli/cmds/start_p2p_bootstrap.ts +3 -3
  142. package/src/cli/cmds/start_prover_agent.ts +9 -20
  143. package/src/cli/cmds/start_prover_broker.ts +29 -26
  144. package/src/cli/cmds/start_txe.ts +7 -5
  145. package/src/cli/cmds/utils/artifacts.ts +44 -0
  146. package/src/cli/cmds/utils/collect_crate_dirs.ts +118 -0
  147. package/src/cli/cmds/utils/needs_recompile.ts +98 -0
  148. package/src/cli/cmds/utils/spawn.ts +16 -0
  149. package/src/cli/cmds/utils/warn_if_aztec_version_mismatch.ts +76 -0
  150. package/src/cli/util.ts +66 -104
  151. package/src/examples/token.ts +11 -11
  152. package/src/examples/util.ts +1 -1
  153. package/src/index.ts +2 -2
  154. package/src/local-network/auth_registry.ts +19 -0
  155. package/src/{sandbox → local-network}/banana_fpc.ts +17 -9
  156. package/src/{sandbox → local-network}/index.ts +1 -1
  157. package/src/local-network/local-network.ts +303 -0
  158. package/src/{sandbox → local-network}/sponsored_fpc.ts +3 -2
  159. package/src/testing/anvil_test_watcher.ts +142 -33
  160. package/src/testing/cheat_codes.ts +92 -38
  161. package/src/testing/epoch_test_settler.ts +69 -0
  162. package/src/testing/index.ts +3 -1
  163. package/src/testing/token_allowed_setup.ts +19 -0
  164. package/dest/cli/cmds/start_archiver.d.ts +0 -9
  165. package/dest/cli/cmds/start_archiver.d.ts.map +0 -1
  166. package/dest/cli/cmds/start_archiver.js +0 -50
  167. package/dest/cli/cmds/start_blob_sink.d.ts +0 -3
  168. package/dest/cli/cmds/start_blob_sink.d.ts.map +0 -1
  169. package/dest/cli/cmds/start_blob_sink.js +0 -33
  170. package/dest/cli/cmds/start_prover_node.d.ts +0 -7
  171. package/dest/cli/cmds/start_prover_node.d.ts.map +0 -1
  172. package/dest/cli/cmds/start_prover_node.js +0 -108
  173. package/dest/cli/release_version.d.ts +0 -2
  174. package/dest/cli/release_version.d.ts.map +0 -1
  175. package/dest/cli/release_version.js +0 -14
  176. package/dest/sandbox/banana_fpc.d.ts +0 -10
  177. package/dest/sandbox/banana_fpc.d.ts.map +0 -1
  178. package/dest/sandbox/index.d.ts +0 -4
  179. package/dest/sandbox/index.d.ts.map +0 -1
  180. package/dest/sandbox/sandbox.d.ts +0 -74
  181. package/dest/sandbox/sandbox.d.ts.map +0 -1
  182. package/dest/sandbox/sandbox.js +0 -183
  183. package/dest/sandbox/sponsored_fpc.d.ts +0 -4
  184. package/dest/sandbox/sponsored_fpc.d.ts.map +0 -1
  185. package/src/cli/cmds/start_archiver.ts +0 -61
  186. package/src/cli/cmds/start_blob_sink.ts +0 -57
  187. package/src/cli/cmds/start_prover_node.ts +0 -124
  188. package/src/cli/release_version.ts +0 -21
  189. package/src/sandbox/sandbox.ts +0 -242
  190. /package/dest/{sandbox → local-network}/sponsored_fpc.js +0 -0
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env -S node --no-warnings
2
+ import { getInitialTestAccountsData } from '@aztec/accounts/testing';
3
+ import { AztecNodeService } from '@aztec/aztec-node';
4
+ import { type AztecNodeConfig, getConfigEnvVars } from '@aztec/aztec-node/config';
5
+ import { Fr } from '@aztec/aztec.js/fields';
6
+ import { createLogger } from '@aztec/aztec.js/log';
7
+ import { type BlobClientInterface, createBlobClient } from '@aztec/blob-client/client';
8
+ import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
9
+ import { createEthereumChain } from '@aztec/ethereum/chain';
10
+ import { waitForPublicClient } from '@aztec/ethereum/client';
11
+ import { getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
12
+ import { NULL_KEY } from '@aztec/ethereum/constants';
13
+ import { deployAztecL1Contracts } from '@aztec/ethereum/deploy-aztec-l1-contracts';
14
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
15
+ import { EthCheatCodes } from '@aztec/ethereum/test';
16
+ import { SecretValue } from '@aztec/foundation/config';
17
+ import { EthAddress } from '@aztec/foundation/eth-address';
18
+ import type { LogFn } from '@aztec/foundation/log';
19
+ import { DateProvider, TestDateProvider } from '@aztec/foundation/timer';
20
+ import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
21
+ import { protocolContractsHash } from '@aztec/protocol-contracts';
22
+ import { SequencerState } from '@aztec/sequencer-client';
23
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
24
+ import type { ProvingJobBroker } from '@aztec/stdlib/interfaces/server';
25
+ import { TxStatus } from '@aztec/stdlib/tx';
26
+ import type { GenesisData } from '@aztec/stdlib/world-state';
27
+ import {
28
+ type TelemetryClient,
29
+ getConfigEnvVars as getTelemetryClientConfig,
30
+ initTelemetryClient,
31
+ } from '@aztec/telemetry-client';
32
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
33
+ import { deployFundedSchnorrAccounts } from '@aztec/wallets/testing';
34
+ import { getGenesisValues } from '@aztec/world-state/testing';
35
+
36
+ import { type Hex, createPublicClient, fallback, http as httpViemTransport } from 'viem';
37
+ import { mnemonicToAccount, privateKeyToAddress } from 'viem/accounts';
38
+ import { foundry } from 'viem/chains';
39
+
40
+ import { createAccountLogs } from '../cli/util.js';
41
+ import { DefaultMnemonic } from '../mnemonic.js';
42
+ import { AnvilTestWatcher } from '../testing/anvil_test_watcher.js';
43
+ import { EpochTestSettler } from '../testing/epoch_test_settler.js';
44
+ import { getTokenAllowedSetupFunctions } from '../testing/token_allowed_setup.js';
45
+ import { publishStandardAuthRegistry } from './auth_registry.js';
46
+ import { getBananaFPCAddress, setupBananaFPC } from './banana_fpc.js';
47
+ import { getSponsoredFPCAddress } from './sponsored_fpc.js';
48
+
49
+ const logger = createLogger('local-network');
50
+
51
+ // The embedded wallet defaults to waiting for PROPOSED, which returns as soon as a tx lands in a
52
+ // proposed L2 block. That is flaky for the serial sandbox setup below: a proposed block can be
53
+ // pruned before its checkpoint is published, dropping a tx we already moved on from ("Tx dropped by
54
+ // P2P node"). Wait for the checkpoint so each setup tx is durably included before the next is sent.
55
+ const setupWaitOpts = { waitForStatus: TxStatus.CHECKPOINTED };
56
+
57
+ const localAnvil = foundry;
58
+
59
+ /**
60
+ * Function to deploy our L1 contracts to the local network L1
61
+ * @param aztecNodeConfig - The Aztec Node Config
62
+ * @param hdAccount - Account for publishing L1 contracts
63
+ */
64
+ export async function deployContractsToL1(
65
+ aztecNodeConfig: AztecNodeConfig,
66
+ privateKey: Hex,
67
+ opts: {
68
+ genesisArchiveRoot?: Fr;
69
+ feeJuicePortalInitialBalance?: bigint;
70
+ } = {},
71
+ ): Promise<L1ContractAddresses> {
72
+ await waitForPublicClient(aztecNodeConfig);
73
+
74
+ const l1Contracts = await deployAztecL1Contracts(aztecNodeConfig.l1RpcUrls[0], privateKey, foundry.id, {
75
+ ...getL1ContractsConfigEnvVars(), // TODO: We should not need to be loading config from env again, caller should handle this
76
+ ...aztecNodeConfig,
77
+ vkTreeRoot: getVKTreeRoot(),
78
+ protocolContractsHash,
79
+ genesisArchiveRoot: opts.genesisArchiveRoot ?? new Fr(GENESIS_ARCHIVE_ROOT),
80
+ feeJuicePortalInitialBalance: opts.feeJuicePortalInitialBalance,
81
+ aztecTargetCommitteeSize: 0, // no committee in local network
82
+ slasherEnabled: false, // no slashing in local network
83
+ realVerifier: false,
84
+ });
85
+
86
+ Object.assign(aztecNodeConfig, l1Contracts.l1ContractAddresses);
87
+ aztecNodeConfig.rollupVersion = l1Contracts.rollupVersion;
88
+
89
+ return l1Contracts.l1ContractAddresses;
90
+ }
91
+
92
+ /** Local network settings. */
93
+ export type LocalNetworkConfig = AztecNodeConfig & {
94
+ /** Mnemonic used to derive the L1 deployer private key.*/
95
+ l1Mnemonic: string;
96
+ /** Whether to deploy test accounts on local network start.*/
97
+ testAccounts: boolean;
98
+ };
99
+
100
+ /**
101
+ * Create and start a new Aztec Node and PXE. Deploys L1 contracts.
102
+ * Does not start any HTTP services nor populate any initial accounts.
103
+ * @param config - Optional local network settings.
104
+ */
105
+ export async function createLocalNetwork(config: Partial<LocalNetworkConfig> = {}, userLog: LogFn) {
106
+ // local network is meant for test envs. We should only need one l1RpcUrl
107
+ const l1RpcUrl = config.l1RpcUrls?.[0];
108
+ if (!l1RpcUrl) {
109
+ throw new Error('An L1 RPC URL is required');
110
+ }
111
+ if ((config.l1RpcUrls?.length || 0) > 1) {
112
+ logger.warn(`Multiple L1 RPC URLs provided. Local networks will only use the first one: ${l1RpcUrl}`);
113
+ }
114
+
115
+ // The local network deploys a banana FPC with Token contracts, so include Token entries
116
+ // in the setup allowlist so FPC-based fee payments work out of the box.
117
+ const tokenAllowList = await getTokenAllowedSetupFunctions();
118
+
119
+ const aztecNodeConfig: AztecNodeConfig = {
120
+ ...getConfigEnvVars(),
121
+ ...config,
122
+ txPublicSetupAllowListExtend: [...tokenAllowList, ...(config.txPublicSetupAllowListExtend ?? [])],
123
+ };
124
+ const hdAccount = mnemonicToAccount(config.l1Mnemonic || DefaultMnemonic);
125
+ if (
126
+ aztecNodeConfig.sequencerPublisherPrivateKeys == undefined ||
127
+ !aztecNodeConfig.sequencerPublisherPrivateKeys.length ||
128
+ aztecNodeConfig.sequencerPublisherPrivateKeys[0].getValue() === NULL_KEY
129
+ ) {
130
+ const privKey = hdAccount.getHdKey().privateKey;
131
+ aztecNodeConfig.sequencerPublisherPrivateKeys = [
132
+ new SecretValue(`0x${Buffer.from(privKey!).toString('hex')}` as const),
133
+ ];
134
+ }
135
+ if (!aztecNodeConfig.validatorPrivateKeys?.getValue().length) {
136
+ const privKey = hdAccount.getHdKey().privateKey;
137
+ aztecNodeConfig.validatorPrivateKeys = new SecretValue([`0x${Buffer.from(privKey!).toString('hex')}`]);
138
+ }
139
+ aztecNodeConfig.coinbase = EthAddress.fromString(
140
+ privateKeyToAddress(aztecNodeConfig.validatorPrivateKeys.getValue()[0]),
141
+ );
142
+
143
+ const initialAccounts = await (async () => {
144
+ if (config.testAccounts === true || config.testAccounts === undefined) {
145
+ if (aztecNodeConfig.p2pEnabled) {
146
+ userLog(`Not setting up test accounts as we are connecting to a network`);
147
+ } else {
148
+ userLog(`Setting up test accounts`);
149
+ return await getInitialTestAccountsData();
150
+ }
151
+ }
152
+ return [];
153
+ })();
154
+
155
+ const bananaFPC = await getBananaFPCAddress(initialAccounts);
156
+ const sponsoredFPC = await getSponsoredFPCAddress();
157
+ const prefundAddresses = (aztecNodeConfig.prefundAddresses ?? []).map(a => AztecAddress.fromString(a));
158
+ const fundedAddresses = [
159
+ ...initialAccounts.map(a => a.address),
160
+ ...(initialAccounts.length ? [bananaFPC, sponsoredFPC] : []),
161
+ ...prefundAddresses,
162
+ ];
163
+ const { genesisArchiveRoot, genesis, fundingNeeded } = await getGenesisValues(fundedAddresses);
164
+
165
+ const dateProvider = new TestDateProvider();
166
+
167
+ let cheatcodes: EthCheatCodes | undefined;
168
+ let rollupAddress: EthAddress | undefined;
169
+ let watcher: AnvilTestWatcher | undefined;
170
+ if (!aztecNodeConfig.p2pEnabled) {
171
+ ({ rollupAddress } = await deployContractsToL1(
172
+ aztecNodeConfig,
173
+ aztecNodeConfig.validatorPrivateKeys.getValue()[0],
174
+ {
175
+ genesisArchiveRoot,
176
+ feeJuicePortalInitialBalance: fundingNeeded,
177
+ },
178
+ ));
179
+
180
+ const chain =
181
+ aztecNodeConfig.l1RpcUrls.length > 0
182
+ ? createEthereumChain([l1RpcUrl], aztecNodeConfig.l1ChainId)
183
+ : { chainInfo: localAnvil };
184
+
185
+ const publicClient = createPublicClient({
186
+ chain: chain.chainInfo,
187
+ transport: fallback([httpViemTransport(l1RpcUrl)]) as any,
188
+ });
189
+
190
+ cheatcodes = new EthCheatCodes([l1RpcUrl], dateProvider);
191
+
192
+ watcher = new AnvilTestWatcher(cheatcodes, rollupAddress, publicClient, dateProvider);
193
+ watcher.setisLocalNetwork(true);
194
+ watcher.setIsMarkingAsProven(false); // Do not mark as proven in the watcher. It's marked in the epochTestSettler after the out hash is set.
195
+
196
+ await watcher.start();
197
+ }
198
+
199
+ const telemetry = await initTelemetryClient(getTelemetryClientConfig());
200
+ // Create a local blob client client inside the local network, no http connectivity
201
+ const blobClient = createBlobClient();
202
+ const node = await createAztecNode(aztecNodeConfig, { telemetry, blobClient, dateProvider }, { genesis });
203
+
204
+ // Now that the node is up, let the watcher check for pending txs so it can skip unfilled slots faster when
205
+ // transactions are waiting in the mempool. Also let it check if the sequencer is actively building, to avoid
206
+ // warping time out from under an in-progress block.
207
+ watcher?.setGetPendingTxCount(() => node.getPendingTxCount());
208
+ const sequencer = node.getSequencer()?.getSequencer();
209
+ if (sequencer) {
210
+ const idleStates: Set<string> = new Set([
211
+ SequencerState.STOPPED,
212
+ SequencerState.STOPPING,
213
+ SequencerState.IDLE,
214
+ SequencerState.SYNCHRONIZING,
215
+ ]);
216
+ watcher?.setIsSequencerBuilding(() => !idleStates.has(sequencer.getState()));
217
+ // Under proposer pipelining the L1 publish for slot N happens during wall-clock slot N,
218
+ // but the proposer for slot N has already built the checkpoint during slot N-1 and is
219
+ // waiting for L1 to advance. We need to fast-forward L1 to wake that wait — and the wait
220
+ // we have to break first is `waitForValidParentCheckpointOnL1`, which blocks the
221
+ // checkpoint_proposal_job's background submission task until the archiver has synced past
222
+ // the build slot. That wait happens *before* `PUBLISHING_CHECKPOINT` is set, so a hook on
223
+ // that state transition would be circular (L1 has to advance before the state we'd use to
224
+ // advance L1 fires). The earliest pre-wait signal is `block-proposed`, which the sequencer
225
+ // emits once each block is built. In sandbox single-block-per-slot mode this is
226
+ // effectively "checkpoint built", and the watcher warp is harmless if a subsequent
227
+ // assembly/validation/parent-wait step aborts: L1 just sits one slot ahead, which the
228
+ // cascade absorbs.
229
+ if (watcher) {
230
+ sequencer.on('block-proposed', ({ slot }) => watcher!.setProposedTargetSlot(Number(slot)));
231
+ }
232
+ }
233
+
234
+ let epochTestSettler: EpochTestSettler | undefined;
235
+ if (!aztecNodeConfig.p2pEnabled) {
236
+ epochTestSettler = new EpochTestSettler(
237
+ cheatcodes!,
238
+ rollupAddress!,
239
+ node.getBlockSource(),
240
+ logger.createChild('epoch-settler'),
241
+ { pollingIntervalMs: 200 },
242
+ );
243
+ await epochTestSettler.start();
244
+ }
245
+
246
+ if (initialAccounts.length) {
247
+ const wallet = await EmbeddedWallet.create(node, {
248
+ pxeConfig: { proverEnabled: aztecNodeConfig.realProofs },
249
+ ephemeral: true,
250
+ });
251
+
252
+ userLog('Setting up funded test accounts...');
253
+ const accountManagers = await deployFundedSchnorrAccounts(wallet, initialAccounts, setupWaitOpts);
254
+ const accLogs = await createAccountLogs(accountManagers, wallet);
255
+ userLog(accLogs.join(''));
256
+
257
+ userLog('Publishing standard AuthRegistry contract...');
258
+ await publishStandardAuthRegistry(wallet, initialAccounts[0].address, setupWaitOpts);
259
+
260
+ await setupBananaFPC(initialAccounts, wallet, userLog, setupWaitOpts);
261
+
262
+ userLog(`SponsoredFPC: ${await getSponsoredFPCAddress()}`);
263
+
264
+ // We no longer need the wallet once we've setup the accounts so we stop the underlying PXE job queue
265
+ await wallet.stop();
266
+ }
267
+
268
+ const stop = async () => {
269
+ await node.stop();
270
+ await watcher?.stop();
271
+ await epochTestSettler?.stop();
272
+ };
273
+
274
+ return { node, stop };
275
+ }
276
+
277
+ /**
278
+ * Create and start a new Aztec RPC HTTP Server
279
+ * @param config - Optional Aztec node settings.
280
+ */
281
+ export async function createAztecNode(
282
+ config: Partial<AztecNodeConfig> = {},
283
+ deps: {
284
+ telemetry?: TelemetryClient;
285
+ blobClient?: BlobClientInterface;
286
+ dateProvider?: DateProvider;
287
+ proverBroker?: ProvingJobBroker;
288
+ } = {},
289
+ options: { genesis?: GenesisData } = {},
290
+ ) {
291
+ // TODO(#12272): will clean this up. This is criminal.
292
+ // Not sure why this was ever done. Will be fixed in A-989, A-991, A-990.
293
+ const aztecNodeConfig: AztecNodeConfig = {
294
+ ...getConfigEnvVars(),
295
+ ...config,
296
+ };
297
+ const node = await AztecNodeService.createAndSync(
298
+ aztecNodeConfig,
299
+ { ...deps, proverNodeDeps: { broker: deps.proverBroker } },
300
+ options,
301
+ );
302
+ return node;
303
+ }
@@ -1,3 +1,4 @@
1
+ import type { AztecAddress } from '@aztec/aztec.js/addresses';
1
2
  import {
2
3
  type ContractInstanceWithAddress,
3
4
  getContractInstanceFromInstantiationParams,
@@ -13,11 +14,11 @@ async function getSponsoredFPCInstance(): Promise<ContractInstanceWithAddress> {
13
14
  });
14
15
  }
15
16
 
16
- export async function getSponsoredFPCAddress() {
17
+ export async function getSponsoredFPCAddress(): Promise<AztecAddress> {
17
18
  return (await getSponsoredFPCInstance()).address;
18
19
  }
19
20
 
20
- export async function registerDeployedSponsoredFPCInWalletAndGetAddress(wallet: Wallet) {
21
+ export async function registerDeployedSponsoredFPCInWalletAndGetAddress(wallet: Wallet): Promise<AztecAddress> {
21
22
  const fpc = await getSponsoredFPCInstance();
22
23
  // The following is no-op if the contract is already registered
23
24
  await wallet.registerContract(fpc, SponsoredFPCContract.artifact);
@@ -1,5 +1,6 @@
1
- import type { ViemClient } from '@aztec/ethereum';
2
1
  import { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
2
+ import type { ViemClient } from '@aztec/ethereum/types';
3
+ import { SlotNumber } from '@aztec/foundation/branded-types';
3
4
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
5
  import { type Logger, createLogger } from '@aztec/foundation/log';
5
6
  import { RunningPromise } from '@aztec/foundation/running-promise';
@@ -8,6 +9,11 @@ import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
8
9
 
9
10
  import { type GetContractReturnType, getAddress, getContract } from 'viem';
10
11
 
12
+ export type AnvilTestWatcherOpts = {
13
+ isLocalNetwork?: boolean;
14
+ isMarkingAsProven?: boolean;
15
+ };
16
+
11
17
  /**
12
18
  * Represents a watcher for a rollup contract.
13
19
  *
@@ -16,11 +22,12 @@ import { type GetContractReturnType, getAddress, getContract } from 'viem';
16
22
  * block within the slot. And if so, it will time travel into the next slot.
17
23
  */
18
24
  export class AnvilTestWatcher {
19
- private isSandbox: boolean = false;
25
+ private isLocalNetwork;
26
+ private isMarkingAsProven;
20
27
 
21
28
  private rollup: GetContractReturnType<typeof RollupAbi, ViemClient>;
22
29
  private rollupCheatCodes: RollupCheatCodes;
23
- private l2SlotDuration!: bigint;
30
+ private l2SlotDuration!: number;
24
31
 
25
32
  private filledRunningPromise?: RunningPromise;
26
33
  private syncDateProviderPromise?: RunningPromise;
@@ -28,13 +35,27 @@ export class AnvilTestWatcher {
28
35
 
29
36
  private logger: Logger = createLogger(`aztecjs:utils:watcher`);
30
37
 
31
- private isMarkingAsProven = true;
38
+ // Optional callback to check if there are pending txs in the mempool.
39
+ private getPendingTxCount?: () => Promise<number>;
40
+
41
+ // Optional callback to check if the sequencer is actively building a block.
42
+ private isSequencerBuilding?: () => boolean;
43
+
44
+ // Tracks when we first observed the current unfilled slot with pending txs (real wall time).
45
+ private unfilledSlotFirstSeen?: { slot: number; realTime: number };
46
+
47
+ // Latest target slot for which the proposer has built a block destined for L1 but which has
48
+ // not yet been committed. Set by the proposer-pipelining hook from `block-proposed` events so
49
+ // the watcher can advance L1 (and the injected date provider) to the target slot ahead of the
50
+ // publisher's `sendRequestsAt` sleep, instead of waiting a full wall-clock slot.
51
+ private proposedTargetSlot?: number;
32
52
 
33
53
  constructor(
34
54
  private cheatcodes: EthCheatCodes,
35
55
  rollupAddress: EthAddress,
36
56
  l1Client: ViemClient,
37
57
  private dateProvider?: TestDateProvider,
58
+ opts: AnvilTestWatcherOpts = {},
38
59
  ) {
39
60
  this.rollup = getContract({
40
61
  address: getAddress(rollupAddress.toString()),
@@ -46,6 +67,9 @@ export class AnvilTestWatcher {
46
67
  rollupAddress,
47
68
  });
48
69
 
70
+ this.isLocalNetwork = opts.isLocalNetwork ?? false;
71
+ this.isMarkingAsProven = opts.isMarkingAsProven ?? true;
72
+
49
73
  this.logger.debug(`Watcher created for rollup at ${rollupAddress}`);
50
74
  }
51
75
 
@@ -54,8 +78,30 @@ export class AnvilTestWatcher {
54
78
  this.isMarkingAsProven = isMarkingAsProven;
55
79
  }
56
80
 
57
- setIsSandbox(isSandbox: boolean) {
58
- this.isSandbox = isSandbox;
81
+ setisLocalNetwork(isLocalNetwork: boolean) {
82
+ this.isLocalNetwork = isLocalNetwork;
83
+ }
84
+
85
+ /** Sets a callback to check for pending txs, used to skip unfilled slots faster when txs are waiting. */
86
+ setGetPendingTxCount(fn: () => Promise<number>) {
87
+ this.getPendingTxCount = fn;
88
+ }
89
+
90
+ /** Sets a callback to check if the sequencer is actively building, to avoid warping while it works. */
91
+ setIsSequencerBuilding(fn: () => boolean) {
92
+ this.isSequencerBuilding = fn;
93
+ }
94
+
95
+ /**
96
+ * Records the target slot for which the proposer has built a block destined for L1. Used by
97
+ * the local-network watcher to fast-forward L1 (and the injected date provider) ahead of the
98
+ * pipelined publisher's `sendRequestsAt` sleep so it ends promptly instead of waiting a full
99
+ * wall-clock slot. Only ratchets up — late warps for stale slots are no-ops.
100
+ */
101
+ setProposedTargetSlot(slot: number) {
102
+ if (this.proposedTargetSlot === undefined || slot > this.proposedTargetSlot) {
103
+ this.proposedTargetSlot = slot;
104
+ }
59
105
  }
60
106
 
61
107
  async start() {
@@ -68,7 +114,7 @@ export class AnvilTestWatcher {
68
114
 
69
115
  // If auto mining is not supported (e.g., we are on a real network), then we
70
116
  // will simple do nothing. But if on an anvil or the like, this make sure that
71
- // the sandbox and tests don't break because time is frozen and we never get to
117
+ // the local network and tests don't break because time is frozen and we never get to
72
118
  // the next slot.
73
119
  const isAutoMining = await this.cheatcodes.isAutoMining();
74
120
 
@@ -105,60 +151,123 @@ export class AnvilTestWatcher {
105
151
  }
106
152
 
107
153
  async syncDateProviderToL1IfBehind() {
108
- // this doesn't apply to the sandbox, because we don't have a date provider in the sandbox
154
+ // this doesn't apply to the local network, because we don't have a date provider in the local network
109
155
  if (!this.dateProvider) {
110
156
  return;
111
157
  }
112
158
 
113
- const l1Time = (await this.cheatcodes.timestamp()) * 1000;
159
+ const l1Time = (await this.cheatcodes.lastBlockTimestamp()) * 1000;
114
160
  const wallTime = this.dateProvider.now();
115
161
  if (l1Time > wallTime) {
116
162
  this.logger.warn(`L1 is ahead of wall time. Syncing wall time to L1 time`);
117
163
  this.dateProvider.setTime(l1Time);
118
164
  } else if (l1Time + Number(this.l2SlotDuration) * 1000 < wallTime) {
119
- this.logger.warn(`L1 is more than 1 L2 slot behind wall time. Warping to wall time`);
120
- await this.cheatcodes.warp(Math.ceil(wallTime / 1000));
165
+ // Warp L1 to the slot boundary at-or-before wall time. Rounding to a slot boundary (rather than
166
+ // `ceil(wallTime / 1000)`) keeps this loop's target aligned with `warpTimeIfNeeded`'s
167
+ // `nextSlotTimestamp` target, avoiding a race where the two loops pick timestamps a fraction of
168
+ // a second apart and one of them is then rejected by anvil as non-monotonic.
169
+ const wallSec = Math.floor(wallTime / 1000);
170
+ const targetSlot = await this.rollup.read.getSlotAt([BigInt(wallSec)]);
171
+ const targetTimestamp = Number(await this.rollup.read.getTimestampForSlot([targetSlot]));
172
+ this.logger.warn(`L1 is more than 1 L2 slot behind wall time. Warping to slot ${targetSlot} boundary`);
173
+ await this.warpToTimestamp(targetTimestamp);
121
174
  }
122
175
  }
123
176
 
124
177
  async warpTimeIfNeeded() {
125
178
  try {
126
- const currentSlot = await this.rollup.read.getCurrentSlot();
127
- const pendingBlockNumber = BigInt(await this.rollup.read.getPendingBlockNumber());
128
- const blockLog = await this.rollup.read.getBlock([pendingBlockNumber]);
129
- const nextSlotTimestamp = Number(await this.rollup.read.getTimestampForSlot([currentSlot + 1n]));
130
-
131
- if (currentSlot === blockLog.slotNumber) {
132
- // We should jump to the next slot
133
- try {
134
- await this.cheatcodes.warp(nextSlotTimestamp, {
135
- resetBlockInterval: true,
136
- });
137
- } catch (e) {
138
- this.logger.error(`Failed to warp to timestamp ${nextSlotTimestamp}: ${e}`);
179
+ const currentSlot = SlotNumber.fromBigInt(await this.rollup.read.getCurrentSlot());
180
+ const pendingCheckpointNumber = await this.rollup.read.getPendingCheckpointNumber();
181
+ const checkpointLog = await this.rollup.read.getCheckpoint([pendingCheckpointNumber]);
182
+ const nextSlot = SlotNumber(currentSlot + 1);
183
+ const nextSlotTimestamp = Number(await this.rollup.read.getTimestampForSlot([BigInt(nextSlot)]));
184
+
185
+ if (BigInt(currentSlot) === checkpointLog.slotNumber) {
186
+ // The current slot has been filled, we should jump to the next slot.
187
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
188
+ this.logger.info(`Slot ${currentSlot} was filled, jumped to next slot`);
139
189
  }
190
+ return;
191
+ }
140
192
 
141
- this.logger.info(`Slot ${currentSlot} was filled, jumped to next slot`);
193
+ // If we are not in local network, we don't need to warp time
194
+ if (!this.isLocalNetwork) {
142
195
  return;
143
196
  }
144
197
 
145
- // If we are not in sandbox, we don't need to warp time
146
- if (!this.isSandbox) {
198
+ // Pipelined-publish shortcut: if the proposer has built a block destined for a slot
199
+ // beyond the current L1 slot, fast-forward L1 to that slot's timestamp so the publisher's
200
+ // `sendRequestsAt(targetSlot)` sleep ends and the multicall mines inside the target slot.
201
+ // Without this, the publisher waits up to a full real-time slot for wall clock to catch up.
202
+ if (this.proposedTargetSlot !== undefined && this.proposedTargetSlot > currentSlot) {
203
+ const targetSlotTimestamp = Number(
204
+ await this.rollup.read.getTimestampForSlot([BigInt(this.proposedTargetSlot)]),
205
+ );
206
+ if (await this.warpToTimestamp(targetSlotTimestamp)) {
207
+ this.logger.info(`Warped L1 to target slot ${this.proposedTargetSlot} for pipelined publish`);
208
+ }
147
209
  return;
148
210
  }
149
211
 
212
+ // If there are pending txs and the sequencer missed them, warp quickly (after a 2s real-time debounce) so the
213
+ // sequencer can retry in the next slot. Without this, we'd have to wait a full real-time slot duration (~36s) for
214
+ // the dateProvider to catch up to the next slot timestamp. We skip the warp if the sequencer is actively building
215
+ // to avoid invalidating its in-progress work.
216
+ if (this.getPendingTxCount) {
217
+ const pendingTxs = await this.getPendingTxCount();
218
+ if (pendingTxs > 0) {
219
+ if (this.isSequencerBuilding?.()) {
220
+ this.unfilledSlotFirstSeen = undefined;
221
+ return;
222
+ }
223
+
224
+ const realNow = Date.now();
225
+ if (!this.unfilledSlotFirstSeen || this.unfilledSlotFirstSeen.slot !== currentSlot) {
226
+ this.unfilledSlotFirstSeen = { slot: currentSlot, realTime: realNow };
227
+ return;
228
+ }
229
+
230
+ if (realNow - this.unfilledSlotFirstSeen.realTime > 2000) {
231
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
232
+ this.logger.info(`Slot ${currentSlot} was missed with pending txs, jumped to next slot`);
233
+ }
234
+ this.unfilledSlotFirstSeen = undefined;
235
+ }
236
+
237
+ return;
238
+ }
239
+ }
240
+
241
+ // Fallback: warp when the dateProvider time has passed the next slot timestamp.
150
242
  const currentTimestamp = this.dateProvider?.now() ?? Date.now();
151
243
  if (currentTimestamp > nextSlotTimestamp * 1000) {
152
- try {
153
- await this.cheatcodes.warp(nextSlotTimestamp, { resetBlockInterval: true });
154
- } catch (e) {
155
- this.logger.error(`Failed to warp to timestamp ${nextSlotTimestamp}: ${e}`);
244
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
245
+ this.logger.info(`Slot ${currentSlot} was missed, jumped to next slot`);
156
246
  }
157
-
158
- this.logger.info(`Slot ${currentSlot} was missed, jumped to next slot`);
159
247
  }
160
248
  } catch {
161
249
  this.logger.error('mineIfSlotFilled failed');
162
250
  }
163
251
  }
252
+
253
+ /**
254
+ * Warps L1 to `timestamp`, unless L1 is already at or past it. Returns true when a warp actually
255
+ * happened, false when skipped or on error. Callers use the return value to gate success logs.
256
+ */
257
+ private async warpToTimestamp(timestamp: number): Promise<boolean> {
258
+ try {
259
+ // Anvil rejects evm_setNextBlockTimestamp values <= the current block's timestamp. The two
260
+ // watcher loops can race and pick targets a fraction of a second apart; skip here rather than
261
+ // letting the second one error out noisily.
262
+ const lastTimestamp = await this.cheatcodes.lastBlockTimestamp();
263
+ if (timestamp <= lastTimestamp) {
264
+ return false;
265
+ }
266
+ await this.cheatcodes.warp(timestamp, { resetBlockInterval: true });
267
+ return true;
268
+ } catch (e) {
269
+ this.logger.error(`Failed to warp to timestamp ${timestamp}: ${e}`);
270
+ return false;
271
+ }
272
+ }
164
273
  }