@aztec/ethereum 5.0.0-rc.2 → 5.0.1

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 (47) hide show
  1. package/dest/config.d.ts +10 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +24 -0
  4. package/dest/deploy_aztec_l1_contracts.d.ts +2 -2
  5. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  6. package/dest/deploy_aztec_l1_contracts.js +13 -4
  7. package/dest/foundry_binary.d.ts +13 -0
  8. package/dest/foundry_binary.d.ts.map +1 -0
  9. package/dest/foundry_binary.js +52 -0
  10. package/dest/l1_tx_utils/config.js +3 -3
  11. package/dest/l1_tx_utils/l1_tx_utils.d.ts +1 -1
  12. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  13. package/dest/l1_tx_utils/l1_tx_utils.js +57 -15
  14. package/dest/publisher_manager.d.ts +18 -6
  15. package/dest/publisher_manager.d.ts.map +1 -1
  16. package/dest/publisher_manager.js +35 -6
  17. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  18. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  19. package/dest/test/blob_kzg_warmup.js +64 -0
  20. package/dest/test/chain_monitor.d.ts +33 -2
  21. package/dest/test/chain_monitor.d.ts.map +1 -1
  22. package/dest/test/chain_monitor.js +71 -6
  23. package/dest/test/eth_cheat_codes.d.ts +20 -3
  24. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  25. package/dest/test/eth_cheat_codes.js +50 -40
  26. package/dest/test/index.d.ts +2 -1
  27. package/dest/test/index.d.ts.map +1 -1
  28. package/dest/test/index.js +1 -0
  29. package/dest/test/rollup_cheat_codes.d.ts +30 -1
  30. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  31. package/dest/test/rollup_cheat_codes.js +27 -0
  32. package/dest/test/start_anvil.d.ts +1 -1
  33. package/dest/test/start_anvil.d.ts.map +1 -1
  34. package/dest/test/start_anvil.js +41 -5
  35. package/package.json +5 -5
  36. package/src/config.ts +35 -0
  37. package/src/deploy_aztec_l1_contracts.ts +18 -5
  38. package/src/foundry_binary.ts +57 -0
  39. package/src/l1_tx_utils/config.ts +3 -3
  40. package/src/l1_tx_utils/l1_tx_utils.ts +52 -18
  41. package/src/publisher_manager.ts +44 -17
  42. package/src/test/blob_kzg_warmup.ts +65 -0
  43. package/src/test/chain_monitor.ts +88 -5
  44. package/src/test/eth_cheat_codes.ts +47 -43
  45. package/src/test/index.ts +1 -0
  46. package/src/test/rollup_cheat_codes.ts +51 -0
  47. package/src/test/start_anvil.ts +38 -6
@@ -1,16 +1,41 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
3
- import { fileURLToPath } from '@aztec/foundation/url';
4
3
  import { spawn } from 'child_process';
5
- import { dirname, resolve } from 'path';
4
+ import { resolveFoundryBinary } from '../foundry_binary.js';
5
+ // Watchdog wrapper: instead of spawning anvil directly, we spawn a small bash supervisor that runs
6
+ // anvil as a background child and polls its own parent (this node process). If the parent dies for
7
+ // ANY reason — including SIGKILL / crash / OOM, where node's own exit handlers never run — the poll
8
+ // loop ends and the EXIT trap reaps anvil. The script is inlined (rather than shipped as a `.sh`) so
9
+ // it works from the published npm tarball too, and the resolved anvil binary is passed via
10
+ // `$ANVIL_BIN` so it works without `anvil` on PATH.
11
+ //
12
+ // `$@` is the anvil argv; `bash -c <script> bash <...args>` puts the args in `$@` and `$0` = 'bash'.
13
+ //
14
+ // The EXIT trap reaps anvil; INT/TERM just `exit` (which fires the EXIT trap) so a signal terminates
15
+ // the supervisor promptly instead of being swallowed — a trapped TERM does NOT terminate the shell,
16
+ // so trapping the kill directly on TERM would leave the poll loop running and the caller's teardown
17
+ // hanging until its SIGKILL escalation. `sleep & wait` makes the poll interruptible, so INT/TERM are
18
+ // handled immediately rather than after the current `sleep` returns.
19
+ const ANVIL_WATCHDOG = `
20
+ set -u
21
+ parent=$PPID
22
+ "$ANVIL_BIN" "$@" &
23
+ anvil_pid=$!
24
+ trap 'kill "$anvil_pid" 2>/dev/null' EXIT
25
+ trap 'exit 0' INT TERM
26
+ while kill -0 "$parent" 2>/dev/null; do sleep 1 & wait $!; done
27
+ `;
6
28
  /**
7
29
  * Ensures there's a running Anvil instance and returns the RPC URL.
8
30
  */ export async function startAnvil(opts = {}) {
9
- const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
31
+ const anvilBinary = resolveFoundryBinary('anvil');
10
32
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
11
33
  const methodCalls = opts.captureMethodCalls ? [] : undefined;
12
34
  let detectedPort;
13
35
  const anvil = await retry(async ()=>{
36
+ // `--port 0` lets anvil bind an OS-assigned ephemeral port; the actual port is read back from
37
+ // its "Listening on host:port" stdout below, so independent suites can spawn their own anvil
38
+ // in parallel without fighting over a fixed port.
14
39
  const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
15
40
  const args = [
16
41
  '--host',
@@ -31,7 +56,14 @@ import { dirname, resolve } from 'path';
31
56
  args.push('--hardfork', opts.hardfork);
32
57
  }
33
58
  args.push('--slots-in-an-epoch', String(opts.slotsInAnEpoch ?? 1));
34
- const child = spawn(anvilBinary, args, {
59
+ // Spawn the watchdog (see ANVIL_WATCHDOG). It launches anvil with these args and reaps it if we
60
+ // die; `$0` is 'bash' and `$@` is the anvil argv.
61
+ const child = spawn('bash', [
62
+ '-c',
63
+ ANVIL_WATCHDOG,
64
+ 'bash',
65
+ ...args
66
+ ], {
35
67
  stdio: [
36
68
  'ignore',
37
69
  'pipe',
@@ -39,6 +71,7 @@ import { dirname, resolve } from 'path';
39
71
  ],
40
72
  env: {
41
73
  ...process.env,
74
+ ANVIL_BIN: anvilBinary,
42
75
  RAYON_NUM_THREADS: '1'
43
76
  }
44
77
  });
@@ -139,7 +172,10 @@ import { dirname, resolve } from 'path';
139
172
  }
140
173
  }
141
174
  }
142
- /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */ function killChild(child) {
175
+ /**
176
+ * Send SIGTERM to the watchdog, wait up to 5 s, then SIGKILL. The watchdog's trap forwards the
177
+ * signal to anvil, so terminating it tears down anvil too. All timers are always cleared.
178
+ */ function killChild(child) {
143
179
  return new Promise((resolve)=>{
144
180
  if (child.exitCode !== null || child.killed) {
145
181
  child.stdout?.destroy();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/ethereum",
3
- "version": "5.0.0-rc.2",
3
+ "version": "5.0.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./account": "./dest/account.js",
@@ -50,10 +50,10 @@
50
50
  "../package.common.json"
51
51
  ],
52
52
  "dependencies": {
53
- "@aztec/blob-lib": "5.0.0-rc.2",
54
- "@aztec/constants": "5.0.0-rc.2",
55
- "@aztec/foundation": "5.0.0-rc.2",
56
- "@aztec/l1-artifacts": "5.0.0-rc.2",
53
+ "@aztec/blob-lib": "5.0.1",
54
+ "@aztec/constants": "5.0.1",
55
+ "@aztec/foundation": "5.0.1",
56
+ "@aztec/l1-artifacts": "5.0.1",
57
57
  "dotenv": "^16.0.3",
58
58
  "lodash.chunk": "^4.2.0",
59
59
  "lodash.pickby": "^4.5.0",
package/src/config.ts CHANGED
@@ -246,6 +246,41 @@ export const l1ContractsConfigMappings: ConfigMappingsType<L1ContractsConfig> =
246
246
  */
247
247
  export const DefaultL1ContractsConfig = getDefaultConfig(l1ContractsConfigMappings);
248
248
 
249
+ /**
250
+ * Validates that `ethereumSlotDuration` and `aztecSlotDuration` are positive and that the L2 slot is an exact
251
+ * multiple of the L1 slot. Every L2 slot boundary must land on an L1 slot boundary; a non-multiple pairing
252
+ * desyncs the epoch/checkpoint timing math throughout the sequencer, validator client, and timetables. Returns
253
+ * a list of error messages (empty when valid).
254
+ */
255
+ export function validateSlotDurations(
256
+ config: Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'>,
257
+ ): string[] {
258
+ const errors: string[] = [];
259
+ if (config.ethereumSlotDuration <= 0) {
260
+ errors.push(`ethereumSlotDuration must be positive (got ${config.ethereumSlotDuration})`);
261
+ }
262
+ if (config.aztecSlotDuration <= 0) {
263
+ errors.push(`aztecSlotDuration must be positive (got ${config.aztecSlotDuration})`);
264
+ }
265
+ if (config.ethereumSlotDuration > 0 && config.aztecSlotDuration % config.ethereumSlotDuration !== 0) {
266
+ errors.push(
267
+ `aztecSlotDuration (${config.aztecSlotDuration}s) must be a multiple of ethereumSlotDuration ` +
268
+ `(${config.ethereumSlotDuration}s)`,
269
+ );
270
+ }
271
+ return errors;
272
+ }
273
+
274
+ /** Throws if {@link validateSlotDurations} reports any errors. */
275
+ export function assertValidSlotDurations(
276
+ config: Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'>,
277
+ ): void {
278
+ const errors = validateSlotDurations(config);
279
+ if (errors.length > 0) {
280
+ throw new Error(`Invalid slot duration configuration:\n${errors.map(e => ` - ${e}`).join('\n')}`);
281
+ }
282
+ }
283
+
249
284
  export const genesisStateConfigMappings: ConfigMappingsType<GenesisStateConfig> = {
250
285
  testAccounts: {
251
286
  env: 'TEST_ACCOUNTS',
@@ -19,9 +19,10 @@ import { mainnet, sepolia } from 'viem/chains';
19
19
 
20
20
  import { createEthereumChain, isAnvilTestChain } from './chain.js';
21
21
  import { createExtendedL1Client } from './client.js';
22
- import type { L1ContractsConfig } from './config.js';
22
+ import { type L1ContractsConfig, assertValidSlotDurations } from './config.js';
23
23
  import { deployMulticall3 } from './contracts/multicall.js';
24
24
  import { RollupContract } from './contracts/rollup.js';
25
+ import { resolveFoundryBinary } from './foundry_binary.js';
25
26
  import type { L1ContractAddresses } from './l1_contract_addresses.js';
26
27
  import type { ExtendedViemWalletClient } from './types.js';
27
28
 
@@ -93,11 +94,16 @@ function runProcess<T>(
93
94
 
94
95
  // Covers an edge where where we may have a cached BlobLib that is not meant for production.
95
96
  // Despite the profile apparently sometimes cached code remains (so says Lasse after his ignition-monorepo arc).
96
- async function maybeForgeForceProductionBuild(l1ContractsPath: string, script: string, chainId: number) {
97
+ async function maybeForgeForceProductionBuild(
98
+ forgeBin: string,
99
+ l1ContractsPath: string,
100
+ script: string,
101
+ chainId: number,
102
+ ) {
97
103
  if (chainId === mainnet.id) {
98
104
  logger.info(`Recompiling ${script} with production profile for mainnet deployment`);
99
105
  logger.info('This may take a minute but ensures production BlobLib is used.');
100
- await runProcess('forge', ['build', script, '--force'], { FOUNDRY_PROFILE: 'production' }, l1ContractsPath);
106
+ await runProcess(forgeBin, ['build', script, '--force'], { FOUNDRY_PROFILE: 'production' }, l1ContractsPath);
101
107
  }
102
108
  }
103
109
 
@@ -282,6 +288,7 @@ export async function deployAztecL1Contracts(
282
288
  args: DeployAztecL1ContractsArgs,
283
289
  ): Promise<DeployAztecL1ContractsReturnType> {
284
290
  logger.info(`Deploying L1 contracts with config: ${jsonStringify(args)}`);
291
+ assertValidSlotDurations(args);
285
292
  if (args.initialValidators && args.initialValidators.length > 0 && args.existingTokenAddress) {
286
293
  throw new Error(
287
294
  'Cannot deploy with both initialValidators and existingTokenAddress. ' +
@@ -319,8 +326,9 @@ export async function deployAztecL1Contracts(
319
326
  // Use foundry-artifacts from l1-artifacts package
320
327
  const l1ContractsPath = prepareL1ContractsForDeployment();
321
328
 
329
+ const forgeBin = resolveFoundryBinary('forge');
322
330
  const FORGE_SCRIPT = 'script/deploy/DeployAztecL1Contracts.s.sol';
323
- await maybeForgeForceProductionBuild(l1ContractsPath, FORGE_SCRIPT, chainId);
331
+ await maybeForgeForceProductionBuild(forgeBin, l1ContractsPath, FORGE_SCRIPT, chainId);
324
332
 
325
333
  // Verify contracts on Etherscan when on mainnet/sepolia and ETHERSCAN_API_KEY is available.
326
334
  const isVerifiableChain = chainId === mainnet.id || chainId === sepolia.id;
@@ -345,6 +353,8 @@ export async function deployAztecL1Contracts(
345
353
  ...(shouldVerify ? ['--verify'] : []),
346
354
  ];
347
355
  const forgeEnv = {
356
+ // Resolved forge binary picked up by forge_broadcast.js, so it works without forge on PATH.
357
+ FORGE_BIN: forgeBin,
348
358
  // Env vars required by l1-contracts/script/deploy/DeploymentConfiguration.sol.
349
359
  NETWORK: getActiveNetworkName(),
350
360
  FOUNDRY_PROFILE: chainId === mainnet.id ? 'production' : undefined,
@@ -612,12 +622,15 @@ export const deployRollupForUpgrade = async (
612
622
  // Use foundry-artifacts from l1-artifacts package
613
623
  const l1ContractsPath = prepareL1ContractsForDeployment();
614
624
 
625
+ const forgeBin = resolveFoundryBinary('forge');
615
626
  const FORGE_SCRIPT = 'script/deploy/DeployRollupForUpgrade.s.sol';
616
- await maybeForgeForceProductionBuild(l1ContractsPath, FORGE_SCRIPT, chainId);
627
+ await maybeForgeForceProductionBuild(forgeBin, l1ContractsPath, FORGE_SCRIPT, chainId);
617
628
 
618
629
  const scriptPath = join(getL1ContractsPath(), 'scripts', 'forge_broadcast.js');
619
630
  const forgeArgs = [FORGE_SCRIPT, '--sig', 'run()', '--private-key', privateKey, '--rpc-url', rpcUrl];
620
631
  const forgeEnv = {
632
+ // Resolved forge binary picked up by forge_broadcast.js, so it works without forge on PATH.
633
+ FORGE_BIN: forgeBin,
621
634
  FOUNDRY_PROFILE: chainId === mainnet.id ? 'production' : undefined,
622
635
  // Env vars required by l1-contracts/script/deploy/RollupConfiguration.sol.
623
636
  REGISTRY_ADDRESS: registryAddress.toString(),
@@ -0,0 +1,57 @@
1
+ import { spawnSync } from 'child_process';
2
+ import { accessSync, constants } from 'fs';
3
+ import { homedir } from 'os';
4
+ import { join } from 'path';
5
+
6
+ function isExecutable(path: string): boolean {
7
+ try {
8
+ accessSync(path, constants.X_OK);
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Locate a Foundry binary (`anvil`, `forge`, ...) without relying on the caller's PATH. Order:
17
+ * 1. `$<NAME>_BIN` (e.g. `$ANVIL_BIN`, `$FORGE_BIN`) — explicit override, e.g. for CI with a pinned
18
+ * version. Throws if set but not pointing at an executable, instead of silently falling back.
19
+ * 2. `~/.aztec/current/internal-bin/<name>` — where aztec-up installs it.
20
+ * 3. `~/.aztec/current/bin/aztec-<name>` — the publicly-exposed symlink.
21
+ * 4. `~/.foundry/bin/<name>` — standalone foundryup install.
22
+ * 5. `command -v <name>` — anything else on PATH.
23
+ *
24
+ * Throws with a directive message if none work.
25
+ */
26
+ export function resolveFoundryBinary(name: string): string {
27
+ const envVar = `${name.toUpperCase()}_BIN`;
28
+ const envBin = process.env[envVar];
29
+ if (envBin) {
30
+ if (!isExecutable(envBin)) {
31
+ throw new Error(`$${envVar} is set to ${envBin}, which does not exist or is not executable.`);
32
+ }
33
+ return envBin;
34
+ }
35
+
36
+ const candidates = [
37
+ join(homedir(), '.aztec', 'current', 'internal-bin', name),
38
+ join(homedir(), '.aztec', 'current', 'bin', `aztec-${name}`),
39
+ join(homedir(), '.foundry', 'bin', name),
40
+ ];
41
+ for (const path of candidates) {
42
+ if (isExecutable(path)) {
43
+ return path;
44
+ }
45
+ }
46
+
47
+ const which = spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' });
48
+ if (which.status === 0 && which.stdout.trim()) {
49
+ return which.stdout.trim();
50
+ }
51
+
52
+ throw new Error(
53
+ `${name} binary not found. Tried $${envVar}, ~/.aztec/current/internal-bin/${name}, ` +
54
+ `~/.aztec/current/bin/aztec-${name}, ~/.foundry/bin/${name}, and $PATH. ` +
55
+ `Install via \`aztec-up\` or set ${envVar} to a working binary.`,
56
+ );
57
+ }
@@ -73,7 +73,7 @@ export const l1TxUtilsConfigMappings: ConfigMappingsType<L1TxUtilsConfig> = {
73
73
  gasLimitBufferPercentage: {
74
74
  description: 'How much to increase calculated gas limit by (percentage)',
75
75
  env: 'L1_GAS_LIMIT_BUFFER_PERCENTAGE',
76
- ...numberConfigHelper(20),
76
+ ...floatConfigHelper(20),
77
77
  },
78
78
  maxGwei: {
79
79
  description: 'Maximum gas price in gwei to be used for transactions.',
@@ -90,12 +90,12 @@ export const l1TxUtilsConfigMappings: ConfigMappingsType<L1TxUtilsConfig> = {
90
90
  priorityFeeBumpPercentage: {
91
91
  description: 'How much to increase priority fee by each attempt (percentage)',
92
92
  env: 'L1_PRIORITY_FEE_BUMP_PERCENTAGE',
93
- ...numberConfigHelper(20),
93
+ ...floatConfigHelper(20),
94
94
  },
95
95
  priorityFeeRetryBumpPercentage: {
96
96
  description: 'How much to increase priority fee by each retry attempt (percentage)',
97
97
  env: 'L1_PRIORITY_FEE_RETRY_BUMP_PERCENTAGE',
98
- ...numberConfigHelper(50),
98
+ ...floatConfigHelper(50),
99
99
  },
100
100
  minimumPriorityFeePerGas: {
101
101
  description:
@@ -5,7 +5,7 @@ import { InterruptError, TimeoutError } from '@aztec/foundation/error';
5
5
  import { EthAddress } from '@aztec/foundation/eth-address';
6
6
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
7
7
  import { Semaphore } from '@aztec/foundation/queue';
8
- import { retryUntil } from '@aztec/foundation/retry';
8
+ import { makeBackoff, retry, retryUntil } from '@aztec/foundation/retry';
9
9
  import { sleep } from '@aztec/foundation/sleep';
10
10
  import { DateProvider } from '@aztec/foundation/timer';
11
11
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
@@ -44,6 +44,11 @@ import {
44
44
 
45
45
  const MAX_L1_TX_STATES = 32;
46
46
 
47
+ // Backoff (in seconds) for retrying the read-only RPC calls that prepare a tx cancellation. A
48
+ // cancellation is fired in the background after a tx times out and is important (it frees the stuck
49
+ // nonce), so a transient RPC failure while reading the pending nonce or gas price must not abandon it.
50
+ const CANCELLATION_PREP_RETRY_BACKOFF_S = [1, 2, 4, 8];
51
+
47
52
  export class L1TxUtils extends ReadOnlyL1TxUtils {
48
53
  protected txs: L1TxState[] = [];
49
54
  /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */
@@ -431,10 +436,23 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
431
436
 
432
437
  const initialTxHash = txHashes[0];
433
438
  let currentTxHash = txHashes.at(-1)!;
434
- let l1Timestamp: number;
439
+ let l1Timestamp = 0;
435
440
 
436
441
  while (true) {
437
- l1Timestamp = await this.getL1Timestamp();
442
+ try {
443
+ l1Timestamp = await this.getL1Timestamp();
444
+ } catch (err) {
445
+ // A transient RPC failure here must not abort monitoring with a rejection: callers that
446
+ // fire this loop in the background would surface it as an unhandled rejection (e.g. when a
447
+ // test tears down its L1 node while a monitor iteration is in flight). Exit quietly if we
448
+ // are shutting down, otherwise retry on the next interval.
449
+ if (this.interrupted) {
450
+ break;
451
+ }
452
+ this.logger.error(`Error fetching L1 timestamp while monitoring tx ${currentTxHash}`, err, { nonce, account });
453
+ await sleep(gasConfig.checkIntervalMs!);
454
+ continue;
455
+ }
438
456
 
439
457
  try {
440
458
  const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
@@ -706,9 +724,37 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
706
724
  return;
707
725
  }
708
726
 
709
- // Check if the original tx is still pending
710
- const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
711
- if (currentNonce < nonce) {
727
+ // Resolve the pending nonce and cancellation gas price up front. These are read-only RPC calls, so
728
+ // they are safe to retry; a transient RPC failure here must not permanently abandon the cancellation
729
+ // (which would leave the nonce stuck and the tx state stranded short of CANCELLED). We retry with a
730
+ // real backoff before giving up, unlike getGasPrice's tight internal retry which can be exhausted by
731
+ // a brief node hiccup. The retried block performs no state-changing send, so retrying cannot
732
+ // double-send the cancellation tx.
733
+ const { currentNonce, cancelGasPrice } = await retry(
734
+ async () => {
735
+ const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
736
+ if (currentNonce >= nonce) {
737
+ // Get gas price with higher priority fee for cancellation
738
+ const cancelGasPrice = await this.getGasPrice(
739
+ {
740
+ ...this.config,
741
+ // Use high bump for cancellation to ensure it replaces the original tx
742
+ priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
743
+ },
744
+ isBlobTx,
745
+ state.txHashes.length,
746
+ previousGasPrice,
747
+ );
748
+ return { currentNonce, cancelGasPrice };
749
+ }
750
+ return { currentNonce, cancelGasPrice: undefined };
751
+ },
752
+ `Preparing cancellation for L1 tx from account ${account} with nonce ${nonce}`,
753
+ makeBackoff(CANCELLATION_PREP_RETRY_BACKOFF_S),
754
+ this.logger,
755
+ );
756
+
757
+ if (cancelGasPrice === undefined) {
712
758
  this.logger.verbose(
713
759
  `Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`,
714
760
  { nonce, account, currentNonce },
@@ -717,18 +763,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
717
763
  return;
718
764
  }
719
765
 
720
- // Get gas price with higher priority fee for cancellation
721
- const cancelGasPrice = await this.getGasPrice(
722
- {
723
- ...this.config,
724
- // Use high bump for cancellation to ensure it replaces the original tx
725
- priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
726
- },
727
- isBlobTx,
728
- state.txHashes.length,
729
- previousGasPrice,
730
- );
731
-
732
766
  const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelGasPrice;
733
767
  this.logger.verbose(
734
768
  `Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`,
@@ -40,11 +40,12 @@ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
40
40
  private log: Logger;
41
41
  private config: PublisherManagerConfig;
42
42
  private static readonly FUNDING_CHECK_INTERVAL_MS = 2 * 60 * 1000;
43
- private funder?: UtilsType;
44
- private fundingPromise?: RunningPromise;
43
+ protected funder?: UtilsType;
44
+ protected readonly fundingPromise?: RunningPromise;
45
+ private started = false;
45
46
 
46
47
  constructor(
47
- private publishers: UtilsType[],
48
+ protected publishers: UtilsType[],
48
49
  config: PublisherManagerConfig,
49
50
  opts?: { bindings?: LoggerBindings; funder?: UtilsType },
50
51
  ) {
@@ -67,34 +68,60 @@ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
67
68
  this.funder = undefined;
68
69
  }
69
70
  }
71
+
72
+ if (this.funder && hasThreshold && hasAmount) {
73
+ this.fundingPromise = new RunningPromise(
74
+ () => this.triggerFundingIfNeeded(),
75
+ this.log,
76
+ PublisherManager.FUNDING_CHECK_INTERVAL_MS,
77
+ );
78
+ }
70
79
  }
71
80
 
72
- /** Loads the state of all publishers and the funder, and starts periodic funding checks. */
81
+ /**
82
+ * Clears any interrupted flag left by a previous {@link stop} so publishing works again after a restart,
83
+ * loads the state of all publishers and the funder, and starts periodic funding checks. Idempotent: a
84
+ * start while already started is a no-op, so it never re-runs `loadStateAndResumeMonitoring` (which
85
+ * would spawn a duplicate background monitor per pending nonce). Lifecycle calls are expected to be
86
+ * serialized by the caller.
87
+ */
73
88
  public async start(): Promise<void> {
89
+ if (this.started) {
90
+ this.log.debug('PublisherManager already started, ignoring start');
91
+ return;
92
+ }
93
+
94
+ // Clear the interrupted flag set by a previous stop() so a restarted manager can publish again.
95
+ // On a first start this is a no-op (the flag is already clear).
96
+ this.publishers.forEach(pub => pub.restart());
97
+ this.funder?.restart();
98
+
74
99
  await Promise.all([
75
100
  ...this.publishers.map(pub => pub.loadStateAndResumeMonitoring()),
76
101
  this.funder?.loadStateAndResumeMonitoring(),
77
102
  ]);
78
103
 
79
- if (
80
- this.funder &&
81
- this.config.publisherFundingThreshold !== undefined &&
82
- this.config.publisherFundingAmount !== undefined
83
- ) {
84
- this.fundingPromise = new RunningPromise(
85
- () => this.triggerFundingIfNeeded(),
86
- this.log,
87
- PublisherManager.FUNDING_CHECK_INTERVAL_MS,
88
- );
89
- this.fundingPromise.start();
90
- }
104
+ this.fundingPromise?.start();
105
+ // Marked started only once fully up, so a start that failed to load state can be retried.
106
+ this.started = true;
91
107
  }
92
108
 
93
- /** Stops the funding loop and interrupts all publishers. */
109
+ /**
110
+ * Stops the funding loop, interrupts all publishers so no further L1 txs are sent, and waits (bounded)
111
+ * for their in-flight tx monitor loops to wind down. Idempotent, and the manager may be restarted
112
+ * afterwards via {@link start}, which clears the interrupted flag.
113
+ */
94
114
  public async stop(): Promise<void> {
115
+ this.started = false;
95
116
  await this.fundingPromise?.stop();
96
117
  this.publishers.forEach(pub => pub.interrupt());
97
118
  this.funder?.interrupt();
119
+ // Wait for in-flight tx monitor loops to observe the interrupt, so no L1 requests are still
120
+ // being issued after shutdown (e.g. against an anvil instance a test is about to tear down).
121
+ await Promise.all([
122
+ ...this.publishers.map(pub => pub.waitMonitoringStopped()),
123
+ this.funder?.waitMonitoringStopped(),
124
+ ]);
98
125
  }
99
126
 
100
127
  // Finds and prioritises available publishers based on
@@ -0,0 +1,65 @@
1
+ import { getBytesPerBlob, getBytesPerCommitment, getKzg } from '@aztec/blob-lib';
2
+ import type { Logger } from '@aztec/foundation/log';
3
+
4
+ import type { ExtendedViemWalletClient } from '../types.js';
5
+
6
+ /**
7
+ * Warms both KZG trusted setups in parallel for tests against a local anvil:
8
+ * - anvil's own setup, loaded lazily when it first validates a blob sidecar in `eth_sendRawTransaction`
9
+ * - our `@crate-crypto/node-eth-kzg` singleton (`getKzg()`, a ~2.2s synchronous precomp build)
10
+ *
11
+ * Without this, the first checkpoint publish pays both serially (~4.4s). The recipe does all RPC round
12
+ * trips up front, fires a single bare raw send carrying a fake (garbage) blob sidecar that anvil rejects
13
+ * after loading its trusted setup, yields once to flush the socket write, then synchronously builds our
14
+ * own precomp tables while anvil warms in parallel. The fake tx is rejected at admission, so it never
15
+ * enters the pool, mines no block, and burns no nonce — sending it from the passed client is harmless.
16
+ *
17
+ * Best-effort: any failure is debug-logged and swallowed, leaving lazy init as the fallback. Never throws.
18
+ *
19
+ * @param l1Client - The L1 client whose account sends the (rejected) warm-up blob tx.
20
+ */
21
+ export async function warmBlobKzg(l1Client: ExtendedViemWalletClient, logger?: Logger): Promise<void> {
22
+ try {
23
+ // A pure-JS fake kzg: returns deterministic garbage of the correct lengths (commitment and proof are
24
+ // both 48 bytes). It makes viem build a syntactically valid sidecar without initializing any native
25
+ // module, so anvil loads its trusted setup to validate the (invalid) proof and then rejects the tx.
26
+ const fakeKzg = {
27
+ blobToKzgCommitment: () => {
28
+ const commitment = new Uint8Array(getBytesPerCommitment());
29
+ commitment.fill(0xab);
30
+ commitment[0] = 0xc0;
31
+ return commitment;
32
+ },
33
+ computeBlobKzgProof: () => {
34
+ const proof = new Uint8Array(getBytesPerCommitment());
35
+ proof.fill(0xcd);
36
+ proof[0] = 0xc0;
37
+ return proof;
38
+ },
39
+ };
40
+
41
+ // All RPC round trips (nonce, fees, gas) happen here, so only a single socket write remains to flush.
42
+ const prepared = await l1Client.prepareTransactionRequest({
43
+ blobs: [new Uint8Array(getBytesPerBlob())],
44
+ kzg: fakeKzg,
45
+ to: '0x0000000000000000000000000000000000000000',
46
+ value: 0n,
47
+ maxFeePerBlobGas: 1_000_000_000_000n,
48
+ });
49
+ const serialized = await l1Client.signTransaction(prepared);
50
+
51
+ // Fire the raw send without awaiting and swallow the expected rejection.
52
+ const sent = l1Client.request({ method: 'eth_sendRawTransaction', params: [serialized] }).catch(() => {});
53
+
54
+ // Flush the single socket write so anvil receives the tx and starts loading its trusted setup in its
55
+ // own process before we block the event loop below.
56
+ await new Promise(resolve => setImmediate(resolve));
57
+
58
+ // Synchronously build our precomp tables (~2.2s, event-loop-blocking); anvil warms in parallel.
59
+ getKzg();
60
+
61
+ await sent;
62
+ } catch (err) {
63
+ logger?.debug('Failed to warm blob KZG; falling back to lazy init', { err });
64
+ }
65
+ }