@aztec/ethereum 0.0.1-commit.d3ec352c → 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 (224) 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 -4
  4. package/dest/config.d.ts +45 -73
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +114 -386
  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/empire_base.d.ts +2 -1
  11. package/dest/contracts/empire_base.d.ts.map +1 -1
  12. package/dest/contracts/fee_asset_handler.d.ts +6 -5
  13. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  14. package/dest/contracts/fee_asset_handler.js +11 -9
  15. package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
  16. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  17. package/dest/contracts/fee_asset_price_oracle.js +656 -0
  18. package/dest/contracts/governance.d.ts +110 -33
  19. package/dest/contracts/governance.d.ts.map +1 -1
  20. package/dest/contracts/governance.js +207 -16
  21. package/dest/contracts/governance_proposer.d.ts +34 -1
  22. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  23. package/dest/contracts/governance_proposer.js +447 -10
  24. package/dest/contracts/gse.d.ts +4 -2
  25. package/dest/contracts/gse.d.ts.map +1 -1
  26. package/dest/contracts/gse.js +2 -2
  27. package/dest/contracts/inbox.d.ts +24 -3
  28. package/dest/contracts/inbox.d.ts.map +1 -1
  29. package/dest/contracts/inbox.js +42 -2
  30. package/dest/contracts/index.d.ts +6 -3
  31. package/dest/contracts/index.d.ts.map +1 -1
  32. package/dest/contracts/index.js +5 -2
  33. package/dest/contracts/log.d.ts +13 -0
  34. package/dest/contracts/log.d.ts.map +1 -0
  35. package/dest/contracts/log.js +1 -0
  36. package/dest/contracts/multicall.d.ts +130 -13
  37. package/dest/contracts/multicall.d.ts.map +1 -1
  38. package/dest/contracts/multicall.js +203 -93
  39. package/dest/contracts/outbox.d.ts +64 -0
  40. package/dest/contracts/outbox.d.ts.map +1 -0
  41. package/dest/contracts/outbox.js +113 -0
  42. package/dest/contracts/registry.d.ts +3 -1
  43. package/dest/contracts/registry.d.ts.map +1 -1
  44. package/dest/contracts/registry.js +30 -1
  45. package/dest/contracts/rollup.d.ts +5571 -102
  46. package/dest/contracts/rollup.d.ts.map +1 -1
  47. package/dest/contracts/rollup.js +1076 -192
  48. package/dest/contracts/{tally_slashing_proposer.d.ts → slashing_proposer.d.ts} +5 -5
  49. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  50. package/dest/contracts/{tally_slashing_proposer.js → slashing_proposer.js} +18 -13
  51. package/dest/deploy_aztec_l1_contracts.d.ts +267 -0
  52. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -0
  53. package/dest/deploy_aztec_l1_contracts.js +424 -0
  54. package/dest/deploy_l1_contract.d.ts +68 -0
  55. package/dest/deploy_l1_contract.d.ts.map +1 -0
  56. package/dest/deploy_l1_contract.js +312 -0
  57. package/dest/forwarder_proxy.d.ts +32 -0
  58. package/dest/forwarder_proxy.d.ts.map +1 -0
  59. package/dest/forwarder_proxy.js +93 -0
  60. package/dest/foundry_binary.d.ts +13 -0
  61. package/dest/foundry_binary.d.ts.map +1 -0
  62. package/dest/foundry_binary.js +52 -0
  63. package/dest/l1_artifacts.d.ts +19674 -16606
  64. package/dest/l1_artifacts.d.ts.map +1 -1
  65. package/dest/l1_artifacts.js +9 -24
  66. package/dest/l1_contract_addresses.d.ts +61 -65
  67. package/dest/l1_contract_addresses.d.ts.map +1 -1
  68. package/dest/l1_contract_addresses.js +99 -80
  69. package/dest/l1_reader.d.ts +7 -5
  70. package/dest/l1_reader.d.ts.map +1 -1
  71. package/dest/l1_reader.js +15 -7
  72. package/dest/l1_tx_utils/config.d.ts +9 -3
  73. package/dest/l1_tx_utils/config.d.ts.map +1 -1
  74. package/dest/l1_tx_utils/config.js +34 -7
  75. package/dest/l1_tx_utils/constants.d.ts +8 -2
  76. package/dest/l1_tx_utils/constants.d.ts.map +1 -1
  77. package/dest/l1_tx_utils/constants.js +27 -2
  78. package/dest/l1_tx_utils/factory.d.ts +18 -10
  79. package/dest/l1_tx_utils/factory.d.ts.map +1 -1
  80. package/dest/l1_tx_utils/factory.js +17 -7
  81. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  82. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  83. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  84. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  85. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  86. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  87. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  88. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  89. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  90. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  91. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  92. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  93. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
  94. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
  95. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +42 -0
  96. package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
  97. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
  98. package/dest/l1_tx_utils/index-blobs.js +2 -0
  99. package/dest/l1_tx_utils/index.d.ts +4 -1
  100. package/dest/l1_tx_utils/index.d.ts.map +1 -1
  101. package/dest/l1_tx_utils/index.js +3 -0
  102. package/dest/l1_tx_utils/interfaces.d.ts +2 -2
  103. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -1
  104. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +252 -0
  105. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  106. package/dest/l1_tx_utils/l1_fee_analyzer.js +568 -0
  107. package/dest/l1_tx_utils/l1_tx_utils.d.ts +26 -7
  108. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  109. package/dest/l1_tx_utils/l1_tx_utils.js +202 -92
  110. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +4 -15
  111. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  112. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +63 -165
  113. package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
  114. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  115. package/dest/{test → l1_tx_utils}/tx_delayer.js +70 -39
  116. package/dest/l1_tx_utils/types.d.ts +27 -1
  117. package/dest/l1_tx_utils/types.d.ts.map +1 -1
  118. package/dest/l1_tx_utils/types.js +10 -0
  119. package/dest/publisher_manager.d.ts +34 -7
  120. package/dest/publisher_manager.d.ts.map +1 -1
  121. package/dest/publisher_manager.js +119 -8
  122. package/dest/queries.d.ts +14 -3
  123. package/dest/queries.d.ts.map +1 -1
  124. package/dest/queries.js +80 -7
  125. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  126. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  127. package/dest/test/blob_kzg_warmup.js +64 -0
  128. package/dest/test/chain_monitor.d.ts +55 -4
  129. package/dest/test/chain_monitor.d.ts.map +1 -1
  130. package/dest/test/chain_monitor.js +105 -5
  131. package/dest/test/eth_cheat_codes.d.ts +49 -6
  132. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  133. package/dest/test/eth_cheat_codes.js +93 -43
  134. package/dest/test/index.d.ts +2 -3
  135. package/dest/test/index.d.ts.map +1 -1
  136. package/dest/test/index.js +1 -2
  137. package/dest/test/rollup_cheat_codes.d.ts +64 -4
  138. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  139. package/dest/test/rollup_cheat_codes.js +109 -8
  140. package/dest/test/start_anvil.d.ts +24 -2
  141. package/dest/test/start_anvil.d.ts.map +1 -1
  142. package/dest/test/start_anvil.js +182 -32
  143. package/dest/test/upgrade_utils.js +2 -2
  144. package/dest/types.d.ts +57 -2
  145. package/dest/types.d.ts.map +1 -1
  146. package/dest/utils.d.ts +24 -4
  147. package/dest/utils.d.ts.map +1 -1
  148. package/dest/utils.js +112 -16
  149. package/package.json +31 -15
  150. package/src/client.ts +66 -2
  151. package/src/config.ts +153 -469
  152. package/src/contracts/README.md +157 -0
  153. package/src/contracts/chain_state_override.ts +200 -0
  154. package/src/contracts/empire_base.ts +1 -1
  155. package/src/contracts/fee_asset_handler.ts +10 -7
  156. package/src/contracts/fee_asset_price_oracle.ts +285 -0
  157. package/src/contracts/governance.ts +279 -13
  158. package/src/contracts/governance_proposer.ts +64 -3
  159. package/src/contracts/gse.ts +7 -2
  160. package/src/contracts/inbox.ts +64 -4
  161. package/src/contracts/index.ts +5 -2
  162. package/src/contracts/log.ts +13 -0
  163. package/src/contracts/multicall.ts +247 -103
  164. package/src/contracts/outbox.ts +132 -0
  165. package/src/contracts/registry.ts +31 -1
  166. package/src/contracts/rollup.ts +789 -154
  167. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +18 -14
  168. package/src/deploy_aztec_l1_contracts.ts +664 -0
  169. package/src/deploy_l1_contract.ts +362 -0
  170. package/src/forwarder_proxy.ts +108 -0
  171. package/src/foundry_binary.ts +57 -0
  172. package/src/l1_artifacts.ts +12 -35
  173. package/src/l1_contract_addresses.ts +120 -92
  174. package/src/l1_reader.ts +25 -10
  175. package/src/l1_tx_utils/config.ts +47 -9
  176. package/src/l1_tx_utils/constants.ts +13 -2
  177. package/src/l1_tx_utils/factory.ts +31 -31
  178. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  179. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +163 -0
  180. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +245 -0
  181. package/src/l1_tx_utils/fee-strategies/types.ts +56 -0
  182. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +108 -0
  183. package/src/l1_tx_utils/index-blobs.ts +2 -0
  184. package/src/l1_tx_utils/index.ts +3 -0
  185. package/src/l1_tx_utils/interfaces.ts +1 -1
  186. package/src/l1_tx_utils/l1_fee_analyzer.ts +875 -0
  187. package/src/l1_tx_utils/l1_tx_utils.ts +194 -72
  188. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +77 -211
  189. package/src/{test → l1_tx_utils}/tx_delayer.ts +97 -58
  190. package/src/l1_tx_utils/types.ts +32 -0
  191. package/src/publisher_manager.ts +145 -12
  192. package/src/queries.ts +87 -7
  193. package/src/test/blob_kzg_warmup.ts +65 -0
  194. package/src/test/chain_monitor.ts +150 -4
  195. package/src/test/eth_cheat_codes.ts +84 -47
  196. package/src/test/index.ts +1 -2
  197. package/src/test/rollup_cheat_codes.ts +136 -8
  198. package/src/test/start_anvil.ts +213 -31
  199. package/src/test/upgrade_utils.ts +2 -2
  200. package/src/types.ts +62 -0
  201. package/src/utils.ts +128 -19
  202. package/dest/contracts/empire_slashing_proposer.d.ts +0 -66
  203. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  204. package/dest/contracts/empire_slashing_proposer.js +0 -200
  205. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  206. package/dest/deploy_l1_contracts.d.ts +0 -673
  207. package/dest/deploy_l1_contracts.d.ts.map +0 -1
  208. package/dest/deploy_l1_contracts.js +0 -1491
  209. package/dest/index.d.ts +0 -18
  210. package/dest/index.d.ts.map +0 -1
  211. package/dest/index.js +0 -17
  212. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +0 -26
  213. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +0 -1
  214. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +0 -26
  215. package/dest/test/delayed_tx_utils.d.ts +0 -13
  216. package/dest/test/delayed_tx_utils.d.ts.map +0 -1
  217. package/dest/test/delayed_tx_utils.js +0 -28
  218. package/dest/test/tx_delayer.d.ts +0 -36
  219. package/dest/test/tx_delayer.d.ts.map +0 -1
  220. package/src/contracts/empire_slashing_proposer.ts +0 -265
  221. package/src/deploy_l1_contracts.ts +0 -1869
  222. package/src/index.ts +0 -17
  223. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +0 -77
  224. package/src/test/delayed_tx_utils.ts +0 -52
@@ -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
  }
@@ -130,12 +172,32 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
130
172
  return;
131
173
  }
132
174
 
133
- // Convert loaded states (which have id) to the txs format
134
- this.txs = loadedStates;
135
- this.logger.info(`Rehydrated ${loadedStates.length} tx states for account ${account}`);
175
+ // Clean up excess states if we have more than MAX_L1_TX_STATES
176
+ if (loadedStates.length > MAX_L1_TX_STATES) {
177
+ this.logger.warn(
178
+ `Found ${loadedStates.length} tx states for account ${account}, pruning to most recent ${MAX_L1_TX_STATES}`,
179
+ );
180
+
181
+ // Keep only the most recent MAX_L1_TX_STATES
182
+ const statesToKeep = loadedStates.slice(-MAX_L1_TX_STATES);
183
+ const statesToDelete = loadedStates.slice(0, -MAX_L1_TX_STATES);
184
+
185
+ // Batch delete old states in a transaction for efficiency
186
+ const idsToDelete = statesToDelete.map(s => s.id);
187
+ await this.store.deleteState(account, ...idsToDelete);
188
+
189
+ this.txs = statesToKeep;
190
+ this.logger.info(
191
+ `Cleaned up ${statesToDelete.length} old tx states, kept ${statesToKeep.length} for account ${account}`,
192
+ );
193
+ } else {
194
+ // Convert loaded states (which have id) to the txs format
195
+ this.txs = loadedStates;
196
+ this.logger.info(`Rehydrated ${loadedStates.length} tx states for account ${account}`);
197
+ }
136
198
 
137
199
  // Find all pending states and resume monitoring
138
- const pendingStates = loadedStates.filter(state => !TerminalTxUtilsState.includes(state.status));
200
+ const pendingStates = this.txs.filter(state => !TerminalTxUtilsState.includes(state.status));
139
201
  if (pendingStates.length === 0) {
140
202
  return;
141
203
  }
@@ -165,6 +227,19 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
165
227
  return await this.signTransaction(txRequest as TransactionSerializable);
166
228
  }
167
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
+
168
243
  /**
169
244
  * Sends a transaction with gas estimation and pricing
170
245
  * @param request - The transaction request (to, data, value)
@@ -177,17 +252,18 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
177
252
  blobInputs?: L1BlobInputs,
178
253
  stateChange: TxUtilsState = TxUtilsState.SENT,
179
254
  ): Promise<{ txHash: Hex; state: L1TxState }> {
180
- if (this.interrupted) {
181
- throw new InterruptError(`Transaction sending is interrupted`);
182
- }
183
-
184
255
  try {
185
256
  const gasConfig = merge(this.config, gasConfigOverrides);
186
257
  const account = this.getSenderAddress().toString();
187
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
+
188
264
  let gasLimit: bigint;
189
265
  if (this.debugMaxGasLimit) {
190
- gasLimit = LARGE_GAS_LIMIT;
266
+ gasLimit = MAX_L1_TX_LIMIT;
191
267
  } else if (gasConfig.gasLimit) {
192
268
  gasLimit = gasConfig.gasLimit;
193
269
  } else {
@@ -197,40 +273,41 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
197
273
 
198
274
  const gasPrice = await this.getGasPrice(gasConfig, !!blobInputs);
199
275
 
200
- if (this.interrupted) {
201
- throw new InterruptError(`Transaction sending is interrupted`);
202
- }
203
-
204
- const nonce = await this.nonceManager.consume({
205
- client: this.client,
206
- address: account,
207
- chainId: this.client.chain.id,
208
- });
276
+ const now = await this.checkInterruptedOrTimedOut(gasConfig);
209
277
 
210
- const baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
211
- 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'>;
212
281
 
213
- const now = new Date(await this.getL1Timestamp());
214
- if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
215
- throw new TimeoutError(
216
- `Transaction timed out before sending (now ${now.toISOString()} > timeoutAt ${gasConfig.txTimeoutAt.toISOString()})`,
217
- );
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();
218
298
  }
219
299
 
220
- // Send the new tx
221
- const signedRequest = await this.prepareSignedTransaction(txData);
222
- const txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
223
-
224
300
  // Create the new state for monitoring
225
301
  const l1TxState: L1TxState = {
226
302
  ...baseState,
227
- 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,
228
304
  txHashes: [txHash],
229
305
  cancelTxHashes: [],
230
306
  status: TxUtilsState.IDLE,
231
307
  txConfigOverrides: gasConfigOverrides ?? {},
232
308
  sentAtL1Ts: now,
233
309
  lastSentAtL1Ts: now,
310
+ gasPriceHistory: [baseState.gasPrice],
234
311
  };
235
312
 
236
313
  // And persist it
@@ -263,7 +340,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
263
340
  return { txHash, state: l1TxState };
264
341
  } catch (err: any) {
265
342
  const viemError = formatViemError(err, request.abi);
266
- this.logger.error(`Failed to send L1 transaction`, viemError, {
343
+ this.logger.error(`Failed to send L1 transaction: ${viemError.message}`, viemError, {
267
344
  request: pick(request, 'to', 'value'),
268
345
  });
269
346
  throw viemError;
@@ -361,10 +438,23 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
361
438
 
362
439
  const initialTxHash = txHashes[0];
363
440
  let currentTxHash = txHashes.at(-1)!;
364
- let l1Timestamp: number;
441
+ let l1Timestamp = 0;
365
442
 
366
443
  while (true) {
367
- 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
+ }
368
458
 
369
459
  try {
370
460
  const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
@@ -403,7 +493,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
403
493
  { nonce, account, pendingNonce, timePassed },
404
494
  );
405
495
  await this.updateState(state, TxUtilsState.NOT_MINED);
406
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
407
496
  throw new DroppedTransactionError(nonce, account);
408
497
  }
409
498
 
@@ -417,6 +506,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
417
506
  if (timePassed >= stallTimeMs && attempts <= maxSpeedUpAttempts) {
418
507
  const newGasPrice = await this.getGasPrice(gasConfig, isBlobTx, attempts, state.gasPrice);
419
508
  state.gasPrice = newGasPrice;
509
+ state.gasPriceHistory?.push(newGasPrice);
420
510
 
421
511
  this.logger.debug(
422
512
  `Tx ${currentTxHash} with nonce ${nonce} from ${account} appears stuck. ` +
@@ -495,12 +585,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
495
585
 
496
586
  // Oh no, the transaction has timed out!
497
587
  if (isCancelTx || !gasConfig.cancelTxOnTimeout) {
498
- // If this was already a cancellation tx, or we are configured to not cancel txs, we just mark it as NOT_MINED
499
- // and reset the nonce manager, so the next tx that comes along can reuse the nonce if/when this tx gets dropped.
500
- // This is the nastiest scenario for us, since the new tx could acquire the next nonce, but then this tx is dropped,
501
- // and the new tx would never get mined. Eventually, the new tx would also drop.
502
588
  await this.updateState(state, TxUtilsState.NOT_MINED);
503
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
504
589
  } else {
505
590
  // Otherwise we fire the cancellation without awaiting to avoid blocking the caller,
506
591
  // and monitor it in the background so we can speed it up as needed.
@@ -590,8 +675,22 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
590
675
  blobInputs?: L1BlobInputs,
591
676
  ): Promise<{ receipt: TransactionReceipt; state: L1TxState }> {
592
677
  const { state } = await this.sendTransaction(request, gasConfig, blobInputs);
593
- const receipt = await this.monitorTransaction(state);
594
- 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
+ }
595
694
  }
596
695
 
597
696
  public override async simulate(
@@ -611,12 +710,12 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
611
710
  from: request.from ?? this.getSenderAddress().toString(),
612
711
  maxFeePerGas: gasPrice.maxFeePerGas,
613
712
  maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas,
614
- gas: request.gas ?? LARGE_GAS_LIMIT,
713
+ gas: request.gas ?? MAX_L1_TX_LIMIT,
615
714
  };
616
715
 
617
716
  if (!request.gas && !gasConfig.ignoreBlockGasLimit) {
618
- // LARGE_GAS_LIMIT is set as call.gas, increase block gasLimit
619
- 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;
620
719
  }
621
720
 
622
721
  return this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
@@ -639,34 +738,48 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
639
738
  { nonce, account },
640
739
  );
641
740
  await this.updateState(state, TxUtilsState.NOT_MINED);
642
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
643
741
  return;
644
742
  }
645
743
 
646
- // Check if the original tx is still pending
647
- const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
648
- 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) {
649
775
  this.logger.verbose(
650
776
  `Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`,
651
777
  { nonce, account, currentNonce },
652
778
  );
653
779
  await this.updateState(state, TxUtilsState.NOT_MINED);
654
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
655
780
  return;
656
781
  }
657
782
 
658
- // Get gas price with higher priority fee for cancellation
659
- const cancelGasPrice = await this.getGasPrice(
660
- {
661
- ...this.config,
662
- // Use high bump for cancellation to ensure it replaces the original tx
663
- priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
664
- },
665
- isBlobTx,
666
- state.txHashes.length,
667
- previousGasPrice,
668
- );
669
-
670
783
  const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelGasPrice;
671
784
  this.logger.verbose(
672
785
  `Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`,
@@ -711,8 +824,17 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
711
824
  return Number(timestamp) * 1000;
712
825
  }
713
826
 
714
- /** Makes empty blob inputs for the cancellation tx. To be overridden in L1TxUtilsWithBlobs. */
715
- protected makeEmptyBlobInputs(_maxFeePerBlobGas: bigint): Required<L1BlobInputs> {
716
- 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);
717
839
  }
718
840
  }