@aztec/ethereum 0.0.1-commit.d431d1c → 0.0.1-commit.d58ff9d0

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 (187) hide show
  1. package/dest/client.d.ts +25 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +60 -8
  4. package/dest/config.d.ts +31 -8
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +74 -14
  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_handler.d.ts +1 -1
  11. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  12. package/dest/contracts/fee_asset_handler.js +2 -0
  13. package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
  14. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  15. package/dest/contracts/fee_asset_price_oracle.js +656 -0
  16. package/dest/contracts/governance.d.ts +110 -33
  17. package/dest/contracts/governance.d.ts.map +1 -1
  18. package/dest/contracts/governance.js +207 -16
  19. package/dest/contracts/governance_proposer.d.ts +33 -1
  20. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  21. package/dest/contracts/governance_proposer.js +57 -3
  22. package/dest/contracts/gse.d.ts +4 -2
  23. package/dest/contracts/gse.d.ts.map +1 -1
  24. package/dest/contracts/gse.js +2 -2
  25. package/dest/contracts/inbox.d.ts +3 -3
  26. package/dest/contracts/inbox.d.ts.map +1 -1
  27. package/dest/contracts/inbox.js +12 -7
  28. package/dest/contracts/index.d.ts +4 -3
  29. package/dest/contracts/index.d.ts.map +1 -1
  30. package/dest/contracts/index.js +3 -2
  31. package/dest/contracts/multicall.d.ts +130 -13
  32. package/dest/contracts/multicall.d.ts.map +1 -1
  33. package/dest/contracts/multicall.js +203 -93
  34. package/dest/contracts/outbox.d.ts +27 -4
  35. package/dest/contracts/outbox.d.ts.map +1 -1
  36. package/dest/contracts/outbox.js +34 -7
  37. package/dest/contracts/registry.d.ts +3 -1
  38. package/dest/contracts/registry.d.ts.map +1 -1
  39. package/dest/contracts/registry.js +30 -1
  40. package/dest/contracts/rollup.d.ts +5422 -33
  41. package/dest/contracts/rollup.d.ts.map +1 -1
  42. package/dest/contracts/rollup.js +409 -78
  43. package/dest/contracts/{tally_slashing_proposer.d.ts → slashing_proposer.d.ts} +3 -4
  44. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  45. package/dest/contracts/{tally_slashing_proposer.js → slashing_proposer.js} +18 -13
  46. package/dest/deploy_aztec_l1_contracts.d.ts +21 -12
  47. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  48. package/dest/deploy_aztec_l1_contracts.js +66 -39
  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/l1_artifacts.d.ts +16231 -15758
  54. package/dest/l1_artifacts.d.ts.map +1 -1
  55. package/dest/l1_artifacts.js +9 -24
  56. package/dest/l1_contract_addresses.d.ts +61 -65
  57. package/dest/l1_contract_addresses.d.ts.map +1 -1
  58. package/dest/l1_contract_addresses.js +101 -82
  59. package/dest/l1_reader.d.ts +5 -5
  60. package/dest/l1_reader.d.ts.map +1 -1
  61. package/dest/l1_reader.js +9 -7
  62. package/dest/l1_tx_utils/config.d.ts +7 -1
  63. package/dest/l1_tx_utils/config.d.ts.map +1 -1
  64. package/dest/l1_tx_utils/config.js +17 -4
  65. package/dest/l1_tx_utils/constants.d.ts +1 -1
  66. package/dest/l1_tx_utils/constants.js +2 -2
  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_fee_analyzer.d.ts +23 -4
  82. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -1
  83. package/dest/l1_tx_utils/l1_fee_analyzer.js +65 -3
  84. package/dest/l1_tx_utils/l1_tx_utils.d.ts +26 -7
  85. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  86. package/dest/l1_tx_utils/l1_tx_utils.js +185 -88
  87. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  88. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  89. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +13 -8
  90. package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
  91. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  92. package/dest/{test → l1_tx_utils}/tx_delayer.js +67 -37
  93. package/dest/l1_tx_utils/types.d.ts +27 -1
  94. package/dest/l1_tx_utils/types.d.ts.map +1 -1
  95. package/dest/l1_tx_utils/types.js +10 -0
  96. package/dest/publisher_manager.d.ts +34 -7
  97. package/dest/publisher_manager.d.ts.map +1 -1
  98. package/dest/publisher_manager.js +119 -8
  99. package/dest/queries.d.ts +13 -2
  100. package/dest/queries.d.ts.map +1 -1
  101. package/dest/queries.js +70 -4
  102. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  103. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  104. package/dest/test/blob_kzg_warmup.js +64 -0
  105. package/dest/test/chain_monitor.d.ts +55 -4
  106. package/dest/test/chain_monitor.d.ts.map +1 -1
  107. package/dest/test/chain_monitor.js +104 -3
  108. package/dest/test/eth_cheat_codes.d.ts +37 -6
  109. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  110. package/dest/test/eth_cheat_codes.js +89 -41
  111. package/dest/test/index.d.ts +2 -3
  112. package/dest/test/index.d.ts.map +1 -1
  113. package/dest/test/index.js +1 -2
  114. package/dest/test/rollup_cheat_codes.d.ts +63 -4
  115. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  116. package/dest/test/rollup_cheat_codes.js +96 -8
  117. package/dest/test/start_anvil.d.ts +23 -3
  118. package/dest/test/start_anvil.d.ts.map +1 -1
  119. package/dest/test/start_anvil.js +182 -32
  120. package/dest/test/upgrade_utils.js +2 -2
  121. package/dest/utils.d.ts +10 -2
  122. package/dest/utils.d.ts.map +1 -1
  123. package/dest/utils.js +94 -16
  124. package/package.json +6 -9
  125. package/src/client.ts +66 -2
  126. package/src/config.ts +104 -18
  127. package/src/contracts/chain_state_override.ts +200 -0
  128. package/src/contracts/fee_asset_handler.ts +2 -0
  129. package/src/contracts/fee_asset_price_oracle.ts +285 -0
  130. package/src/contracts/governance.ts +279 -13
  131. package/src/contracts/governance_proposer.ts +58 -2
  132. package/src/contracts/gse.ts +7 -2
  133. package/src/contracts/inbox.ts +13 -5
  134. package/src/contracts/index.ts +3 -2
  135. package/src/contracts/multicall.ts +247 -103
  136. package/src/contracts/outbox.ts +42 -8
  137. package/src/contracts/registry.ts +31 -1
  138. package/src/contracts/rollup.ts +461 -82
  139. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +16 -14
  140. package/src/deploy_aztec_l1_contracts.ts +93 -47
  141. package/src/deploy_l1_contract.ts +3 -3
  142. package/src/foundry_binary.ts +57 -0
  143. package/src/l1_artifacts.ts +12 -35
  144. package/src/l1_contract_addresses.ts +120 -94
  145. package/src/l1_reader.ts +17 -10
  146. package/src/l1_tx_utils/config.ts +23 -3
  147. package/src/l1_tx_utils/constants.ts +2 -2
  148. package/src/l1_tx_utils/factory.ts +31 -31
  149. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +1 -1
  150. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +1 -1
  151. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +43 -54
  152. package/src/l1_tx_utils/index-blobs.ts +2 -2
  153. package/src/l1_tx_utils/index.ts +1 -0
  154. package/src/l1_tx_utils/l1_fee_analyzer.ts +75 -3
  155. package/src/l1_tx_utils/l1_tx_utils.ts +170 -68
  156. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +13 -8
  157. package/src/{test → l1_tx_utils}/tx_delayer.ts +93 -56
  158. package/src/l1_tx_utils/types.ts +32 -0
  159. package/src/publisher_manager.ts +145 -12
  160. package/src/queries.ts +77 -4
  161. package/src/test/blob_kzg_warmup.ts +65 -0
  162. package/src/test/chain_monitor.ts +148 -3
  163. package/src/test/eth_cheat_codes.ts +82 -45
  164. package/src/test/index.ts +1 -2
  165. package/src/test/rollup_cheat_codes.ts +126 -8
  166. package/src/test/start_anvil.ts +212 -32
  167. package/src/test/upgrade_utils.ts +2 -2
  168. package/src/utils.ts +98 -18
  169. package/dest/contracts/empire_slashing_proposer.d.ts +0 -67
  170. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  171. package/dest/contracts/empire_slashing_proposer.js +0 -209
  172. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  173. package/dest/generated/l1-contracts-defaults.d.ts +0 -29
  174. package/dest/generated/l1-contracts-defaults.d.ts.map +0 -1
  175. package/dest/generated/l1-contracts-defaults.js +0 -29
  176. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +0 -26
  177. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +0 -1
  178. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +0 -26
  179. package/dest/test/delayed_tx_utils.d.ts +0 -13
  180. package/dest/test/delayed_tx_utils.d.ts.map +0 -1
  181. package/dest/test/delayed_tx_utils.js +0 -28
  182. package/dest/test/tx_delayer.d.ts +0 -36
  183. package/dest/test/tx_delayer.d.ts.map +0 -1
  184. package/src/contracts/empire_slashing_proposer.ts +0 -270
  185. package/src/generated/l1-contracts-defaults.ts +0 -31
  186. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +0 -77
  187. package/src/test/delayed_tx_utils.ts +0 -52
@@ -791,9 +791,6 @@ export class L1FeeAnalyzer {
791
791
  });
792
792
  }
793
793
 
794
- /**
795
- * Gets the minimum value from an array of bigints
796
- */
797
794
  private minBigInt(values: bigint[]): bigint {
798
795
  if (values.length === 0) {
799
796
  return 0n;
@@ -801,3 +798,78 @@ export class L1FeeAnalyzer {
801
798
  return values.reduce((min, val) => (val < min ? val : min), values[0]);
802
799
  }
803
800
  }
801
+
802
+ /** Per-block fee data for one mined L1 block, used to diagnose whether a tx was underpriced for it. */
803
+ export interface WindowBlockFees {
804
+ blockNumber: bigint;
805
+ timestamp: bigint;
806
+ baseFeePerGas: bigint;
807
+ /** 75th percentile priority fee among the block's txs (gas-weighted, from eth_feeHistory). */
808
+ p75PriorityFee: bigint;
809
+ /** Minimum priority fee among all included txs — the inclusion bar for that block. */
810
+ minIncludedPriorityFee: bigint;
811
+ blockBlobsFull: boolean;
812
+ includedBlobCount: number;
813
+ }
814
+
815
+ /** Safety bound on how far back the window scan walks if the chain head is far ahead of the window. */
816
+ const MAX_WINDOW_SCAN_BLOCKS = 64;
817
+
818
+ /**
819
+ * Reads the already-mined L1 blocks whose timestamps fall in [windowStartS, windowEndS) — the L1
820
+ * inclusion window of an L2 slot — and extracts per-block fee data. Walks block headers to map the
821
+ * window to block numbers, then reads the priority-fee stats from a single eth_feeHistory call
822
+ * (percentile 0 is the cheapest included tx, i.e. the inclusion bar), so no transaction bodies are
823
+ * ever downloaded. Historical reads only, so it never waits on a future block. Returns the blocks in
824
+ * chronological order, [] on error, or the subset mined so far if the window is still in progress.
825
+ * Never throws.
826
+ */
827
+ export async function captureWindowBlockFees(
828
+ client: ViemClient,
829
+ windowStartS: bigint,
830
+ windowEndS: bigint,
831
+ ): Promise<WindowBlockFees[]> {
832
+ try {
833
+ let current = await client.getBlock({ blockTag: 'latest' });
834
+ const inWindow: (typeof current)[] = [];
835
+ let scanned = 0;
836
+ // Walk back from the head, collecting blocks inside the window and skipping any past its end,
837
+ // until we cross below the window start (or hit the safety cap / genesis).
838
+ while (current.timestamp >= windowStartS && scanned < MAX_WINDOW_SCAN_BLOCKS) {
839
+ if (current.timestamp < windowEndS) {
840
+ inWindow.push(current);
841
+ }
842
+ if (current.number === 0n) {
843
+ break;
844
+ }
845
+ current = await client.getBlock({ blockNumber: current.number - 1n });
846
+ scanned++;
847
+ }
848
+ if (inWindow.length === 0) {
849
+ return [];
850
+ }
851
+ inWindow.reverse();
852
+ const newest = inWindow[inWindow.length - 1];
853
+ const feeHistory = await client.getFeeHistory({
854
+ blockCount: Number(newest.number - inWindow[0].number) + 1,
855
+ blockNumber: newest.number,
856
+ rewardPercentiles: [0, 75],
857
+ });
858
+ return inWindow.map(block => {
859
+ const idx = Number(block.number - feeHistory.oldestBlock);
860
+ const [minIncludedPriorityFee, p75PriorityFee] = feeHistory.reward?.[idx] ?? [0n, 0n];
861
+ const blobsInBlock = block.blobGasUsed ? Number(block.blobGasUsed / GAS_PER_BLOB) : 0;
862
+ return {
863
+ blockNumber: block.number,
864
+ timestamp: block.timestamp,
865
+ baseFeePerGas: block.baseFeePerGas ?? 0n,
866
+ p75PriorityFee,
867
+ minIncludedPriorityFee,
868
+ blockBlobsFull: blobsInBlock >= getMaxBlobCapacity(block.timestamp),
869
+ includedBlobCount: blobsInBlock,
870
+ };
871
+ });
872
+ } catch {
873
+ return [];
874
+ }
875
+ }
@@ -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,29 +15,28 @@ 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';
29
28
  import { type L1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
30
- import { LARGE_GAS_LIMIT } from './constants.js';
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,
36
36
  type L1TxConfig,
37
37
  type L1TxRequest,
38
38
  type L1TxState,
39
+ L1TxTimeoutError,
39
40
  type SigningCallback,
40
41
  TerminalTxUtilsState,
41
42
  TxUtilsState,
@@ -44,9 +45,21 @@ import {
44
45
 
45
46
  const MAX_L1_TX_STATES = 32;
46
47
 
48
+ // Backoff (in seconds) for retrying the read-only RPC calls that prepare a tx cancellation. A
49
+ // cancellation is fired in the background after a tx times out and is important (it frees the stuck
50
+ // nonce), so a transient RPC failure while reading the pending nonce or gas price must not abandon it.
51
+ const CANCELLATION_PREP_RETRY_BACKOFF_S = [1, 2, 4, 8];
52
+
47
53
  export class L1TxUtils extends ReadOnlyL1TxUtils {
48
- protected nonceManager: NonceManager;
49
54
  protected txs: L1TxState[] = [];
55
+ /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */
56
+ private lastSentNonce: number | undefined;
57
+ /** Mutex to prevent concurrent sendTransaction calls from racing on the same nonce. */
58
+ private readonly sendMutex = new Semaphore(1);
59
+ /** Tx delayer for testing. Only set when enableDelayer config is true. */
60
+ public delayer?: Delayer;
61
+ /** KZG instance for blob operations. */
62
+ protected kzg?: BlobKzgInstance;
50
63
 
51
64
  constructor(
52
65
  public override client: ViemClient,
@@ -58,9 +71,25 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
58
71
  debugMaxGasLimit: boolean = false,
59
72
  protected store?: IL1TxStore,
60
73
  protected metrics?: IL1TxMetrics,
74
+ kzg?: BlobKzgInstance,
75
+ delayer?: Delayer,
61
76
  ) {
62
77
  super(client, logger, dateProvider, config, debugMaxGasLimit);
63
- this.nonceManager = createNonceManager({ source: jsonRpc() });
78
+ this.kzg = kzg;
79
+
80
+ // Set up delayer: use provided one or create new
81
+ if (config?.enableDelayer && config?.ethereumSlotDuration) {
82
+ this.delayer =
83
+ delayer ?? this.createDelayer({ ethereumSlotDuration: config.ethereumSlotDuration }, logger.getBindings());
84
+ this.client = wrapClientWithDelayer(this.client, this.delayer);
85
+ if (config.txDelayerMaxInclusionTimeIntoSlot !== undefined) {
86
+ this.delayer.setMaxInclusionTimeIntoSlot(config.txDelayerMaxInclusionTimeIntoSlot);
87
+ }
88
+ } else if (delayer) {
89
+ // Delayer provided but enableDelayer not set — just store it without wrapping
90
+ logger.warn('Delayer provided but enableDelayer config is not set; delayer will not be used');
91
+ this.delayer = delayer;
92
+ }
64
93
  }
65
94
 
66
95
  public get state() {
@@ -87,6 +116,11 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
87
116
  this.metrics?.recordMinedTx(l1TxState, new Date(l1Timestamp));
88
117
  } else if (newState === TxUtilsState.NOT_MINED) {
89
118
  this.metrics?.recordDroppedTx(l1TxState);
119
+ // The tx was dropped: the chain nonce reverted to l1TxState.nonce, so our lower bound is
120
+ // no longer valid. Clear it so the next send fetches the real nonce from the chain.
121
+ if (this.lastSentNonce === l1TxState.nonce) {
122
+ this.lastSentNonce = undefined;
123
+ }
90
124
  }
91
125
 
92
126
  // Update state in the store
@@ -103,6 +137,14 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
103
137
  );
104
138
  }
105
139
 
140
+ /**
141
+ * Clears the cached `lastSentNonce` so the next `sendTransaction` call fetches the real
142
+ * nonce from the chain. Call this after an L1 reorg to prevent stale nonce references.
143
+ */
144
+ public resetNonce(): void {
145
+ this.lastSentNonce = undefined;
146
+ }
147
+
106
148
  public getSenderAddress() {
107
149
  return this.address;
108
150
  }
@@ -185,6 +227,19 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
185
227
  return await this.signTransaction(txRequest as TransactionSerializable);
186
228
  }
187
229
 
230
+ private async checkInterruptedOrTimedOut(gasConfig: Pick<L1TxConfig, 'txTimeoutAt'>): Promise<Date> {
231
+ if (this.interrupted) {
232
+ throw new InterruptError(`Transaction sending is interrupted`);
233
+ }
234
+ const now = new Date(await this.getL1Timestamp());
235
+ if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
236
+ throw new TimeoutError(
237
+ `Transaction timed out before sending (now ${now.toISOString()} > timeoutAt ${gasConfig.txTimeoutAt.toISOString()})`,
238
+ );
239
+ }
240
+ return now;
241
+ }
242
+
188
243
  /**
189
244
  * Sends a transaction with gas estimation and pricing
190
245
  * @param request - The transaction request (to, data, value)
@@ -197,17 +252,18 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
197
252
  blobInputs?: L1BlobInputs,
198
253
  stateChange: TxUtilsState = TxUtilsState.SENT,
199
254
  ): Promise<{ txHash: Hex; state: L1TxState }> {
200
- if (this.interrupted) {
201
- throw new InterruptError(`Transaction sending is interrupted`);
202
- }
203
-
204
255
  try {
205
256
  const gasConfig = merge(this.config, gasConfigOverrides);
206
257
  const account = this.getSenderAddress().toString();
207
258
 
259
+ // Fail fast before doing any work (gas estimation, balance check) if we've been interrupted
260
+ // or if the caller's deadline has already passed. The same check is repeated after gas
261
+ // estimation in case it took long enough to push us past the deadline.
262
+ await this.checkInterruptedOrTimedOut(gasConfig);
263
+
208
264
  let gasLimit: bigint;
209
265
  if (this.debugMaxGasLimit) {
210
- gasLimit = LARGE_GAS_LIMIT;
266
+ gasLimit = MAX_L1_TX_LIMIT;
211
267
  } else if (gasConfig.gasLimit) {
212
268
  gasLimit = gasConfig.gasLimit;
213
269
  } else {
@@ -217,40 +273,41 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
217
273
 
218
274
  const gasPrice = await this.getGasPrice(gasConfig, !!blobInputs);
219
275
 
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
- });
276
+ const now = await this.checkInterruptedOrTimedOut(gasConfig);
229
277
 
230
- const baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
231
- const txData = this.makeTxData(baseState, { isCancelTx: false });
278
+ let txHash: Hex;
279
+ let nonce: number;
280
+ let baseState: Pick<L1TxState, 'request' | 'gasLimit' | 'blobInputs' | 'gasPrice' | 'nonce'>;
232
281
 
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
- );
282
+ await this.sendMutex.acquire();
283
+ try {
284
+ const chainNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
285
+ // If a fallback RPC node returns a stale count (lower than what we last sent), use our
286
+ // local lower bound to avoid sending a duplicate of an already-pending transaction.
287
+ nonce =
288
+ this.lastSentNonce !== undefined && chainNonce <= this.lastSentNonce ? this.lastSentNonce + 1 : chainNonce;
289
+
290
+ baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
291
+ const txData = this.makeTxData(baseState, { isCancelTx: false });
292
+
293
+ const signedRequest = await this.prepareSignedTransaction(txData);
294
+ txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
295
+ this.lastSentNonce = nonce;
296
+ } finally {
297
+ this.sendMutex.release();
238
298
  }
239
299
 
240
- // Send the new tx
241
- const signedRequest = await this.prepareSignedTransaction(txData);
242
- const txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
243
-
244
300
  // Create the new state for monitoring
245
301
  const l1TxState: L1TxState = {
246
302
  ...baseState,
247
- id: (await this.store?.consumeNextStateId(account)) ?? Math.max(...this.txs.map(tx => tx.id), 0),
303
+ id: (await this.store?.consumeNextStateId(account)) ?? Math.max(...this.txs.map(tx => tx.id), -1) + 1,
248
304
  txHashes: [txHash],
249
305
  cancelTxHashes: [],
250
306
  status: TxUtilsState.IDLE,
251
307
  txConfigOverrides: gasConfigOverrides ?? {},
252
308
  sentAtL1Ts: now,
253
309
  lastSentAtL1Ts: now,
310
+ gasPriceHistory: [baseState.gasPrice],
254
311
  };
255
312
 
256
313
  // And persist it
@@ -283,7 +340,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
283
340
  return { txHash, state: l1TxState };
284
341
  } catch (err: any) {
285
342
  const viemError = formatViemError(err, request.abi);
286
- this.logger.error(`Failed to send L1 transaction`, viemError, {
343
+ this.logger.error(`Failed to send L1 transaction: ${viemError.message}`, viemError, {
287
344
  request: pick(request, 'to', 'value'),
288
345
  });
289
346
  throw viemError;
@@ -381,10 +438,23 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
381
438
 
382
439
  const initialTxHash = txHashes[0];
383
440
  let currentTxHash = txHashes.at(-1)!;
384
- let l1Timestamp: number;
441
+ let l1Timestamp = 0;
385
442
 
386
443
  while (true) {
387
- l1Timestamp = await this.getL1Timestamp();
444
+ try {
445
+ l1Timestamp = await this.getL1Timestamp();
446
+ } catch (err) {
447
+ // A transient RPC failure here must not abort monitoring with a rejection: callers that
448
+ // fire this loop in the background would surface it as an unhandled rejection (e.g. when a
449
+ // test tears down its L1 node while a monitor iteration is in flight). Exit quietly if we
450
+ // are shutting down, otherwise retry on the next interval.
451
+ if (this.interrupted) {
452
+ break;
453
+ }
454
+ this.logger.error(`Error fetching L1 timestamp while monitoring tx ${currentTxHash}`, err, { nonce, account });
455
+ await sleep(gasConfig.checkIntervalMs!);
456
+ continue;
457
+ }
388
458
 
389
459
  try {
390
460
  const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
@@ -423,7 +493,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
423
493
  { nonce, account, pendingNonce, timePassed },
424
494
  );
425
495
  await this.updateState(state, TxUtilsState.NOT_MINED);
426
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
427
496
  throw new DroppedTransactionError(nonce, account);
428
497
  }
429
498
 
@@ -437,6 +506,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
437
506
  if (timePassed >= stallTimeMs && attempts <= maxSpeedUpAttempts) {
438
507
  const newGasPrice = await this.getGasPrice(gasConfig, isBlobTx, attempts, state.gasPrice);
439
508
  state.gasPrice = newGasPrice;
509
+ state.gasPriceHistory?.push(newGasPrice);
440
510
 
441
511
  this.logger.debug(
442
512
  `Tx ${currentTxHash} with nonce ${nonce} from ${account} appears stuck. ` +
@@ -515,12 +585,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
515
585
 
516
586
  // Oh no, the transaction has timed out!
517
587
  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
588
  await this.updateState(state, TxUtilsState.NOT_MINED);
523
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
524
589
  } else {
525
590
  // Otherwise we fire the cancellation without awaiting to avoid blocking the caller,
526
591
  // and monitor it in the background so we can speed it up as needed.
@@ -610,8 +675,22 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
610
675
  blobInputs?: L1BlobInputs,
611
676
  ): Promise<{ receipt: TransactionReceipt; state: L1TxState }> {
612
677
  const { state } = await this.sendTransaction(request, gasConfig, blobInputs);
613
- const receipt = await this.monitorTransaction(state);
614
- return { receipt, state };
678
+ try {
679
+ const receipt = await this.monitorTransaction(state);
680
+ return { receipt, state };
681
+ } catch (err) {
682
+ if (err instanceof TimeoutError) {
683
+ // Snapshot the ladder now: the fire-and-forget cancellation mutates state.gasPrice moments later.
684
+ throw new L1TxTimeoutError(err.message, {
685
+ gasPriceHistory: state.gasPriceHistory ? [...state.gasPriceHistory] : undefined,
686
+ finalGasPrice: state.gasPrice,
687
+ attempts: state.txHashes.length,
688
+ nonce: state.nonce,
689
+ gasLimit: state.gasLimit,
690
+ });
691
+ }
692
+ throw err;
693
+ }
615
694
  }
616
695
 
617
696
  public override async simulate(
@@ -631,12 +710,12 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
631
710
  from: request.from ?? this.getSenderAddress().toString(),
632
711
  maxFeePerGas: gasPrice.maxFeePerGas,
633
712
  maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas,
634
- gas: request.gas ?? LARGE_GAS_LIMIT,
713
+ gas: request.gas ?? MAX_L1_TX_LIMIT,
635
714
  };
636
715
 
637
716
  if (!request.gas && !gasConfig.ignoreBlockGasLimit) {
638
- // LARGE_GAS_LIMIT is set as call.gas, increase block gasLimit
639
- blockOverrides.gasLimit = LARGE_GAS_LIMIT * 2n;
717
+ // MAX_L1_TX_LIMIT is set as call.gas, ensure block gasLimit is sufficient
718
+ blockOverrides.gasLimit = MAX_L1_TX_LIMIT;
640
719
  }
641
720
 
642
721
  return this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
@@ -659,34 +738,48 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
659
738
  { nonce, account },
660
739
  );
661
740
  await this.updateState(state, TxUtilsState.NOT_MINED);
662
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
663
741
  return;
664
742
  }
665
743
 
666
- // Check if the original tx is still pending
667
- const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
668
- if (currentNonce < nonce) {
744
+ // Resolve the pending nonce and cancellation gas price up front. These are read-only RPC calls, so
745
+ // they are safe to retry; a transient RPC failure here must not permanently abandon the cancellation
746
+ // (which would leave the nonce stuck and the tx state stranded short of CANCELLED). We retry with a
747
+ // real backoff before giving up, unlike getGasPrice's tight internal retry which can be exhausted by
748
+ // a brief node hiccup. The retried block performs no state-changing send, so retrying cannot
749
+ // double-send the cancellation tx.
750
+ const { currentNonce, cancelGasPrice } = await retry(
751
+ async () => {
752
+ const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
753
+ if (currentNonce >= nonce) {
754
+ // Get gas price with higher priority fee for cancellation
755
+ const cancelGasPrice = await this.getGasPrice(
756
+ {
757
+ ...this.config,
758
+ // Use high bump for cancellation to ensure it replaces the original tx
759
+ priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
760
+ },
761
+ isBlobTx,
762
+ state.txHashes.length,
763
+ previousGasPrice,
764
+ );
765
+ return { currentNonce, cancelGasPrice };
766
+ }
767
+ return { currentNonce, cancelGasPrice: undefined };
768
+ },
769
+ `Preparing cancellation for L1 tx from account ${account} with nonce ${nonce}`,
770
+ makeBackoff(CANCELLATION_PREP_RETRY_BACKOFF_S),
771
+ this.logger,
772
+ );
773
+
774
+ if (cancelGasPrice === undefined) {
669
775
  this.logger.verbose(
670
776
  `Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`,
671
777
  { nonce, account, currentNonce },
672
778
  );
673
779
  await this.updateState(state, TxUtilsState.NOT_MINED);
674
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
675
780
  return;
676
781
  }
677
782
 
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
783
  const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelGasPrice;
691
784
  this.logger.verbose(
692
785
  `Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`,
@@ -731,8 +824,17 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
731
824
  return Number(timestamp) * 1000;
732
825
  }
733
826
 
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');
827
+ /** Makes empty blob inputs for the cancellation tx. */
828
+ protected makeEmptyBlobInputs(maxFeePerBlobGas: bigint): Required<L1BlobInputs> {
829
+ if (!this.kzg) {
830
+ throw new Error('Cannot make empty blob inputs for cancellation without kzg');
831
+ }
832
+ const blobData = new Uint8Array(131072).fill(0);
833
+ return { blobs: [blobData], kzg: this.kzg, maxFeePerBlobGas };
834
+ }
835
+
836
+ /** Creates a new delayer instance. */
837
+ protected createDelayer(opts: { ethereumSlotDuration: bigint | number }, bindings: LoggerBindings): Delayer {
838
+ return createDelayer(this.dateProvider, opts, bindings);
737
839
  }
738
840
  }
@@ -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';
@@ -27,7 +28,7 @@ import type { ViemClient } from '../types.js';
27
28
  import { type L1TxUtilsConfig, defaultL1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
28
29
  import {
29
30
  BLOCK_TIME_MS,
30
- LARGE_GAS_LIMIT,
31
+ MAX_L1_TX_LIMIT,
31
32
  MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE,
32
33
  MIN_REPLACEMENT_BUMP_PERCENTAGE,
33
34
  WEI_CONST,
@@ -130,9 +131,10 @@ export class ReadOnlyL1TxUtils {
130
131
  const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
131
132
  for (let i = 0; i < numBlocks; i++) {
132
133
  // each block can go up 12.5% from previous baseFee
133
- maxFeePerGas = (maxFeePerGas * (1_000n + 125n)) / 1_000n;
134
+ // ceil, (a+b-1)/b, to avoid truncation at small values (e.g. 1 wei blob base fee)
135
+ maxFeePerGas = (maxFeePerGas * (1_000n + 125n) + 999n) / 1_000n;
134
136
  // same for blob gas fee
135
- maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n)) / 1_000n;
137
+ maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n) + 999n) / 1_000n;
136
138
  }
137
139
 
138
140
  if (attempt > 0) {
@@ -242,14 +244,17 @@ export class ReadOnlyL1TxUtils {
242
244
  const gasConfig = { ...this.config, ..._gasConfig };
243
245
  let initialEstimate = 0n;
244
246
  if (_blobInputs) {
245
- // @note requests with blobs also require maxFeePerBlobGas to be set
247
+ // @note requests with blobs also require maxFeePerBlobGas to be set.
248
+ // Use 2x buffer for maxFeePerBlobGas to avoid stale fees and to pass EIP-4844 validation (even if it is a gas estimation call).
249
+ // 1. maxFeePerBlobGas >= blobBaseFee
250
+ // 2. account balance >= gas * maxFeePerGas + maxFeePerBlobGas * blobCount + value
246
251
  const gasPrice = await this.getGasPrice(gasConfig, true, 0);
247
252
  initialEstimate = await this.client.estimateGas({
248
253
  account,
249
254
  ...request,
250
255
  ..._blobInputs,
251
- maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
252
- gas: LARGE_GAS_LIMIT,
256
+ maxFeePerBlobGas: gasPrice.maxFeePerBlobGas! * 2n,
257
+ gas: MAX_L1_TX_LIMIT,
253
258
  blockTag: 'latest',
254
259
  });
255
260
 
@@ -258,7 +263,7 @@ export class ReadOnlyL1TxUtils {
258
263
  initialEstimate = await this.client.estimateGas({
259
264
  account,
260
265
  ...request,
261
- gas: LARGE_GAS_LIMIT,
266
+ gas: MAX_L1_TX_LIMIT,
262
267
  blockTag: 'latest',
263
268
  });
264
269
  this.logger?.trace(`Estimated gas for non-blob tx: ${initialEstimate}`);
@@ -391,7 +396,7 @@ export class ReadOnlyL1TxUtils {
391
396
  this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
392
397
  return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
393
398
  } catch (err) {
394
- if (err instanceof MethodNotFoundRpcError || err instanceof MethodNotSupportedRpcError) {
399
+ if (getErrorCause(err, MethodNotFoundRpcError) || getErrorCause(err, MethodNotSupportedRpcError)) {
395
400
  if (gasConfig.fallbackGasEstimate) {
396
401
  this.logger?.warn(
397
402
  `Node does not support eth_simulateV1 API. Using fallback gas estimate: ${gasConfig.fallbackGasEstimate}`,