@aztec/ethereum 0.0.1-commit.f2ce05ee → 0.0.1-commit.f5a9928

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 (181) hide show
  1. package/dest/client.d.ts +27 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +63 -8
  4. package/dest/config.d.ts +17 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +38 -10
  7. package/dest/contracts/chain_state_override.d.ts +78 -0
  8. package/dest/contracts/chain_state_override.d.ts.map +1 -0
  9. package/dest/contracts/chain_state_override.js +137 -0
  10. package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
  11. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  12. package/dest/contracts/fee_asset_price_oracle.js +656 -0
  13. package/dest/contracts/governance.d.ts +135 -35
  14. package/dest/contracts/governance.d.ts.map +1 -1
  15. package/dest/contracts/governance.js +229 -18
  16. package/dest/contracts/governance_proposer.d.ts +33 -2
  17. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  18. package/dest/contracts/governance_proposer.js +54 -6
  19. package/dest/contracts/gse.d.ts +4 -2
  20. package/dest/contracts/gse.d.ts.map +1 -1
  21. package/dest/contracts/gse.js +2 -2
  22. package/dest/contracts/inbox.d.ts +3 -3
  23. package/dest/contracts/inbox.d.ts.map +1 -1
  24. package/dest/contracts/inbox.js +12 -7
  25. package/dest/contracts/index.d.ts +4 -3
  26. package/dest/contracts/index.d.ts.map +1 -1
  27. package/dest/contracts/index.js +3 -2
  28. package/dest/contracts/multicall.d.ts +127 -12
  29. package/dest/contracts/multicall.d.ts.map +1 -1
  30. package/dest/contracts/multicall.js +201 -94
  31. package/dest/contracts/outbox.d.ts +27 -4
  32. package/dest/contracts/outbox.d.ts.map +1 -1
  33. package/dest/contracts/outbox.js +34 -7
  34. package/dest/contracts/registry.d.ts +3 -1
  35. package/dest/contracts/registry.d.ts.map +1 -1
  36. package/dest/contracts/registry.js +30 -1
  37. package/dest/contracts/rollup.d.ts +5437 -34
  38. package/dest/contracts/rollup.d.ts.map +1 -1
  39. package/dest/contracts/rollup.js +448 -104
  40. package/dest/contracts/slashing_proposer.d.ts +171 -0
  41. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  42. package/dest/contracts/slashing_proposer.js +753 -0
  43. package/dest/contracts/watch_event.d.ts +36 -0
  44. package/dest/contracts/watch_event.d.ts.map +1 -0
  45. package/dest/contracts/watch_event.js +66 -0
  46. package/dest/deploy_aztec_l1_contracts.d.ts +5 -9
  47. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  48. package/dest/deploy_aztec_l1_contracts.js +48 -27
  49. package/dest/deploy_l1_contract.js +3 -3
  50. package/dest/foundry_binary.d.ts +13 -0
  51. package/dest/foundry_binary.d.ts.map +1 -0
  52. package/dest/foundry_binary.js +52 -0
  53. package/dest/generated/l1-contracts-defaults.d.ts +3 -3
  54. package/dest/generated/l1-contracts-defaults.js +3 -3
  55. package/dest/l1_artifacts.d.ts +15524 -15847
  56. package/dest/l1_artifacts.d.ts.map +1 -1
  57. package/dest/l1_artifacts.js +9 -24
  58. package/dest/l1_contract_addresses.d.ts +61 -65
  59. package/dest/l1_contract_addresses.d.ts.map +1 -1
  60. package/dest/l1_contract_addresses.js +101 -82
  61. package/dest/l1_reader.d.ts +5 -5
  62. package/dest/l1_reader.d.ts.map +1 -1
  63. package/dest/l1_reader.js +9 -7
  64. package/dest/l1_tx_utils/config.d.ts +7 -1
  65. package/dest/l1_tx_utils/config.d.ts.map +1 -1
  66. package/dest/l1_tx_utils/config.js +17 -4
  67. package/dest/l1_tx_utils/factory.d.ts +18 -10
  68. package/dest/l1_tx_utils/factory.d.ts.map +1 -1
  69. package/dest/l1_tx_utils/factory.js +17 -7
  70. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +1 -1
  71. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +1 -1
  72. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +15 -15
  73. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -1
  74. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +9 -15
  75. package/dest/l1_tx_utils/index-blobs.d.ts +3 -3
  76. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -1
  77. package/dest/l1_tx_utils/index-blobs.js +2 -2
  78. package/dest/l1_tx_utils/index.d.ts +2 -1
  79. package/dest/l1_tx_utils/index.d.ts.map +1 -1
  80. package/dest/l1_tx_utils/index.js +1 -0
  81. package/dest/l1_tx_utils/l1_tx_utils.d.ts +26 -7
  82. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  83. package/dest/l1_tx_utils/l1_tx_utils.js +156 -79
  84. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  85. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  86. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +57 -23
  87. package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
  88. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  89. package/dest/{test → l1_tx_utils}/tx_delayer.js +67 -37
  90. package/dest/publisher_manager.d.ts +34 -8
  91. package/dest/publisher_manager.d.ts.map +1 -1
  92. package/dest/publisher_manager.js +119 -8
  93. package/dest/queries.d.ts +13 -2
  94. package/dest/queries.d.ts.map +1 -1
  95. package/dest/queries.js +62 -3
  96. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  97. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  98. package/dest/test/blob_kzg_warmup.js +64 -0
  99. package/dest/test/chain_monitor.d.ts +55 -4
  100. package/dest/test/chain_monitor.d.ts.map +1 -1
  101. package/dest/test/chain_monitor.js +104 -3
  102. package/dest/test/eth_cheat_codes.d.ts +31 -6
  103. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  104. package/dest/test/eth_cheat_codes.js +67 -44
  105. package/dest/test/index.d.ts +2 -3
  106. package/dest/test/index.d.ts.map +1 -1
  107. package/dest/test/index.js +1 -2
  108. package/dest/test/recording_rpc_server.d.ts +18 -0
  109. package/dest/test/recording_rpc_server.d.ts.map +1 -0
  110. package/dest/test/recording_rpc_server.js +68 -0
  111. package/dest/test/rollup_cheat_codes.d.ts +60 -3
  112. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  113. package/dest/test/rollup_cheat_codes.js +86 -7
  114. package/dest/test/start_anvil.d.ts +23 -3
  115. package/dest/test/start_anvil.d.ts.map +1 -1
  116. package/dest/test/start_anvil.js +182 -32
  117. package/dest/test/upgrade_utils.js +2 -2
  118. package/dest/utils.d.ts +9 -2
  119. package/dest/utils.d.ts.map +1 -1
  120. package/dest/utils.js +59 -24
  121. package/package.json +6 -8
  122. package/src/client.ts +72 -2
  123. package/src/config.ts +58 -14
  124. package/src/contracts/chain_state_override.ts +200 -0
  125. package/src/contracts/fee_asset_price_oracle.ts +285 -0
  126. package/src/contracts/governance.ts +313 -13
  127. package/src/contracts/governance_proposer.ts +58 -9
  128. package/src/contracts/gse.ts +7 -2
  129. package/src/contracts/inbox.ts +13 -5
  130. package/src/contracts/index.ts +3 -2
  131. package/src/contracts/multicall.ts +243 -105
  132. package/src/contracts/outbox.ts +42 -8
  133. package/src/contracts/registry.ts +31 -1
  134. package/src/contracts/rollup.ts +507 -109
  135. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +119 -45
  136. package/src/contracts/watch_event.ts +110 -0
  137. package/src/deploy_aztec_l1_contracts.ts +75 -39
  138. package/src/deploy_l1_contract.ts +3 -3
  139. package/src/foundry_binary.ts +57 -0
  140. package/src/generated/l1-contracts-defaults.ts +3 -3
  141. package/src/l1_artifacts.ts +12 -35
  142. package/src/l1_contract_addresses.ts +120 -94
  143. package/src/l1_reader.ts +17 -10
  144. package/src/l1_tx_utils/config.ts +23 -3
  145. package/src/l1_tx_utils/factory.ts +31 -31
  146. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +1 -1
  147. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +1 -1
  148. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +43 -54
  149. package/src/l1_tx_utils/index-blobs.ts +2 -2
  150. package/src/l1_tx_utils/index.ts +1 -0
  151. package/src/l1_tx_utils/l1_tx_utils.ts +149 -64
  152. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +57 -17
  153. package/src/{test → l1_tx_utils}/tx_delayer.ts +93 -56
  154. package/src/publisher_manager.ts +143 -12
  155. package/src/queries.ts +70 -4
  156. package/src/test/blob_kzg_warmup.ts +65 -0
  157. package/src/test/chain_monitor.ts +148 -3
  158. package/src/test/eth_cheat_codes.ts +63 -47
  159. package/src/test/index.ts +1 -2
  160. package/src/test/recording_rpc_server.ts +69 -0
  161. package/src/test/rollup_cheat_codes.ts +115 -6
  162. package/src/test/start_anvil.ts +212 -32
  163. package/src/test/upgrade_utils.ts +2 -2
  164. package/src/utils.ts +56 -29
  165. package/dest/contracts/empire_slashing_proposer.d.ts +0 -67
  166. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  167. package/dest/contracts/empire_slashing_proposer.js +0 -207
  168. package/dest/contracts/tally_slashing_proposer.d.ts +0 -140
  169. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  170. package/dest/contracts/tally_slashing_proposer.js +0 -320
  171. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +0 -26
  172. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +0 -1
  173. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +0 -26
  174. package/dest/test/delayed_tx_utils.d.ts +0 -13
  175. package/dest/test/delayed_tx_utils.d.ts.map +0 -1
  176. package/dest/test/delayed_tx_utils.js +0 -28
  177. package/dest/test/tx_delayer.d.ts +0 -36
  178. package/dest/test/tx_delayer.d.ts.map +0 -1
  179. package/src/contracts/empire_slashing_proposer.ts +0 -259
  180. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +0 -77
  181. package/src/test/delayed_tx_utils.ts +0 -52
@@ -1,25 +1,27 @@
1
+ import type { BlobKzgInstance } from '@aztec/blob-lib/types';
1
2
  import { EthAddress } from '@aztec/foundation/eth-address';
2
3
  import type { Logger } from '@aztec/foundation/log';
3
4
  import type { DateProvider } from '@aztec/foundation/timer';
4
5
 
5
6
  import { type Hex, encodeFunctionData } from 'viem';
6
7
 
7
- import type { EthSigner } from '../eth-signer/eth-signer.js';
8
8
  import { FORWARDER_ABI } from '../forwarder_proxy.js';
9
- import type { ExtendedViemWalletClient, ViemClient } from '../types.js';
9
+ import type { ViemClient } from '../types.js';
10
10
  import type { L1TxUtilsConfig } from './config.js';
11
+ import type { L1SignerSource } from './factory.js';
12
+ import { resolveSignerSource } from './factory.js';
11
13
  import type { IL1TxMetrics, IL1TxStore } from './interfaces.js';
12
- import { L1TxUtilsWithBlobs } from './l1_tx_utils_with_blobs.js';
13
- import { createViemSigner } from './signer.js';
14
+ import { L1TxUtils } from './l1_tx_utils.js';
15
+ import { Delayer } from './tx_delayer.js';
14
16
  import type { L1BlobInputs, L1TxConfig, L1TxRequest, SigningCallback } from './types.js';
15
17
 
16
18
  /**
17
- * Extends L1TxUtilsWithBlobs to wrap all transactions through a forwarder contract.
19
+ * Extends L1TxUtils to wrap all transactions through a forwarder contract.
18
20
  * This is mainly used for testing the archiver's ability to decode transactions that go through proxies.
19
21
  */
20
- export class ForwarderL1TxUtils extends L1TxUtilsWithBlobs {
22
+ export class ForwarderL1TxUtils extends L1TxUtils {
21
23
  constructor(
22
- client: ViemClient | ExtendedViemWalletClient,
24
+ client: ViemClient,
23
25
  senderAddress: EthAddress,
24
26
  signingCallback: SigningCallback,
25
27
  logger: Logger | undefined,
@@ -28,9 +30,23 @@ export class ForwarderL1TxUtils extends L1TxUtilsWithBlobs {
28
30
  debugMaxGasLimit: boolean,
29
31
  store: IL1TxStore | undefined,
30
32
  metrics: IL1TxMetrics | undefined,
33
+ kzg: BlobKzgInstance | undefined,
34
+ delayer: Delayer | undefined,
31
35
  private readonly forwarderAddress: EthAddress,
32
36
  ) {
33
- super(client, senderAddress, signingCallback, logger, dateProvider, config, debugMaxGasLimit, store, metrics);
37
+ super(
38
+ client,
39
+ senderAddress,
40
+ signingCallback,
41
+ logger,
42
+ dateProvider,
43
+ config,
44
+ debugMaxGasLimit,
45
+ store,
46
+ metrics,
47
+ kzg,
48
+ delayer,
49
+ );
34
50
  }
35
51
 
36
52
  /**
@@ -61,59 +77,32 @@ export class ForwarderL1TxUtils extends L1TxUtilsWithBlobs {
61
77
  }
62
78
  }
63
79
 
64
- export function createForwarderL1TxUtilsFromViemWallet(
65
- client: ExtendedViemWalletClient,
80
+ export function createForwarderL1TxUtils(
81
+ source: L1SignerSource,
66
82
  forwarderAddress: EthAddress,
67
- deps: {
83
+ deps?: {
68
84
  logger?: Logger;
69
85
  dateProvider?: DateProvider;
70
86
  store?: IL1TxStore;
71
87
  metrics?: IL1TxMetrics;
72
- } = {},
73
- config: Partial<L1TxUtilsConfig> = {},
74
- debugMaxGasLimit: boolean = false,
75
- ) {
88
+ kzg?: BlobKzgInstance;
89
+ delayer?: Delayer;
90
+ },
91
+ config?: Partial<L1TxUtilsConfig> & { debugMaxGasLimit?: boolean },
92
+ ): ForwarderL1TxUtils {
93
+ const { client, address, signingCallback } = resolveSignerSource(source);
76
94
  return new ForwarderL1TxUtils(
77
95
  client,
78
- EthAddress.fromString(client.account.address),
79
- createViemSigner(client),
80
- deps.logger,
81
- deps.dateProvider,
82
- config,
83
- debugMaxGasLimit,
84
- deps.store,
85
- deps.metrics,
86
- forwarderAddress,
87
- );
88
- }
89
-
90
- export function createForwarderL1TxUtilsFromEthSigner(
91
- client: ViemClient,
92
- signer: EthSigner,
93
- forwarderAddress: EthAddress,
94
- deps: {
95
- logger?: Logger;
96
- dateProvider?: DateProvider;
97
- store?: IL1TxStore;
98
- metrics?: IL1TxMetrics;
99
- } = {},
100
- config: Partial<L1TxUtilsConfig> = {},
101
- debugMaxGasLimit: boolean = false,
102
- ) {
103
- const callback: SigningCallback = async (transaction, _signingAddress) => {
104
- return (await signer.signTransaction(transaction)).toViemTransactionSignature();
105
- };
106
-
107
- return new ForwarderL1TxUtils(
108
- client,
109
- signer.address,
110
- callback,
111
- deps.logger,
112
- deps.dateProvider,
113
- config,
114
- debugMaxGasLimit,
115
- deps.store,
116
- deps.metrics,
96
+ address,
97
+ signingCallback,
98
+ deps?.logger,
99
+ deps?.dateProvider,
100
+ config ?? {},
101
+ config?.debugMaxGasLimit ?? false,
102
+ deps?.store,
103
+ deps?.metrics,
104
+ deps?.kzg,
105
+ deps?.delayer,
117
106
  forwarderAddress,
118
107
  );
119
108
  }
@@ -1,2 +1,2 @@
1
- export * from './forwarder_l1_tx_utils.js';
2
- export * from './l1_tx_utils_with_blobs.js';
1
+ export { createForwarderL1TxUtils, ForwarderL1TxUtils } from './forwarder_l1_tx_utils.js';
2
+ export { createL1TxUtils, type L1SignerSource, resolveSignerSource } from './factory.js';
@@ -8,6 +8,7 @@ export * from './l1_tx_utils.js';
8
8
  export * from './readonly_l1_tx_utils.js';
9
9
  export * from './signer.js';
10
10
  export * from './types.js';
11
+ export * from './tx_delayer.js';
11
12
  export * from './utils.js';
12
13
 
13
14
  // Note: We intentionally do not export l1_tx_utils_with_blobs.js
@@ -1,9 +1,11 @@
1
+ import type { BlobKzgInstance } from '@aztec/blob-lib/types';
1
2
  import { maxBigint } from '@aztec/foundation/bigint';
2
3
  import { merge, pick } from '@aztec/foundation/collection';
3
4
  import { InterruptError, TimeoutError } from '@aztec/foundation/error';
4
5
  import { EthAddress } from '@aztec/foundation/eth-address';
5
- import { type Logger, createLogger } from '@aztec/foundation/log';
6
- import { retryUntil } from '@aztec/foundation/retry';
6
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
7
+ import { Semaphore } from '@aztec/foundation/queue';
8
+ import { makeBackoff, retry, retryUntil } from '@aztec/foundation/retry';
7
9
  import { sleep } from '@aztec/foundation/sleep';
8
10
  import { DateProvider } from '@aztec/foundation/timer';
9
11
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
@@ -13,16 +15,13 @@ import {
13
15
  type Abi,
14
16
  type BlockOverrides,
15
17
  type Hex,
16
- type NonceManager,
17
18
  type PrepareTransactionRequestRequest,
18
19
  type StateOverride,
19
20
  type TransactionReceipt,
20
21
  type TransactionSerializable,
21
- createNonceManager,
22
22
  formatGwei,
23
23
  serializeTransaction,
24
24
  } from 'viem';
25
- import { jsonRpc } from 'viem/nonce';
26
25
 
27
26
  import type { ViemClient } from '../types.js';
28
27
  import { formatViemError } from '../utils.js';
@@ -30,6 +29,7 @@ import { type L1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
30
29
  import { MAX_L1_TX_LIMIT } from './constants.js';
31
30
  import type { IL1TxMetrics, IL1TxStore } from './interfaces.js';
32
31
  import { ReadOnlyL1TxUtils } from './readonly_l1_tx_utils.js';
32
+ import { Delayer, createDelayer, wrapClientWithDelayer } from './tx_delayer.js';
33
33
  import {
34
34
  DroppedTransactionError,
35
35
  type L1BlobInputs,
@@ -44,9 +44,21 @@ 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
- protected nonceManager: NonceManager;
49
53
  protected txs: L1TxState[] = [];
54
+ /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */
55
+ private lastSentNonce: number | undefined;
56
+ /** Mutex to prevent concurrent sendTransaction calls from racing on the same nonce. */
57
+ private readonly sendMutex = new Semaphore(1);
58
+ /** Tx delayer for testing. Only set when enableDelayer config is true. */
59
+ public delayer?: Delayer;
60
+ /** KZG instance for blob operations. */
61
+ protected kzg?: BlobKzgInstance;
50
62
 
51
63
  constructor(
52
64
  public override client: ViemClient,
@@ -58,9 +70,25 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
58
70
  debugMaxGasLimit: boolean = false,
59
71
  protected store?: IL1TxStore,
60
72
  protected metrics?: IL1TxMetrics,
73
+ kzg?: BlobKzgInstance,
74
+ delayer?: Delayer,
61
75
  ) {
62
76
  super(client, logger, dateProvider, config, debugMaxGasLimit);
63
- this.nonceManager = createNonceManager({ source: jsonRpc() });
77
+ this.kzg = kzg;
78
+
79
+ // Set up delayer: use provided one or create new
80
+ if (config?.enableDelayer && config?.ethereumSlotDuration) {
81
+ this.delayer =
82
+ delayer ?? this.createDelayer({ ethereumSlotDuration: config.ethereumSlotDuration }, logger.getBindings());
83
+ this.client = wrapClientWithDelayer(this.client, this.delayer);
84
+ if (config.txDelayerMaxInclusionTimeIntoSlot !== undefined) {
85
+ this.delayer.setMaxInclusionTimeIntoSlot(config.txDelayerMaxInclusionTimeIntoSlot);
86
+ }
87
+ } else if (delayer) {
88
+ // Delayer provided but enableDelayer not set — just store it without wrapping
89
+ logger.warn('Delayer provided but enableDelayer config is not set; delayer will not be used');
90
+ this.delayer = delayer;
91
+ }
64
92
  }
65
93
 
66
94
  public get state() {
@@ -87,6 +115,11 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
87
115
  this.metrics?.recordMinedTx(l1TxState, new Date(l1Timestamp));
88
116
  } else if (newState === TxUtilsState.NOT_MINED) {
89
117
  this.metrics?.recordDroppedTx(l1TxState);
118
+ // The tx was dropped: the chain nonce reverted to l1TxState.nonce, so our lower bound is
119
+ // no longer valid. Clear it so the next send fetches the real nonce from the chain.
120
+ if (this.lastSentNonce === l1TxState.nonce) {
121
+ this.lastSentNonce = undefined;
122
+ }
90
123
  }
91
124
 
92
125
  // Update state in the store
@@ -103,6 +136,14 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
103
136
  );
104
137
  }
105
138
 
139
+ /**
140
+ * Clears the cached `lastSentNonce` so the next `sendTransaction` call fetches the real
141
+ * nonce from the chain. Call this after an L1 reorg to prevent stale nonce references.
142
+ */
143
+ public resetNonce(): void {
144
+ this.lastSentNonce = undefined;
145
+ }
146
+
106
147
  public getSenderAddress() {
107
148
  return this.address;
108
149
  }
@@ -185,6 +226,19 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
185
226
  return await this.signTransaction(txRequest as TransactionSerializable);
186
227
  }
187
228
 
229
+ private async checkInterruptedOrTimedOut(gasConfig: Pick<L1TxConfig, 'txTimeoutAt'>): Promise<Date> {
230
+ if (this.interrupted) {
231
+ throw new InterruptError(`Transaction sending is interrupted`);
232
+ }
233
+ const now = new Date(await this.getL1Timestamp());
234
+ if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
235
+ throw new TimeoutError(
236
+ `Transaction timed out before sending (now ${now.toISOString()} > timeoutAt ${gasConfig.txTimeoutAt.toISOString()})`,
237
+ );
238
+ }
239
+ return now;
240
+ }
241
+
188
242
  /**
189
243
  * Sends a transaction with gas estimation and pricing
190
244
  * @param request - The transaction request (to, data, value)
@@ -197,14 +251,15 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
197
251
  blobInputs?: L1BlobInputs,
198
252
  stateChange: TxUtilsState = TxUtilsState.SENT,
199
253
  ): Promise<{ txHash: Hex; state: L1TxState }> {
200
- if (this.interrupted) {
201
- throw new InterruptError(`Transaction sending is interrupted`);
202
- }
203
-
204
254
  try {
205
255
  const gasConfig = merge(this.config, gasConfigOverrides);
206
256
  const account = this.getSenderAddress().toString();
207
257
 
258
+ // Fail fast before doing any work (gas estimation, balance check) if we've been interrupted
259
+ // or if the caller's deadline has already passed. The same check is repeated after gas
260
+ // estimation in case it took long enough to push us past the deadline.
261
+ await this.checkInterruptedOrTimedOut(gasConfig);
262
+
208
263
  let gasLimit: bigint;
209
264
  if (this.debugMaxGasLimit) {
210
265
  gasLimit = MAX_L1_TX_LIMIT;
@@ -217,34 +272,34 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
217
272
 
218
273
  const gasPrice = await this.getGasPrice(gasConfig, !!blobInputs);
219
274
 
220
- if (this.interrupted) {
221
- throw new InterruptError(`Transaction sending is interrupted`);
222
- }
223
-
224
- const nonce = await this.nonceManager.consume({
225
- client: this.client,
226
- address: account,
227
- chainId: this.client.chain.id,
228
- });
275
+ const now = await this.checkInterruptedOrTimedOut(gasConfig);
229
276
 
230
- const baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
231
- const txData = this.makeTxData(baseState, { isCancelTx: false });
277
+ let txHash: Hex;
278
+ let nonce: number;
279
+ let baseState: Pick<L1TxState, 'request' | 'gasLimit' | 'blobInputs' | 'gasPrice' | 'nonce'>;
232
280
 
233
- const now = new Date(await this.getL1Timestamp());
234
- if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
235
- throw new TimeoutError(
236
- `Transaction timed out before sending (now ${now.toISOString()} > timeoutAt ${gasConfig.txTimeoutAt.toISOString()})`,
237
- );
281
+ await this.sendMutex.acquire();
282
+ try {
283
+ const chainNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
284
+ // If a fallback RPC node returns a stale count (lower than what we last sent), use our
285
+ // local lower bound to avoid sending a duplicate of an already-pending transaction.
286
+ nonce =
287
+ this.lastSentNonce !== undefined && chainNonce <= this.lastSentNonce ? this.lastSentNonce + 1 : chainNonce;
288
+
289
+ baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
290
+ const txData = this.makeTxData(baseState, { isCancelTx: false });
291
+
292
+ const signedRequest = await this.prepareSignedTransaction(txData);
293
+ txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
294
+ this.lastSentNonce = nonce;
295
+ } finally {
296
+ this.sendMutex.release();
238
297
  }
239
298
 
240
- // Send the new tx
241
- const signedRequest = await this.prepareSignedTransaction(txData);
242
- const txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
243
-
244
299
  // Create the new state for monitoring
245
300
  const l1TxState: L1TxState = {
246
301
  ...baseState,
247
- id: (await this.store?.consumeNextStateId(account)) ?? Math.max(...this.txs.map(tx => tx.id), 0),
302
+ id: (await this.store?.consumeNextStateId(account)) ?? Math.max(...this.txs.map(tx => tx.id), -1) + 1,
248
303
  txHashes: [txHash],
249
304
  cancelTxHashes: [],
250
305
  status: TxUtilsState.IDLE,
@@ -381,10 +436,23 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
381
436
 
382
437
  const initialTxHash = txHashes[0];
383
438
  let currentTxHash = txHashes.at(-1)!;
384
- let l1Timestamp: number;
439
+ let l1Timestamp = 0;
385
440
 
386
441
  while (true) {
387
- 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
+ }
388
456
 
389
457
  try {
390
458
  const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
@@ -423,7 +491,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
423
491
  { nonce, account, pendingNonce, timePassed },
424
492
  );
425
493
  await this.updateState(state, TxUtilsState.NOT_MINED);
426
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
427
494
  throw new DroppedTransactionError(nonce, account);
428
495
  }
429
496
 
@@ -515,12 +582,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
515
582
 
516
583
  // Oh no, the transaction has timed out!
517
584
  if (isCancelTx || !gasConfig.cancelTxOnTimeout) {
518
- // If this was already a cancellation tx, or we are configured to not cancel txs, we just mark it as NOT_MINED
519
- // and reset the nonce manager, so the next tx that comes along can reuse the nonce if/when this tx gets dropped.
520
- // This is the nastiest scenario for us, since the new tx could acquire the next nonce, but then this tx is dropped,
521
- // and the new tx would never get mined. Eventually, the new tx would also drop.
522
585
  await this.updateState(state, TxUtilsState.NOT_MINED);
523
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
524
586
  } else {
525
587
  // Otherwise we fire the cancellation without awaiting to avoid blocking the caller,
526
588
  // and monitor it in the background so we can speed it up as needed.
@@ -623,14 +685,14 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
623
685
  ): Promise<{ gasUsed: bigint; result: `0x${string}` }> {
624
686
  const blockOverrides = { ..._blockOverrides };
625
687
  const gasConfig = merge(this.config, _gasConfig);
626
- const gasPrice = await this.getGasPrice(gasConfig, false);
627
688
 
689
+ // Fee fields are deliberately omitted. Supplying them makes the node apply the EIP-1559 upfront funds
690
+ // check (sender balance >= gas * maxFeePerGas) against the worst-case gas cap below, which rejects the
691
+ // whole simulation request before any execution. Omitted fee fields default to a zero gas price.
628
692
  const call: any = {
629
693
  to: request.to!,
630
694
  data: request.data,
631
695
  from: request.from ?? this.getSenderAddress().toString(),
632
- maxFeePerGas: gasPrice.maxFeePerGas,
633
- maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas,
634
696
  gas: request.gas ?? MAX_L1_TX_LIMIT,
635
697
  };
636
698
 
@@ -639,7 +701,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
639
701
  blockOverrides.gasLimit = MAX_L1_TX_LIMIT;
640
702
  }
641
703
 
642
- return this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
704
+ return await this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
643
705
  }
644
706
 
645
707
  /**
@@ -659,34 +721,48 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
659
721
  { nonce, account },
660
722
  );
661
723
  await this.updateState(state, TxUtilsState.NOT_MINED);
662
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
663
724
  return;
664
725
  }
665
726
 
666
- // Check if the original tx is still pending
667
- const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
668
- 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) {
669
758
  this.logger.verbose(
670
759
  `Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`,
671
760
  { nonce, account, currentNonce },
672
761
  );
673
762
  await this.updateState(state, TxUtilsState.NOT_MINED);
674
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
675
763
  return;
676
764
  }
677
765
 
678
- // Get gas price with higher priority fee for cancellation
679
- const cancelGasPrice = await this.getGasPrice(
680
- {
681
- ...this.config,
682
- // Use high bump for cancellation to ensure it replaces the original tx
683
- priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
684
- },
685
- isBlobTx,
686
- state.txHashes.length,
687
- previousGasPrice,
688
- );
689
-
690
766
  const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelGasPrice;
691
767
  this.logger.verbose(
692
768
  `Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`,
@@ -731,8 +807,17 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
731
807
  return Number(timestamp) * 1000;
732
808
  }
733
809
 
734
- /** Makes empty blob inputs for the cancellation tx. To be overridden in L1TxUtilsWithBlobs. */
735
- protected makeEmptyBlobInputs(_maxFeePerBlobGas: bigint): Required<L1BlobInputs> {
736
- throw new Error('Cannot make empty blob inputs for cancellation');
810
+ /** Makes empty blob inputs for the cancellation tx. */
811
+ protected makeEmptyBlobInputs(maxFeePerBlobGas: bigint): Required<L1BlobInputs> {
812
+ if (!this.kzg) {
813
+ throw new Error('Cannot make empty blob inputs for cancellation without kzg');
814
+ }
815
+ const blobData = new Uint8Array(131072).fill(0);
816
+ return { blobs: [blobData], kzg: this.kzg, maxFeePerBlobGas };
817
+ }
818
+
819
+ /** Creates a new delayer instance. */
820
+ protected createDelayer(opts: { ethereumSlotDuration: bigint | number }, bindings: LoggerBindings): Delayer {
821
+ return createDelayer(this.dateProvider, opts, bindings);
737
822
  }
738
823
  }
@@ -3,6 +3,7 @@ import type { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
4
  import { makeBackoff, retry } from '@aztec/foundation/retry';
5
5
  import { DateProvider } from '@aztec/foundation/timer';
6
+ import { getErrorCause } from '@aztec/foundation/types';
6
7
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
7
8
 
8
9
  import pickBy from 'lodash.pickby';
@@ -16,6 +17,7 @@ import {
16
17
  type Hex,
17
18
  MethodNotFoundRpcError,
18
19
  MethodNotSupportedRpcError,
20
+ RpcRequestError,
19
21
  type StateOverride,
20
22
  decodeErrorResult,
21
23
  formatGwei,
@@ -23,6 +25,7 @@ import {
23
25
  hexToBytes,
24
26
  } from 'viem';
25
27
 
28
+ import { getL1RpcErrorCode } from '../client.js';
26
29
  import type { ViemClient } from '../types.js';
27
30
  import { type L1TxUtilsConfig, defaultL1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
28
31
  import {
@@ -39,6 +42,23 @@ import { getCalldataGasUsage, tryGetCustomErrorNameContractFunction } from './ut
39
42
  // Change this to the current strategy we want to use
40
43
  const CurrentStrategy: PriorityFeeStrategy = P75AllTxsPriorityFeeStrategy;
41
44
 
45
+ /** Error code returned by eth_simulateV1 for `insufficient funds for gas * price + value`. */
46
+ const INSUFFICIENT_FUNDS_RPC_ERROR_CODE = -38014;
47
+
48
+ /**
49
+ * Returns true when an RPC transport error reports the node's upfront funds check
50
+ * (sender balance >= gasLimit * maxFeePerGas) rejecting the request. Matches on the message as well as on the
51
+ * error code, since RPC gateways differ in how they wrap node errors. Apply this only to transport errors: an
52
+ * execution revert string can mention insufficient funds without being this kind of rejection.
53
+ */
54
+ function isInsufficientFundsRpcError(err: unknown): boolean {
55
+ if (getL1RpcErrorCode(err) === INSUFFICIENT_FUNDS_RPC_ERROR_CODE) {
56
+ return true;
57
+ }
58
+ const messages = [err, getErrorCause(err, RpcRequestError)].map(e => (e instanceof Error ? e.message : '')).join(' ');
59
+ return /insufficient funds/i.test(messages);
60
+ }
61
+
42
62
  export class ReadOnlyL1TxUtils {
43
63
  public config: Required<L1TxUtilsConfig>;
44
64
  protected interrupted = false;
@@ -130,9 +150,10 @@ export class ReadOnlyL1TxUtils {
130
150
  const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
131
151
  for (let i = 0; i < numBlocks; i++) {
132
152
  // each block can go up 12.5% from previous baseFee
133
- maxFeePerGas = (maxFeePerGas * (1_000n + 125n)) / 1_000n;
153
+ // ceil, (a+b-1)/b, to avoid truncation at small values (e.g. 1 wei blob base fee)
154
+ maxFeePerGas = (maxFeePerGas * (1_000n + 125n) + 999n) / 1_000n;
134
155
  // same for blob gas fee
135
- maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n)) / 1_000n;
156
+ maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n) + 999n) / 1_000n;
136
157
  }
137
158
 
138
159
  if (attempt > 0) {
@@ -242,13 +263,16 @@ export class ReadOnlyL1TxUtils {
242
263
  const gasConfig = { ...this.config, ..._gasConfig };
243
264
  let initialEstimate = 0n;
244
265
  if (_blobInputs) {
245
- // @note requests with blobs also require maxFeePerBlobGas to be set
266
+ // @note requests with blobs also require maxFeePerBlobGas to be set.
267
+ // Use 2x buffer for maxFeePerBlobGas to avoid stale fees and to pass EIP-4844 validation (even if it is a gas estimation call).
268
+ // 1. maxFeePerBlobGas >= blobBaseFee
269
+ // 2. account balance >= gas * maxFeePerGas + maxFeePerBlobGas * blobCount + value
246
270
  const gasPrice = await this.getGasPrice(gasConfig, true, 0);
247
271
  initialEstimate = await this.client.estimateGas({
248
272
  account,
249
273
  ...request,
250
274
  ..._blobInputs,
251
- maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
275
+ maxFeePerBlobGas: gasPrice.maxFeePerBlobGas! * 2n,
252
276
  gas: MAX_L1_TX_LIMIT,
253
277
  blockTag: 'latest',
254
278
  });
@@ -368,8 +392,8 @@ export class ReadOnlyL1TxUtils {
368
392
  gasConfig: L1TxUtilsConfig & { fallbackGasEstimate?: bigint },
369
393
  abi: Abi,
370
394
  ) {
371
- try {
372
- const result = await this.client.simulateBlocks({
395
+ const simulateBlocks = () =>
396
+ this.client.simulateBlocks({
373
397
  validation: false,
374
398
  blocks: [
375
399
  {
@@ -380,18 +404,13 @@ export class ReadOnlyL1TxUtils {
380
404
  ],
381
405
  });
382
406
 
383
- if (result[0].calls[0].status === 'failure') {
384
- this.logger?.error('L1 transaction simulation failed', result[0].calls[0].error);
385
- const decodedError = decodeErrorResult({ abi, data: result[0].calls[0].data });
386
-
387
- throw new Error(
388
- `L1 transaction simulation failed with error ${decodedError.errorName}(${decodedError.args?.join(',')})`,
389
- );
390
- }
391
- this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
392
- return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
407
+ // Only the request itself is wrapped, so that transport-level rejections are never confused with an
408
+ // execution revert (whose decoded revert string could well mention insufficient funds too).
409
+ let result: Awaited<ReturnType<typeof simulateBlocks>>;
410
+ try {
411
+ result = await simulateBlocks();
393
412
  } catch (err) {
394
- if (err instanceof MethodNotFoundRpcError || err instanceof MethodNotSupportedRpcError) {
413
+ if (getErrorCause(err, MethodNotFoundRpcError) || getErrorCause(err, MethodNotSupportedRpcError)) {
395
414
  if (gasConfig.fallbackGasEstimate) {
396
415
  this.logger?.warn(
397
416
  `Node does not support eth_simulateV1 API. Using fallback gas estimate: ${gasConfig.fallbackGasEstimate}`,
@@ -400,8 +419,29 @@ export class ReadOnlyL1TxUtils {
400
419
  }
401
420
  this.logger?.error('Node does not support eth_simulateV1 API');
402
421
  }
422
+ if (isInsufficientFundsRpcError(err)) {
423
+ const rpcError = getErrorCause(err, RpcRequestError);
424
+ const providerMessage = rpcError?.details ?? (err instanceof Error ? err.message : String(err));
425
+ const gas = call?.gas !== undefined ? `, gas ${call.gas}` : '';
426
+ throw new Error(
427
+ `L1 node rejected the eth_simulateV1 request with an insufficient funds error before executing it ` +
428
+ `(sender ${call?.from ?? 'unknown'}${gas}): ${providerMessage}`,
429
+ { cause: err },
430
+ );
431
+ }
403
432
  throw err;
404
433
  }
434
+
435
+ if (result[0].calls[0].status === 'failure') {
436
+ this.logger?.error('L1 transaction simulation failed', result[0].calls[0].error);
437
+ const decodedError = decodeErrorResult({ abi, data: result[0].calls[0].data });
438
+
439
+ throw new Error(
440
+ `L1 transaction simulation failed with error ${decodedError.errorName}(${decodedError.args?.join(',')})`,
441
+ );
442
+ }
443
+ this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
444
+ return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
405
445
  }
406
446
 
407
447
  public bumpGasLimit(gasLimit: bigint, _gasConfig?: L1TxUtilsConfig): bigint {