@aztec/aztec 0.0.1-commit.ff7989d6c → 0.0.1-commit.fff30aa

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 (113) hide show
  1. package/dest/bin/index.js +4 -2
  2. package/dest/cli/aztec_start_action.d.ts +1 -1
  3. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  4. package/dest/cli/aztec_start_action.js +27 -9
  5. package/dest/cli/aztec_start_options.d.ts +1 -1
  6. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  7. package/dest/cli/aztec_start_options.js +14 -2
  8. package/dest/cli/cli.js +3 -3
  9. package/dest/cli/cmds/compile.d.ts +1 -1
  10. package/dest/cli/cmds/compile.d.ts.map +1 -1
  11. package/dest/cli/cmds/compile.js +109 -36
  12. package/dest/cli/cmds/profile.d.ts +4 -0
  13. package/dest/cli/cmds/profile.d.ts.map +1 -0
  14. package/dest/cli/cmds/profile.js +8 -0
  15. package/dest/cli/cmds/profile_flamegraph.d.ts +4 -0
  16. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -0
  17. package/dest/cli/cmds/profile_flamegraph.js +52 -0
  18. package/dest/cli/cmds/profile_gates.d.ts +4 -0
  19. package/dest/cli/cmds/profile_gates.d.ts.map +1 -0
  20. package/dest/cli/cmds/profile_gates.js +58 -0
  21. package/dest/cli/cmds/profile_utils.d.ts +18 -0
  22. package/dest/cli/cmds/profile_utils.d.ts.map +1 -0
  23. package/dest/cli/cmds/profile_utils.js +50 -0
  24. package/dest/cli/cmds/standby.d.ts +32 -0
  25. package/dest/cli/cmds/standby.d.ts.map +1 -0
  26. package/dest/cli/cmds/standby.js +97 -0
  27. package/dest/cli/cmds/start_node.d.ts +3 -2
  28. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  29. package/dest/cli/cmds/start_node.js +24 -32
  30. package/dest/cli/cmds/start_prover_agent.d.ts +1 -1
  31. package/dest/cli/cmds/start_prover_agent.d.ts.map +1 -1
  32. package/dest/cli/cmds/start_prover_agent.js +3 -15
  33. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  34. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  35. package/dest/cli/cmds/start_prover_broker.js +12 -6
  36. package/dest/cli/cmds/utils/artifacts.d.ts +21 -0
  37. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -0
  38. package/dest/cli/cmds/utils/artifacts.js +24 -0
  39. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts +21 -0
  40. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts.map +1 -0
  41. package/dest/cli/cmds/utils/collect_crate_dirs.js +114 -0
  42. package/dest/cli/cmds/utils/needs_recompile.d.ts +10 -0
  43. package/dest/cli/cmds/utils/needs_recompile.d.ts.map +1 -0
  44. package/dest/cli/cmds/utils/needs_recompile.js +90 -0
  45. package/dest/cli/cmds/utils/spawn.d.ts +3 -0
  46. package/dest/cli/cmds/utils/spawn.d.ts.map +1 -0
  47. package/dest/cli/cmds/utils/spawn.js +16 -0
  48. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts +4 -0
  49. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts.map +1 -0
  50. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.js +62 -0
  51. package/dest/cli/util.d.ts +3 -5
  52. package/dest/cli/util.d.ts.map +1 -1
  53. package/dest/cli/util.js +37 -78
  54. package/dest/examples/token.js +4 -4
  55. package/dest/local-network/banana_fpc.js +1 -1
  56. package/dest/local-network/local-network.d.ts +1 -1
  57. package/dest/local-network/local-network.d.ts.map +1 -1
  58. package/dest/local-network/local-network.js +18 -5
  59. package/dest/testing/anvil_test_watcher.d.ts +1 -1
  60. package/dest/testing/anvil_test_watcher.d.ts.map +1 -1
  61. package/dest/testing/anvil_test_watcher.js +36 -10
  62. package/dest/testing/cheat_codes.d.ts +11 -15
  63. package/dest/testing/cheat_codes.d.ts.map +1 -1
  64. package/dest/testing/cheat_codes.js +34 -32
  65. package/dest/testing/epoch_test_settler.d.ts +1 -1
  66. package/dest/testing/epoch_test_settler.d.ts.map +1 -1
  67. package/dest/testing/epoch_test_settler.js +3 -4
  68. package/dest/testing/index.d.ts +2 -1
  69. package/dest/testing/index.d.ts.map +1 -1
  70. package/dest/testing/index.js +1 -0
  71. package/dest/testing/token_allowed_setup.d.ts +7 -0
  72. package/dest/testing/token_allowed_setup.d.ts.map +1 -0
  73. package/dest/testing/token_allowed_setup.js +20 -0
  74. package/package.json +35 -34
  75. package/scripts/add_crate.sh +102 -0
  76. package/scripts/aztec.sh +9 -1
  77. package/scripts/init.sh +23 -19
  78. package/scripts/new.sh +48 -24
  79. package/scripts/setup_workspace.sh +68 -0
  80. package/src/bin/index.ts +4 -2
  81. package/src/cli/aztec_start_action.ts +16 -9
  82. package/src/cli/aztec_start_options.ts +14 -2
  83. package/src/cli/cli.ts +3 -3
  84. package/src/cli/cmds/compile.ts +124 -37
  85. package/src/cli/cmds/profile.ts +25 -0
  86. package/src/cli/cmds/profile_flamegraph.ts +64 -0
  87. package/src/cli/cmds/profile_gates.ts +68 -0
  88. package/src/cli/cmds/profile_utils.ts +58 -0
  89. package/src/cli/cmds/standby.ts +132 -0
  90. package/src/cli/cmds/start_node.ts +39 -31
  91. package/src/cli/cmds/start_prover_agent.ts +3 -6
  92. package/src/cli/cmds/start_prover_broker.ts +14 -14
  93. package/src/cli/cmds/utils/artifacts.ts +44 -0
  94. package/src/cli/cmds/utils/collect_crate_dirs.ts +118 -0
  95. package/src/cli/cmds/utils/needs_recompile.ts +98 -0
  96. package/src/cli/cmds/utils/spawn.ts +16 -0
  97. package/src/cli/cmds/utils/warn_if_aztec_version_mismatch.ts +77 -0
  98. package/src/cli/util.ts +41 -74
  99. package/src/examples/token.ts +6 -4
  100. package/src/local-network/banana_fpc.ts +1 -1
  101. package/src/local-network/local-network.ts +13 -3
  102. package/src/testing/anvil_test_watcher.ts +33 -10
  103. package/src/testing/cheat_codes.ts +42 -36
  104. package/src/testing/epoch_test_settler.ts +3 -4
  105. package/src/testing/index.ts +1 -0
  106. package/src/testing/token_allowed_setup.ts +19 -0
  107. package/dest/cli/release_version.d.ts +0 -2
  108. package/dest/cli/release_version.d.ts.map +0 -1
  109. package/dest/cli/release_version.js +0 -14
  110. package/scripts/extract_function.js +0 -47
  111. package/scripts/flamegraph.sh +0 -59
  112. package/scripts/setup_project.sh +0 -31
  113. package/src/cli/release_version.ts +0 -21
@@ -0,0 +1,77 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+ import { getPackageVersion } from '@aztec/stdlib/update-checker';
3
+
4
+ import TOML from '@iarna/toml';
5
+ import { readFile } from 'fs/promises';
6
+ import { join } from 'path';
7
+
8
+ import { collectCrateDirs } from './collect_crate_dirs.js';
9
+
10
+ /** Returns true if the given git URL points to the AztecProtocol/aztec-nr repository. */
11
+ function isAztecNrGitUrl(gitUrl: string): boolean {
12
+ let url: URL;
13
+ try {
14
+ url = new URL(gitUrl);
15
+ } catch {
16
+ return false;
17
+ }
18
+ if (url.hostname !== 'github.com') {
19
+ return false;
20
+ }
21
+ const repoPath = url.pathname
22
+ .replace(/^\//, '')
23
+ .replace(/\.git$/, '')
24
+ .replace(/\/$/, '');
25
+ return repoPath === 'AztecProtocol/aztec-nr';
26
+ }
27
+
28
+ /** Warns if any aztec-nr git dependency in a crate's Nargo.toml has a tag that doesn't match the CLI version. */
29
+ export async function warnIfAztecVersionMismatch(log: LogFn, cliVersion?: string): Promise<void> {
30
+ const version = cliVersion ?? getPackageVersion();
31
+ if (!version) {
32
+ log(`WARNING: aztec CLI version not found. Skipping dependency compatibility check.`);
33
+ return;
34
+ }
35
+
36
+ const expectedTag = `v${version}`;
37
+ const mismatches: { file: string; depName: string; tag: string }[] = [];
38
+
39
+ const crateDirs = await collectCrateDirs('.', { skipGitDeps: true });
40
+
41
+ for (const dir of crateDirs) {
42
+ const tomlPath = join(dir, 'Nargo.toml');
43
+ let content: string;
44
+ try {
45
+ content = await readFile(tomlPath, 'utf-8');
46
+ } catch {
47
+ continue;
48
+ }
49
+
50
+ const parsed = TOML.parse(content) as Record<string, any>;
51
+ const deps = (parsed.dependencies as Record<string, any>) ?? {};
52
+
53
+ for (const [depName, dep] of Object.entries(deps)) {
54
+ // Skip non-object deps (e.g. malformed entries) and anything that isn't a tagged git dep.
55
+ if (!dep || typeof dep !== 'object' || typeof dep.git !== 'string' || typeof dep.tag !== 'string') {
56
+ continue;
57
+ }
58
+ // Only flag deps that are sourced from the aztec-nr repo.
59
+ if (!isAztecNrGitUrl(dep.git)) {
60
+ continue;
61
+ }
62
+ if (dep.tag !== expectedTag) {
63
+ mismatches.push({ file: tomlPath, depName, tag: dep.tag });
64
+ }
65
+ }
66
+ }
67
+
68
+ if (mismatches.length > 0) {
69
+ const details = mismatches.map(m => ` ${m.file} — ${m.depName} (${m.tag})`).join('\n');
70
+ log(
71
+ `WARNING: Aztec dependency version mismatch detected.\n` +
72
+ `The following aztec-nr dependencies do not match the CLI version (${expectedTag}):\n` +
73
+ `${details}\n\n` +
74
+ `See https://docs.aztec.network/errors/9 for how to update your dependencies.`,
75
+ );
76
+ }
77
+ }
package/src/cli/util.ts CHANGED
@@ -1,17 +1,18 @@
1
1
  import type { AztecNodeConfig } from '@aztec/aztec-node';
2
2
  import type { AccountManager } from '@aztec/aztec.js/wallet';
3
+ import { getNetworkConfig } from '@aztec/cli/config';
4
+ import { RegistryContract } from '@aztec/ethereum/contracts';
3
5
  import type { ViemClient } from '@aztec/ethereum/types';
4
- import type { ConfigMappingsType } from '@aztec/foundation/config';
5
- import { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { ConfigMappingsType, NetworkNames } from '@aztec/foundation/config';
6
7
  import { jsonStringify } from '@aztec/foundation/json-rpc';
7
8
  import { type LogFn, createLogger } from '@aztec/foundation/log';
8
- import type { SharedNodeConfig } from '@aztec/node-lib/config';
9
9
  import type { ProverConfig } from '@aztec/stdlib/interfaces/server';
10
- import { getTelemetryClient } from '@aztec/telemetry-client/start';
10
+ import { type VersionCheck, getPackageVersion } from '@aztec/stdlib/update-checker';
11
11
  import type { EmbeddedWallet } from '@aztec/wallets/embedded';
12
12
 
13
13
  import chalk from 'chalk';
14
14
  import type { Command } from 'commander';
15
+ import type { Hex } from 'viem';
15
16
 
16
17
  import { type AztecStartOption, aztecStartOptions } from './aztec_start_options.js';
17
18
 
@@ -290,92 +291,58 @@ export async function preloadCrsDataForServerSideProving(
290
291
  }
291
292
  }
292
293
 
293
- export async function setupUpdateMonitor(
294
- autoUpdateMode: SharedNodeConfig['autoUpdate'],
295
- updatesLocation: URL,
294
+ export async function setupVersionChecker(
295
+ network: NetworkNames,
296
296
  followsCanonicalRollup: boolean,
297
297
  publicClient: ViemClient,
298
- registryContractAddress: EthAddress,
299
298
  signalHandlers: Array<() => Promise<void>>,
300
- updateNodeConfig?: (config: object) => Promise<void>,
301
- ) {
302
- const logger = createLogger('update-check');
303
- const { UpdateChecker } = await import('@aztec/stdlib/update-checker');
304
- const checker = await UpdateChecker.new({
305
- baseURL: updatesLocation,
306
- publicClient,
307
- registryContractAddress,
308
- });
299
+ cacheDir?: string,
300
+ ): Promise<void> {
301
+ const networkConfig = await getNetworkConfig(network, cacheDir);
302
+ if (!networkConfig) {
303
+ return;
304
+ }
309
305
 
310
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
311
- checker.on('newRollupVersion', async ({ latestVersion, currentVersion }) => {
312
- if (isShuttingDown()) {
313
- return;
314
- }
306
+ const { VersionChecker } = await import('@aztec/stdlib/update-checker');
315
307
 
316
- // if node follows canonical rollup then this is equivalent to a config update
317
- if (!followsCanonicalRollup) {
318
- return;
319
- }
308
+ const logger = createLogger('version_check');
309
+ const registry = new RegistryContract(publicClient, networkConfig.registryAddress as Hex);
320
310
 
321
- if (autoUpdateMode === 'config' || autoUpdateMode === 'config-and-version') {
322
- logger.info(`New rollup version detected. Please restart the node`, { latestVersion, currentVersion });
323
- await shutdown(logger.info, ExitCode.ROLLUP_UPGRADE, signalHandlers);
324
- } else if (autoUpdateMode === 'notify') {
325
- logger.warn(`New rollup detected. Please restart the node`, { latestVersion, currentVersion });
326
- }
311
+ const checks: Array<VersionCheck> = [];
312
+ checks.push({
313
+ name: 'node',
314
+ currentVersion: getPackageVersion() ?? 'unknown',
315
+ getLatestVersion: async () => {
316
+ const cfg = await getNetworkConfig(network, cacheDir);
317
+ return cfg?.nodeVersion;
318
+ },
327
319
  });
328
320
 
329
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
330
- checker.on('newNodeVersion', async ({ latestVersion, currentVersion }) => {
331
- if (isShuttingDown()) {
332
- return;
333
- }
334
- if (autoUpdateMode === 'config-and-version') {
335
- logger.info(`New node version detected. Please update and restart the node`, { latestVersion, currentVersion });
336
- await shutdown(logger.info, ExitCode.VERSION_UPGRADE, signalHandlers);
337
- } else if (autoUpdateMode === 'notify') {
338
- logger.info(`New node version detected. Please update and restart the node`, { latestVersion, currentVersion });
321
+ if (followsCanonicalRollup) {
322
+ const getLatestVersion = async () => {
323
+ const version = (await registry.getRollupVersions()).at(-1);
324
+ return version !== undefined ? String(version) : undefined;
325
+ };
326
+ const currentVersion = await getLatestVersion();
327
+ if (currentVersion !== undefined) {
328
+ checks.push({
329
+ name: 'rollup',
330
+ currentVersion,
331
+ getLatestVersion,
332
+ });
339
333
  }
340
- });
334
+ }
341
335
 
342
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
343
- checker.on('updateNodeConfig', async config => {
336
+ const checker = new VersionChecker(checks, 600_000, logger);
337
+ checker.on('newVersion', ({ name, latestVersion, currentVersion }) => {
344
338
  if (isShuttingDown()) {
345
339
  return;
346
340
  }
347
341
 
348
- if ((autoUpdateMode === 'config' || autoUpdateMode === 'config-and-version') && updateNodeConfig) {
349
- logger.warn(`Config change detected. Updating node`, config);
350
- try {
351
- await updateNodeConfig(config);
352
- } catch (err) {
353
- logger.warn('Failed to update config', { err });
354
- }
355
- }
356
- // don't notify on these config changes
357
- });
358
-
359
- checker.on('updatePublicTelemetryConfig', config => {
360
- if (autoUpdateMode === 'config' || autoUpdateMode === 'config-and-version') {
361
- logger.warn(`Public telemetry config change detected. Updating telemetry client`, config);
362
- try {
363
- const publicIncludeMetrics: unknown = (config as any).publicIncludeMetrics;
364
- if (Array.isArray(publicIncludeMetrics) && publicIncludeMetrics.every(m => typeof m === 'string')) {
365
- getTelemetryClient().setExportedPublicTelemetry(publicIncludeMetrics);
366
- }
367
- const publicMetricsCollectFrom: unknown = (config as any).publicMetricsCollectFrom;
368
- if (Array.isArray(publicMetricsCollectFrom) && publicMetricsCollectFrom.every(m => typeof m === 'string')) {
369
- getTelemetryClient().setPublicTelemetryCollectFrom(publicMetricsCollectFrom);
370
- }
371
- } catch (err) {
372
- logger.warn('Failed to update config', { err });
373
- }
374
- }
375
- // don't notify on these config changes
342
+ logger.warn(`New ${name} version available`, { latestVersion, currentVersion });
376
343
  });
377
-
378
344
  checker.start();
345
+ signalHandlers.push(() => checker.stop());
379
346
  }
380
347
 
381
348
  export function stringifyConfig(config: object): string {
@@ -32,7 +32,9 @@ async function main() {
32
32
  logger.info(`Fetched Alice and Bob accounts: ${alice.toString()}, ${bob.toString()}`);
33
33
 
34
34
  logger.info('Deploying Token...');
35
- const token = await TokenContract.deploy(wallet, alice, 'TokenName', 'TokenSymbol', 18).send({ from: alice });
35
+ const { contract: token } = await TokenContract.deploy(wallet, alice, 'TokenName', 'TokenSymbol', 18).send({
36
+ from: alice,
37
+ });
36
38
  logger.info('Token deployed');
37
39
 
38
40
  // Mint tokens to Alice
@@ -41,7 +43,7 @@ async function main() {
41
43
 
42
44
  logger.info(`${ALICE_MINT_BALANCE} tokens were successfully minted by Alice and transferred to private`);
43
45
 
44
- const balanceAfterMint = await token.methods.balance_of_private(alice).simulate({ from: alice });
46
+ const { result: balanceAfterMint } = await token.methods.balance_of_private(alice).simulate({ from: alice });
45
47
  logger.info(`Tokens successfully minted. New Alice's balance: ${balanceAfterMint}`);
46
48
 
47
49
  // We will now transfer tokens from Alice to Bob
@@ -49,10 +51,10 @@ async function main() {
49
51
  await token.methods.transfer(bob, TRANSFER_AMOUNT).send({ from: alice });
50
52
 
51
53
  // Check the new balances
52
- const aliceBalance = await token.methods.balance_of_private(alice).simulate({ from: alice });
54
+ const { result: aliceBalance } = await token.methods.balance_of_private(alice).simulate({ from: alice });
53
55
  logger.info(`Alice's balance ${aliceBalance}`);
54
56
 
55
- const bobBalance = await token.methods.balance_of_private(bob).simulate({ from: bob });
57
+ const { result: bobBalance } = await token.methods.balance_of_private(bob).simulate({ from: bob });
56
58
  logger.info(`Bob's balance ${bobBalance}`);
57
59
  }
58
60
 
@@ -48,7 +48,7 @@ export async function getBananaFPCAddress(initialAccounts: InitialAccountData[])
48
48
  export async function setupBananaFPC(initialAccounts: InitialAccountData[], wallet: Wallet, log: LogFn) {
49
49
  const bananaCoinAddress = await getBananaCoinAddress(initialAccounts);
50
50
  const admin = getBananaAdmin(initialAccounts);
51
- const [bananaCoin, fpc] = await Promise.all([
51
+ const [{ contract: bananaCoin }, { contract: fpc }] = await Promise.all([
52
52
  TokenContract.deploy(wallet, admin, bananaCoinArgs.name, bananaCoinArgs.symbol, bananaCoinArgs.decimal).send({
53
53
  from: admin,
54
54
  contractAddressSalt: BANANA_COIN_SALT,
@@ -19,6 +19,7 @@ import { DateProvider, TestDateProvider } from '@aztec/foundation/timer';
19
19
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
20
20
  import { protocolContractsHash } from '@aztec/protocol-contracts';
21
21
  import { SequencerState } from '@aztec/sequencer-client';
22
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
22
23
  import type { ProvingJobBroker } from '@aztec/stdlib/interfaces/server';
23
24
  import type { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
24
25
  import {
@@ -38,6 +39,7 @@ import { createAccountLogs } from '../cli/util.js';
38
39
  import { DefaultMnemonic } from '../mnemonic.js';
39
40
  import { AnvilTestWatcher } from '../testing/anvil_test_watcher.js';
40
41
  import { EpochTestSettler } from '../testing/epoch_test_settler.js';
42
+ import { getTokenAllowedSetupFunctions } from '../testing/token_allowed_setup.js';
41
43
  import { getBananaFPCAddress, setupBananaFPC } from './banana_fpc.js';
42
44
  import { getSponsoredFPCAddress } from './sponsored_fpc.js';
43
45
 
@@ -101,9 +103,14 @@ export async function createLocalNetwork(config: Partial<LocalNetworkConfig> = {
101
103
  logger.warn(`Multiple L1 RPC URLs provided. Local networks will only use the first one: ${l1RpcUrl}`);
102
104
  }
103
105
 
106
+ // The local network deploys a banana FPC with Token contracts, so include Token entries
107
+ // in the setup allowlist so FPC-based fee payments work out of the box.
108
+ const tokenAllowList = await getTokenAllowedSetupFunctions();
109
+
104
110
  const aztecNodeConfig: AztecNodeConfig = {
105
111
  ...getConfigEnvVars(),
106
112
  ...config,
113
+ txPublicSetupAllowListExtend: [...tokenAllowList, ...(config.txPublicSetupAllowListExtend ?? [])],
107
114
  };
108
115
  const hdAccount = mnemonicToAccount(config.l1Mnemonic || DefaultMnemonic);
109
116
  if (
@@ -138,9 +145,12 @@ export async function createLocalNetwork(config: Partial<LocalNetworkConfig> = {
138
145
 
139
146
  const bananaFPC = await getBananaFPCAddress(initialAccounts);
140
147
  const sponsoredFPC = await getSponsoredFPCAddress();
141
- const fundedAddresses = initialAccounts.length
142
- ? [...initialAccounts.map(a => a.address), bananaFPC, sponsoredFPC]
143
- : [];
148
+ const prefundAddresses = (aztecNodeConfig.prefundAddresses ?? []).map(a => AztecAddress.fromString(a));
149
+ const fundedAddresses = [
150
+ ...initialAccounts.map(a => a.address),
151
+ ...(initialAccounts.length ? [bananaFPC, sponsoredFPC] : []),
152
+ ...prefundAddresses,
153
+ ];
144
154
  const { genesisArchiveRoot, prefilledPublicData, fundingNeeded } = await getGenesisValues(fundedAddresses);
145
155
 
146
156
  const dateProvider = new TestDateProvider();
@@ -130,14 +130,21 @@ export class AnvilTestWatcher {
130
130
  return;
131
131
  }
132
132
 
133
- const l1Time = (await this.cheatcodes.timestamp()) * 1000;
133
+ const l1Time = (await this.cheatcodes.lastBlockTimestamp()) * 1000;
134
134
  const wallTime = this.dateProvider.now();
135
135
  if (l1Time > wallTime) {
136
136
  this.logger.warn(`L1 is ahead of wall time. Syncing wall time to L1 time`);
137
137
  this.dateProvider.setTime(l1Time);
138
138
  } else if (l1Time + Number(this.l2SlotDuration) * 1000 < wallTime) {
139
- this.logger.warn(`L1 is more than 1 L2 slot behind wall time. Warping to wall time`);
140
- await this.cheatcodes.warp(Math.ceil(wallTime / 1000));
139
+ // Warp L1 to the slot boundary at-or-before wall time. Rounding to a slot boundary (rather than
140
+ // `ceil(wallTime / 1000)`) keeps this loop's target aligned with `warpTimeIfNeeded`'s
141
+ // `nextSlotTimestamp` target, avoiding a race where the two loops pick timestamps a fraction of
142
+ // a second apart and one of them is then rejected by anvil as non-monotonic.
143
+ const wallSec = Math.floor(wallTime / 1000);
144
+ const targetSlot = await this.rollup.read.getSlotAt([BigInt(wallSec)]);
145
+ const targetTimestamp = Number(await this.rollup.read.getTimestampForSlot([targetSlot]));
146
+ this.logger.warn(`L1 is more than 1 L2 slot behind wall time. Warping to slot ${targetSlot} boundary`);
147
+ await this.warpToTimestamp(targetTimestamp);
141
148
  }
142
149
  }
143
150
 
@@ -151,8 +158,9 @@ export class AnvilTestWatcher {
151
158
 
152
159
  if (BigInt(currentSlot) === checkpointLog.slotNumber) {
153
160
  // The current slot has been filled, we should jump to the next slot.
154
- await this.warpToTimestamp(nextSlotTimestamp);
155
- this.logger.info(`Slot ${currentSlot} was filled, jumped to next slot`);
161
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
162
+ this.logger.info(`Slot ${currentSlot} was filled, jumped to next slot`);
163
+ }
156
164
  return;
157
165
  }
158
166
 
@@ -180,9 +188,10 @@ export class AnvilTestWatcher {
180
188
  }
181
189
 
182
190
  if (realNow - this.unfilledSlotFirstSeen.realTime > 2000) {
183
- await this.warpToTimestamp(nextSlotTimestamp);
191
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
192
+ this.logger.info(`Slot ${currentSlot} was missed with pending txs, jumped to next slot`);
193
+ }
184
194
  this.unfilledSlotFirstSeen = undefined;
185
- this.logger.info(`Slot ${currentSlot} was missed with pending txs, jumped to next slot`);
186
195
  }
187
196
 
188
197
  return;
@@ -192,19 +201,33 @@ export class AnvilTestWatcher {
192
201
  // Fallback: warp when the dateProvider time has passed the next slot timestamp.
193
202
  const currentTimestamp = this.dateProvider?.now() ?? Date.now();
194
203
  if (currentTimestamp > nextSlotTimestamp * 1000) {
195
- await this.warpToTimestamp(nextSlotTimestamp);
196
- this.logger.info(`Slot ${currentSlot} was missed, jumped to next slot`);
204
+ if (await this.warpToTimestamp(nextSlotTimestamp)) {
205
+ this.logger.info(`Slot ${currentSlot} was missed, jumped to next slot`);
206
+ }
197
207
  }
198
208
  } catch {
199
209
  this.logger.error('mineIfSlotFilled failed');
200
210
  }
201
211
  }
202
212
 
203
- private async warpToTimestamp(timestamp: number) {
213
+ /**
214
+ * Warps L1 to `timestamp`, unless L1 is already at or past it. Returns true when a warp actually
215
+ * happened, false when skipped or on error. Callers use the return value to gate success logs.
216
+ */
217
+ private async warpToTimestamp(timestamp: number): Promise<boolean> {
204
218
  try {
219
+ // Anvil rejects evm_setNextBlockTimestamp values <= the current block's timestamp. The two
220
+ // watcher loops can race and pick targets a fraction of a second apart; skip here rather than
221
+ // letting the second one error out noisily.
222
+ const lastTimestamp = await this.cheatcodes.lastBlockTimestamp();
223
+ if (timestamp <= lastTimestamp) {
224
+ return false;
225
+ }
205
226
  await this.cheatcodes.warp(timestamp, { resetBlockInterval: true });
227
+ return true;
206
228
  } catch (e) {
207
229
  this.logger.error(`Failed to warp to timestamp ${timestamp}: ${e}`);
230
+ return false;
208
231
  }
209
232
  }
210
233
  }
@@ -1,9 +1,8 @@
1
1
  import { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { retryUntil } from '@aztec/foundation/retry';
2
+ import { SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { createLogger } from '@aztec/foundation/log';
4
4
  import type { DateProvider } from '@aztec/foundation/timer';
5
- import type { SequencerClient } from '@aztec/sequencer-client';
6
- import type { AztecNode } from '@aztec/stdlib/interfaces/client';
5
+ import type { AztecNode, AztecNodeDebug } from '@aztec/stdlib/interfaces/client';
7
6
 
8
7
  /**
9
8
  * A class that provides utility functions for interacting with the chain.
@@ -12,6 +11,8 @@ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
12
11
  * codes, please consider whether it makes sense to just introduce new utils in your tests instead.
13
12
  */
14
13
  export class CheatCodes {
14
+ private logger = createLogger('aztecjs:cheat_codes');
15
+
15
16
  constructor(
16
17
  /** Cheat codes for L1.*/
17
18
  public eth: EthCheatCodes,
@@ -30,50 +31,55 @@ export class CheatCodes {
30
31
 
31
32
  /**
32
33
  * Warps the L1 timestamp to a target timestamp and mines an L2 block that advances the L2 timestamp to at least
33
- * the target timestamp. L2 timestamp is not advanced exactly to the target timestamp because it is determined
34
- * by the slot number, which advances in fixed intervals.
35
- * This is useful for testing time-dependent contract behavior.
36
- * @param sequencerClient - The sequencer client to use to force an empty block to be mined.
37
- * @param node - The Aztec node used to query if a new block has been mined.
34
+ * the target timestamp. If the target timestamp falls within the current L2 slot (which already has a block),
35
+ * the timestamp is automatically adjusted forward to the start of the next slot so that `mineBlock()` succeeds.
36
+ * @param node - The Aztec node used to force an empty block to be mined.
38
37
  * @param targetTimestamp - The target timestamp to warp to (in seconds)
39
38
  */
40
- async warpL2TimeAtLeastTo(sequencerClient: SequencerClient, node: AztecNode, targetTimestamp: bigint | number) {
41
- const currentL2BlockNumber: BlockNumber = await node.getBlockNumber();
39
+ async warpL2TimeAtLeastTo(node: AztecNodeDebug, targetTimestamp: bigint | number) {
40
+ const targetBigInt = BigInt(targetTimestamp);
41
+ const currentTimestamp = BigInt(await this.eth.lastBlockTimestamp());
42
42
 
43
- // We warp the L1 timestamp
44
- await this.eth.warp(targetTimestamp, { resetBlockInterval: true });
43
+ if (targetBigInt <= currentTimestamp) {
44
+ throw new Error(
45
+ `warpL2TimeAtLeastTo: target timestamp ${targetBigInt} is not in the future (current L1 timestamp is ${currentTimestamp}).`,
46
+ );
47
+ }
45
48
 
46
- // Wait until an L2 block is mined
47
- const sequencer = sequencerClient.getSequencer();
48
- const minTxsPerBlock = sequencer.getConfig().minTxsPerBlock;
49
- sequencer.updateConfig({ minTxsPerBlock: 0 });
49
+ const currentSlot = await this.rollup.getSlot();
50
+ const targetSlot = await this.rollup.getSlotAt(targetBigInt);
50
51
 
51
- await retryUntil(
52
- async () => {
53
- const newL2BlockNumber: BlockNumber = await node.getBlockNumber();
54
- return newL2BlockNumber > currentL2BlockNumber;
55
- },
56
- 'new block after warping L2 time',
57
- 36,
58
- 1,
59
- );
52
+ let effectiveTimestamp = targetBigInt;
60
53
 
61
- // Restore original minTxsPerBlock
62
- sequencer.updateConfig({ minTxsPerBlock });
54
+ if (targetSlot <= currentSlot) {
55
+ // Target lands in the same (or earlier) slot — auto-adjust to the next slot's start.
56
+ const nextSlot = SlotNumber(currentSlot + 1);
57
+ const nextSlotTimestamp = await this.rollup.getTimestampForSlot(nextSlot);
58
+ this.logger.warn(
59
+ `warpL2TimeAtLeastTo: target timestamp ${targetBigInt} falls in current slot ${currentSlot}. ` +
60
+ `Auto-adjusting to start of slot ${nextSlot} at timestamp ${nextSlotTimestamp}.`,
61
+ );
62
+ effectiveTimestamp = nextSlotTimestamp;
63
+ }
64
+
65
+ await this.eth.warp(effectiveTimestamp, { resetBlockInterval: true });
66
+ await node.mineBlock();
63
67
  }
64
68
 
65
69
  /**
66
70
  * Warps the L1 timestamp forward by a specified duration and mines an L2 block that advances the L2 timestamp at
67
- * least by the duration. L2 timestamp is not advanced exactly by the duration because it is determined by the slot
68
- * number, which advances in fixed intervals.
69
- * This is useful for testing time-dependent contract behavior.
70
- * @param sequencerClient - The sequencer client to use to force an empty block to be mined.
71
- * @param node - The Aztec node used to query if a new block has been mined.
71
+ * least by the duration. If the duration is too short to cross an L2 slot boundary, the warp is automatically
72
+ * extended to the start of the next slot so that `mineBlock()` succeeds.
73
+ * @param node - The Aztec node used to force an empty block to be mined.
72
74
  * @param duration - The duration to advance time by (in seconds)
73
75
  */
74
- async warpL2TimeAtLeastBy(sequencerClient: SequencerClient, node: AztecNode, duration: bigint | number) {
75
- const currentTimestamp = await this.eth.timestamp();
76
+ async warpL2TimeAtLeastBy(node: AztecNodeDebug, duration: bigint | number) {
77
+ if (BigInt(duration) <= 0n) {
78
+ throw new Error(`warpL2TimeAtLeastBy: duration must be positive, got ${duration} seconds.`);
79
+ }
80
+
81
+ const currentTimestamp = await this.eth.lastBlockTimestamp();
76
82
  const targetTimestamp = BigInt(currentTimestamp) + BigInt(duration);
77
- await this.warpL2TimeAtLeastTo(sequencerClient, node, targetTimestamp);
83
+ await this.warpL2TimeAtLeastTo(node, targetTimestamp);
78
84
  }
79
85
  }
@@ -4,7 +4,7 @@ import { type EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
4
  import type { Logger } from '@aztec/foundation/log';
5
5
  import { EpochMonitor } from '@aztec/prover-node';
6
6
  import type { EthAddress, L2BlockSource } from '@aztec/stdlib/block';
7
- import { computeL2ToL1MembershipWitnessFromMessagesInEpoch } from '@aztec/stdlib/messaging';
7
+ import { computeEpochOutHash } from '@aztec/stdlib/messaging';
8
8
 
9
9
  export class EpochTestSettler {
10
10
  private rollupCheatCodes: RollupCheatCodes;
@@ -51,9 +51,8 @@ export class EpochTestSettler {
51
51
  messagesInEpoch[checkpointIndex].push(block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs));
52
52
  }
53
53
 
54
- const [firstMessage] = messagesInEpoch.flat(3);
55
- if (firstMessage) {
56
- const { root: outHash } = computeL2ToL1MembershipWitnessFromMessagesInEpoch(messagesInEpoch, firstMessage);
54
+ const outHash = computeEpochOutHash(messagesInEpoch);
55
+ if (!outHash.isZero()) {
57
56
  await this.rollupCheatCodes.insertOutbox(epoch, outHash.toBigInt());
58
57
  } else {
59
58
  this.log.info(`No L2 to L1 messages in epoch ${epoch}`);
@@ -2,3 +2,4 @@ export { AnvilTestWatcher } from './anvil_test_watcher.js';
2
2
  export { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
3
3
  export { CheatCodes } from './cheat_codes.js';
4
4
  export { EpochTestSettler } from './epoch_test_settler.js';
5
+ export { getTokenAllowedSetupFunctions } from './token_allowed_setup.js';
@@ -0,0 +1,19 @@
1
+ import { TokenContractArtifact } from '@aztec/noir-contracts.js/Token';
2
+ import { buildAllowedElement } from '@aztec/p2p/msg_validators';
3
+ import { getContractClassFromArtifact } from '@aztec/stdlib/contract';
4
+ import type { AllowedElement } from '@aztec/stdlib/interfaces/server';
5
+
6
+ /**
7
+ * Returns Token-specific allowlist entries needed for FPC-based fee payments.
8
+ * These are test-only: FPC-based fee payment with custom tokens won't work on mainnet alpha.
9
+ */
10
+ export async function getTokenAllowedSetupFunctions(): Promise<AllowedElement[]> {
11
+ const tokenClassId = (await getContractClassFromArtifact(TokenContractArtifact)).id;
12
+ const target = { classId: tokenClassId };
13
+ return Promise.all([
14
+ // Token: needed for private transfers via FPC (transfer_to_public enqueues this)
15
+ buildAllowedElement(TokenContractArtifact, target, '_increase_public_balance', { onlySelf: true }),
16
+ // Token: needed for public transfers via FPC (fee_entrypoint_public enqueues this)
17
+ buildAllowedElement(TokenContractArtifact, target, 'transfer_in_public'),
18
+ ]);
19
+ }
@@ -1,2 +0,0 @@
1
- export declare const getCliVersion: () => any;
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVsZWFzZV92ZXJzaW9uLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY2xpL3JlbGVhc2VfdmVyc2lvbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFLQSxlQUFPLE1BQU0sYUFBYSxXQWV6QixDQUFDIn0=
@@ -1 +0,0 @@
1
- {"version":3,"file":"release_version.d.ts","sourceRoot":"","sources":["../../src/cli/release_version.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,aAAa,WAezB,CAAC"}
@@ -1,14 +0,0 @@
1
- import { fileURLToPath } from '@aztec/foundation/url';
2
- import { readFileSync } from 'fs';
3
- import { dirname, resolve } from 'path';
4
- export const getCliVersion = ()=>{
5
- const packageJsonPath = resolve(dirname(fileURLToPath(import.meta.url)), '../../package.json');
6
- const cliVersion = JSON.parse(readFileSync(packageJsonPath).toString()).version;
7
- // If the version is 0.1.0, this is a placeholder version and we are in a docker container; query release please for the latest version
8
- if (cliVersion === '0.1.0') {
9
- const releasePleasePath = resolve(dirname(fileURLToPath(import.meta.url)), '../../../../.release-please-manifest.json');
10
- const releaseVersion = JSON.parse(readFileSync(releasePleasePath).toString())['.'];
11
- return releaseVersion;
12
- }
13
- return cliVersion;
14
- };
@@ -1,47 +0,0 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs/promises';
3
- import path from 'path';
4
-
5
- // Simple script to extract a contract function as a separate Noir artifact.
6
- // We need to use this since the transpiling that we do on public functions make the contract artifacts
7
- // unreadable by noir tooling, since they are no longer following the noir artifact format.
8
- async function main() {
9
- let [contractArtifactPath, functionName] = process.argv.slice(2);
10
- if (!contractArtifactPath || !functionName) {
11
- console.log('Usage: node extractFunctionAsNoirArtifact.js <contractArtifactPath> <functionName>');
12
- return;
13
- }
14
-
15
- const contractArtifact = JSON.parse(await fs.readFile(contractArtifactPath, 'utf8'));
16
- const func = contractArtifact.functions.find(f => f.name === functionName);
17
- if (!func) {
18
- console.error(`Function ${functionName} not found in ${contractArtifactPath}`);
19
- return;
20
- }
21
-
22
- const artifact = {
23
- noir_version: contractArtifact.noir_version,
24
- hash: 0,
25
- abi: func.abi,
26
- bytecode: func.bytecode,
27
- debug_symbols: func.debug_symbols,
28
- file_map: contractArtifact.file_map,
29
- expression_width: {
30
- Bounded: {
31
- width: 4,
32
- },
33
- },
34
- };
35
-
36
- const outputDir = path.dirname(contractArtifactPath);
37
- const outputName = path.basename(contractArtifactPath, '.json') + `-${functionName}.json`;
38
-
39
- const outPath = path.join(outputDir, outputName);
40
-
41
- await fs.writeFile(outPath, JSON.stringify(artifact, null, 2));
42
- }
43
-
44
- main().catch(err => {
45
- console.error(err);
46
- process.exit(1);
47
- });