@aztec-labs/ethereum 6.0.0-nightly.20260829

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 (272) hide show
  1. package/README.md +3 -0
  2. package/dest/account.d.ts +2 -0
  3. package/dest/account.d.ts.map +1 -0
  4. package/dest/account.js +4 -0
  5. package/dest/chain.d.ts +25 -0
  6. package/dest/chain.d.ts.map +1 -0
  7. package/dest/chain.js +53 -0
  8. package/dest/client.d.ts +42 -0
  9. package/dest/client.d.ts.map +1 -0
  10. package/dest/client.js +104 -0
  11. package/dest/config.d.ts +103 -0
  12. package/dest/config.d.ts.map +1 -0
  13. package/dest/config.js +233 -0
  14. package/dest/constants.d.ts +4 -0
  15. package/dest/constants.d.ts.map +1 -0
  16. package/dest/constants.js +2 -0
  17. package/dest/contracts/chain_state_override.d.ts +81 -0
  18. package/dest/contracts/chain_state_override.d.ts.map +1 -0
  19. package/dest/contracts/chain_state_override.js +139 -0
  20. package/dest/contracts/empire_base.d.ts +30 -0
  21. package/dest/contracts/empire_base.d.ts.map +1 -0
  22. package/dest/contracts/empire_base.js +84 -0
  23. package/dest/contracts/errors.d.ts +7 -0
  24. package/dest/contracts/errors.d.ts.map +1 -0
  25. package/dest/contracts/errors.js +12 -0
  26. package/dest/contracts/fee_asset_handler.d.ts +20 -0
  27. package/dest/contracts/fee_asset_handler.d.ts.map +1 -0
  28. package/dest/contracts/fee_asset_handler.js +59 -0
  29. package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
  30. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  31. package/dest/contracts/fee_asset_price_oracle.js +656 -0
  32. package/dest/contracts/fee_juice.d.ts +14 -0
  33. package/dest/contracts/fee_juice.d.ts.map +1 -0
  34. package/dest/contracts/fee_juice.js +59 -0
  35. package/dest/contracts/governance.d.ts +192 -0
  36. package/dest/contracts/governance.d.ts.map +1 -0
  37. package/dest/contracts/governance.js +471 -0
  38. package/dest/contracts/governance_proposer.d.ts +63 -0
  39. package/dest/contracts/governance_proposer.d.ts.map +1 -0
  40. package/dest/contracts/governance_proposer.js +536 -0
  41. package/dest/contracts/gse.d.ts +38 -0
  42. package/dest/contracts/gse.d.ts.map +1 -0
  43. package/dest/contracts/gse.js +81 -0
  44. package/dest/contracts/inbox.d.ts +94 -0
  45. package/dest/contracts/inbox.d.ts.map +1 -0
  46. package/dest/contracts/inbox.js +141 -0
  47. package/dest/contracts/index.d.ts +18 -0
  48. package/dest/contracts/index.d.ts.map +1 -0
  49. package/dest/contracts/index.js +17 -0
  50. package/dest/contracts/log.d.ts +13 -0
  51. package/dest/contracts/log.d.ts.map +1 -0
  52. package/dest/contracts/log.js +1 -0
  53. package/dest/contracts/multicall.d.ts +138 -0
  54. package/dest/contracts/multicall.d.ts.map +1 -0
  55. package/dest/contracts/multicall.js +266 -0
  56. package/dest/contracts/outbox.d.ts +64 -0
  57. package/dest/contracts/outbox.d.ts.map +1 -0
  58. package/dest/contracts/outbox.js +113 -0
  59. package/dest/contracts/registry.d.ts +31 -0
  60. package/dest/contracts/registry.d.ts.map +1 -0
  61. package/dest/contracts/registry.js +142 -0
  62. package/dest/contracts/rollup.d.ts +5836 -0
  63. package/dest/contracts/rollup.d.ts.map +1 -0
  64. package/dest/contracts/rollup.js +1612 -0
  65. package/dest/contracts/slasher_contract.d.ts +44 -0
  66. package/dest/contracts/slasher_contract.d.ts.map +1 -0
  67. package/dest/contracts/slasher_contract.js +75 -0
  68. package/dest/contracts/slashing_proposer.d.ts +174 -0
  69. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  70. package/dest/contracts/slashing_proposer.js +755 -0
  71. package/dest/contracts/utils.d.ts +3 -0
  72. package/dest/contracts/utils.d.ts.map +1 -0
  73. package/dest/contracts/utils.js +11 -0
  74. package/dest/contracts/watch_event.d.ts +36 -0
  75. package/dest/contracts/watch_event.d.ts.map +1 -0
  76. package/dest/contracts/watch_event.js +66 -0
  77. package/dest/deploy_aztec_l1_contracts.d.ts +267 -0
  78. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -0
  79. package/dest/deploy_aztec_l1_contracts.js +424 -0
  80. package/dest/deploy_l1_contract.d.ts +68 -0
  81. package/dest/deploy_l1_contract.d.ts.map +1 -0
  82. package/dest/deploy_l1_contract.js +312 -0
  83. package/dest/eth-signer/eth-signer.d.ts +21 -0
  84. package/dest/eth-signer/eth-signer.d.ts.map +1 -0
  85. package/dest/eth-signer/eth-signer.js +5 -0
  86. package/dest/eth-signer/index.d.ts +2 -0
  87. package/dest/eth-signer/index.d.ts.map +1 -0
  88. package/dest/eth-signer/index.js +1 -0
  89. package/dest/forwarder_proxy.d.ts +32 -0
  90. package/dest/forwarder_proxy.d.ts.map +1 -0
  91. package/dest/forwarder_proxy.js +93 -0
  92. package/dest/foundry_binary.d.ts +13 -0
  93. package/dest/foundry_binary.d.ts.map +1 -0
  94. package/dest/foundry_binary.js +52 -0
  95. package/dest/l1_artifacts.d.ts +81896 -0
  96. package/dest/l1_artifacts.d.ts.map +1 -0
  97. package/dest/l1_artifacts.js +151 -0
  98. package/dest/l1_contract_addresses.d.ts +73 -0
  99. package/dest/l1_contract_addresses.d.ts.map +1 -0
  100. package/dest/l1_contract_addresses.js +120 -0
  101. package/dest/l1_reader.d.ts +18 -0
  102. package/dest/l1_reader.d.ts.map +1 -0
  103. package/dest/l1_reader.js +35 -0
  104. package/dest/l1_tx_utils/config.d.ts +65 -0
  105. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  106. package/dest/l1_tx_utils/config.js +109 -0
  107. package/dest/l1_tx_utils/constants.d.ts +12 -0
  108. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  109. package/dest/l1_tx_utils/constants.js +39 -0
  110. package/dest/l1_tx_utils/factory.d.ts +32 -0
  111. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  112. package/dest/l1_tx_utils/factory.js +22 -0
  113. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  114. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  115. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  116. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  117. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  118. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  119. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  120. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  121. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  122. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  123. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  124. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  125. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
  126. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
  127. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +42 -0
  128. package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
  129. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
  130. package/dest/l1_tx_utils/index-blobs.js +2 -0
  131. package/dest/l1_tx_utils/index.d.ts +13 -0
  132. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  133. package/dest/l1_tx_utils/index.js +13 -0
  134. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  135. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  136. package/dest/l1_tx_utils/interfaces.js +4 -0
  137. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +252 -0
  138. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  139. package/dest/l1_tx_utils/l1_fee_analyzer.js +568 -0
  140. package/dest/l1_tx_utils/l1_tx_utils.d.ts +113 -0
  141. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  142. package/dest/l1_tx_utils/l1_tx_utils.js +720 -0
  143. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +83 -0
  144. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  145. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +357 -0
  146. package/dest/l1_tx_utils/signer.d.ts +4 -0
  147. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  148. package/dest/l1_tx_utils/signer.js +16 -0
  149. package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
  150. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  151. package/dest/l1_tx_utils/tx_delayer.js +223 -0
  152. package/dest/l1_tx_utils/types.d.ts +93 -0
  153. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  154. package/dest/l1_tx_utils/types.js +36 -0
  155. package/dest/l1_tx_utils/utils.d.ts +4 -0
  156. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  157. package/dest/l1_tx_utils/utils.js +14 -0
  158. package/dest/l1_types.d.ts +6 -0
  159. package/dest/l1_types.d.ts.map +1 -0
  160. package/dest/l1_types.js +1 -0
  161. package/dest/publisher_manager.d.ts +42 -0
  162. package/dest/publisher_manager.d.ts.map +1 -0
  163. package/dest/publisher_manager.js +199 -0
  164. package/dest/queries.d.ts +25 -0
  165. package/dest/queries.d.ts.map +1 -0
  166. package/dest/queries.js +144 -0
  167. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  168. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  169. package/dest/test/blob_kzg_warmup.js +64 -0
  170. package/dest/test/chain_monitor.d.ts +126 -0
  171. package/dest/test/chain_monitor.d.ts.map +1 -0
  172. package/dest/test/chain_monitor.js +314 -0
  173. package/dest/test/eth_cheat_codes.d.ts +260 -0
  174. package/dest/test/eth_cheat_codes.d.ts.map +1 -0
  175. package/dest/test/eth_cheat_codes.js +608 -0
  176. package/dest/test/eth_cheat_codes_with_state.d.ts +18 -0
  177. package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -0
  178. package/dest/test/eth_cheat_codes_with_state.js +34 -0
  179. package/dest/test/index.d.ts +8 -0
  180. package/dest/test/index.d.ts.map +1 -0
  181. package/dest/test/index.js +7 -0
  182. package/dest/test/recording_rpc_server.d.ts +18 -0
  183. package/dest/test/recording_rpc_server.d.ts.map +1 -0
  184. package/dest/test/recording_rpc_server.js +68 -0
  185. package/dest/test/rollup_cheat_codes.d.ts +142 -0
  186. package/dest/test/rollup_cheat_codes.d.ts.map +1 -0
  187. package/dest/test/rollup_cheat_codes.js +338 -0
  188. package/dest/test/start_anvil.d.ts +40 -0
  189. package/dest/test/start_anvil.d.ts.map +1 -0
  190. package/dest/test/start_anvil.js +210 -0
  191. package/dest/test/upgrade_utils.d.ts +12 -0
  192. package/dest/test/upgrade_utils.d.ts.map +1 -0
  193. package/dest/test/upgrade_utils.js +111 -0
  194. package/dest/types.d.ts +68 -0
  195. package/dest/types.d.ts.map +1 -0
  196. package/dest/types.js +3 -0
  197. package/dest/utils.d.ts +45 -0
  198. package/dest/utils.d.ts.map +1 -0
  199. package/dest/utils.js +260 -0
  200. package/dest/zkPassportVerifierAddress.d.ts +15 -0
  201. package/dest/zkPassportVerifierAddress.d.ts.map +1 -0
  202. package/dest/zkPassportVerifierAddress.js +11 -0
  203. package/package.json +122 -0
  204. package/src/account.ts +5 -0
  205. package/src/chain.ts +71 -0
  206. package/src/client.ts +165 -0
  207. package/src/config.ts +342 -0
  208. package/src/constants.ts +4 -0
  209. package/src/contracts/README.md +157 -0
  210. package/src/contracts/chain_state_override.ts +203 -0
  211. package/src/contracts/empire_base.ts +89 -0
  212. package/src/contracts/errors.ts +13 -0
  213. package/src/contracts/fee_asset_handler.ts +66 -0
  214. package/src/contracts/fee_asset_price_oracle.ts +284 -0
  215. package/src/contracts/fee_juice.ts +57 -0
  216. package/src/contracts/governance.ts +597 -0
  217. package/src/contracts/governance_proposer.ts +181 -0
  218. package/src/contracts/gse.ts +105 -0
  219. package/src/contracts/inbox.ts +223 -0
  220. package/src/contracts/index.ts +17 -0
  221. package/src/contracts/log.ts +13 -0
  222. package/src/contracts/multicall.ts +298 -0
  223. package/src/contracts/outbox.ts +132 -0
  224. package/src/contracts/registry.ts +161 -0
  225. package/src/contracts/rollup.ts +1502 -0
  226. package/src/contracts/slasher_contract.ts +89 -0
  227. package/src/contracts/slashing_proposer.ts +397 -0
  228. package/src/contracts/utils.ts +14 -0
  229. package/src/contracts/watch_event.ts +109 -0
  230. package/src/deploy_aztec_l1_contracts.ts +663 -0
  231. package/src/deploy_l1_contract.ts +361 -0
  232. package/src/eth-signer/eth-signer.ts +24 -0
  233. package/src/eth-signer/index.ts +1 -0
  234. package/src/forwarder_proxy.ts +107 -0
  235. package/src/foundry_binary.ts +57 -0
  236. package/src/l1_artifacts.ts +231 -0
  237. package/src/l1_contract_addresses.ts +149 -0
  238. package/src/l1_reader.ts +57 -0
  239. package/src/l1_tx_utils/README.md +177 -0
  240. package/src/l1_tx_utils/config.ts +181 -0
  241. package/src/l1_tx_utils/constants.ts +29 -0
  242. package/src/l1_tx_utils/factory.ts +64 -0
  243. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  244. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +162 -0
  245. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +244 -0
  246. package/src/l1_tx_utils/fee-strategies/types.ts +55 -0
  247. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +107 -0
  248. package/src/l1_tx_utils/index-blobs.ts +2 -0
  249. package/src/l1_tx_utils/index.ts +15 -0
  250. package/src/l1_tx_utils/interfaces.ts +86 -0
  251. package/src/l1_tx_utils/l1_fee_analyzer.ts +874 -0
  252. package/src/l1_tx_utils/l1_tx_utils.ts +840 -0
  253. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +459 -0
  254. package/src/l1_tx_utils/signer.ts +27 -0
  255. package/src/l1_tx_utils/tx_delayer.ts +302 -0
  256. package/src/l1_tx_utils/types.ts +116 -0
  257. package/src/l1_tx_utils/utils.ts +15 -0
  258. package/src/l1_types.ts +6 -0
  259. package/src/publisher_manager.ts +239 -0
  260. package/src/queries.ts +189 -0
  261. package/src/test/blob_kzg_warmup.ts +65 -0
  262. package/src/test/chain_monitor.ts +389 -0
  263. package/src/test/eth_cheat_codes.ts +624 -0
  264. package/src/test/eth_cheat_codes_with_state.ts +38 -0
  265. package/src/test/index.ts +7 -0
  266. package/src/test/recording_rpc_server.ts +69 -0
  267. package/src/test/rollup_cheat_codes.ts +398 -0
  268. package/src/test/start_anvil.ts +255 -0
  269. package/src/test/upgrade_utils.ts +109 -0
  270. package/src/types.ts +97 -0
  271. package/src/utils.ts +344 -0
  272. package/src/zkPassportVerifierAddress.ts +15 -0
@@ -0,0 +1,720 @@
1
+ import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
2
+ import { maxBigint } from '@aztec-labs/foundation/bigint';
3
+ import { merge, pick } from '@aztec-labs/foundation/collection';
4
+ import { InterruptError, TimeoutError } from '@aztec-labs/foundation/error';
5
+ import { createLogger } from '@aztec-labs/foundation/log';
6
+ import { Semaphore } from '@aztec-labs/foundation/queue';
7
+ import { makeBackoff, retry, retryUntil } from '@aztec-labs/foundation/retry';
8
+ import { sleep } from '@aztec-labs/foundation/sleep';
9
+ import { DateProvider } from '@aztec-labs/foundation/timer';
10
+ import pickBy from 'lodash.pickby';
11
+ import { formatGwei, serializeTransaction } from 'viem';
12
+ import { formatViemError } from '../utils.js';
13
+ import { l1TxUtilsConfigMappings } from './config.js';
14
+ import { MAX_L1_TX_LIMIT } from './constants.js';
15
+ import { ReadOnlyL1TxUtils } from './readonly_l1_tx_utils.js';
16
+ import { createDelayer, wrapClientWithDelayer } from './tx_delayer.js';
17
+ import { DroppedTransactionError, L1TxTimeoutError, TerminalTxUtilsState, TxUtilsState, UnknownMinedTxError } from './types.js';
18
+ const MAX_L1_TX_STATES = 32;
19
+ // Backoff (in seconds) for retrying the read-only RPC calls that prepare a tx cancellation. A
20
+ // cancellation is fired in the background after a tx times out and is important (it frees the stuck
21
+ // nonce), so a transient RPC failure while reading the pending nonce or gas price must not abandon it.
22
+ const CANCELLATION_PREP_RETRY_BACKOFF_S = [
23
+ 1,
24
+ 2,
25
+ 4,
26
+ 8
27
+ ];
28
+ export class L1TxUtils extends ReadOnlyL1TxUtils {
29
+ client;
30
+ address;
31
+ signer;
32
+ store;
33
+ metrics;
34
+ txs;
35
+ /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */ lastSentNonce;
36
+ /** Mutex to prevent concurrent sendTransaction calls from racing on the same nonce. */ sendMutex;
37
+ /** Tx delayer for testing. Only set when enableDelayer config is true. */ delayer;
38
+ /** KZG instance for blob operations. */ kzg;
39
+ constructor(client, address, signer, logger = createLogger('ethereum:publisher'), dateProvider = new DateProvider(), config, debugMaxGasLimit = false, store, metrics, kzg, delayer){
40
+ super(client, logger, dateProvider, config, debugMaxGasLimit), this.client = client, this.address = address, this.signer = signer, this.store = store, this.metrics = metrics, this.txs = [], this.sendMutex = new Semaphore(1);
41
+ this.kzg = kzg;
42
+ // Set up delayer: use provided one or create new
43
+ if (config?.enableDelayer && config?.ethereumSlotDuration) {
44
+ this.delayer = delayer ?? this.createDelayer({
45
+ ethereumSlotDuration: config.ethereumSlotDuration
46
+ }, logger.getBindings());
47
+ this.client = wrapClientWithDelayer(this.client, this.delayer);
48
+ if (config.txDelayerMaxInclusionTimeIntoSlot !== undefined) {
49
+ this.delayer.setMaxInclusionTimeIntoSlot(config.txDelayerMaxInclusionTimeIntoSlot);
50
+ }
51
+ } else if (delayer) {
52
+ // Delayer provided but enableDelayer not set — just store it without wrapping
53
+ logger.warn('Delayer provided but enableDelayer config is not set; delayer will not be used');
54
+ this.delayer = delayer;
55
+ }
56
+ }
57
+ get state() {
58
+ return this.txs.at(-1)?.status ?? TxUtilsState.IDLE;
59
+ }
60
+ get lastMinedAtBlockNumber() {
61
+ const minedBlockNumbers = this.txs.map((tx)=>tx.receipt?.blockNumber).filter((bn)=>bn !== undefined);
62
+ return minedBlockNumbers.length === 0 ? undefined : maxBigint(...minedBlockNumbers);
63
+ }
64
+ async updateState(l1TxState, newState, l1Timestamp) {
65
+ const oldState = l1TxState.status;
66
+ l1TxState.status = newState;
67
+ const sender = this.getSenderAddress().toString();
68
+ this.logger.debug(`Tx state changed from ${TxUtilsState[oldState]} to ${TxUtilsState[newState]} for nonce ${l1TxState.nonce} account ${sender}`);
69
+ // Record metrics
70
+ if (newState === TxUtilsState.MINED && l1Timestamp !== undefined) {
71
+ this.metrics?.recordMinedTx(l1TxState, new Date(l1Timestamp));
72
+ } else if (newState === TxUtilsState.NOT_MINED) {
73
+ this.metrics?.recordDroppedTx(l1TxState);
74
+ // The tx was dropped: the chain nonce reverted to l1TxState.nonce, so our lower bound is
75
+ // no longer valid. Clear it so the next send fetches the real nonce from the chain.
76
+ if (this.lastSentNonce === l1TxState.nonce) {
77
+ this.lastSentNonce = undefined;
78
+ }
79
+ }
80
+ // Update state in the store
81
+ await this.store?.saveState(sender, l1TxState).catch((err)=>this.logger.error('Failed to persist L1 tx state', err));
82
+ }
83
+ updateConfig(newConfig) {
84
+ this.config = merge(this.config, newConfig);
85
+ this.logger.info('Updated L1TxUtils config', pickBy(newConfig, (_, key)=>key in l1TxUtilsConfigMappings));
86
+ }
87
+ /**
88
+ * Clears the cached `lastSentNonce` so the next `sendTransaction` call fetches the real
89
+ * nonce from the chain. Call this after an L1 reorg to prevent stale nonce references.
90
+ */ resetNonce() {
91
+ this.lastSentNonce = undefined;
92
+ }
93
+ getSenderAddress() {
94
+ return this.address;
95
+ }
96
+ getSenderBalance() {
97
+ return this.client.getBalance({
98
+ address: this.getSenderAddress().toString()
99
+ });
100
+ }
101
+ /**
102
+ * Rehydrates transaction states from the store and resumes monitoring for pending transactions.
103
+ * This should be called on startup to restore state and resume monitoring of any in-flight transactions.
104
+ */ async loadStateAndResumeMonitoring() {
105
+ if (!this.store) {
106
+ return;
107
+ }
108
+ const account = this.getSenderAddress().toString();
109
+ const loadedStates = await this.store.loadStates(account);
110
+ if (loadedStates.length === 0) {
111
+ this.logger.debug(`No states to rehydrate for account ${account}`);
112
+ return;
113
+ }
114
+ // Clean up excess states if we have more than MAX_L1_TX_STATES
115
+ if (loadedStates.length > MAX_L1_TX_STATES) {
116
+ this.logger.warn(`Found ${loadedStates.length} tx states for account ${account}, pruning to most recent ${MAX_L1_TX_STATES}`);
117
+ // Keep only the most recent MAX_L1_TX_STATES
118
+ const statesToKeep = loadedStates.slice(-MAX_L1_TX_STATES);
119
+ const statesToDelete = loadedStates.slice(0, -MAX_L1_TX_STATES);
120
+ // Batch delete old states in a transaction for efficiency
121
+ const idsToDelete = statesToDelete.map((s)=>s.id);
122
+ await this.store.deleteState(account, ...idsToDelete);
123
+ this.txs = statesToKeep;
124
+ this.logger.info(`Cleaned up ${statesToDelete.length} old tx states, kept ${statesToKeep.length} for account ${account}`);
125
+ } else {
126
+ // Convert loaded states (which have id) to the txs format
127
+ this.txs = loadedStates;
128
+ this.logger.info(`Rehydrated ${loadedStates.length} tx states for account ${account}`);
129
+ }
130
+ // Find all pending states and resume monitoring
131
+ const pendingStates = this.txs.filter((state)=>!TerminalTxUtilsState.includes(state.status));
132
+ if (pendingStates.length === 0) {
133
+ return;
134
+ }
135
+ this.logger.info(`Resuming monitoring for ${pendingStates.length} pending transactions for account ${account}`, {
136
+ txs: pendingStates.map((s)=>({
137
+ id: s.id,
138
+ nonce: s.nonce,
139
+ status: TxUtilsState[s.status]
140
+ }))
141
+ });
142
+ for (const state of pendingStates){
143
+ void this.monitorTransaction(state).catch((err)=>{
144
+ this.logger.error(`Error monitoring rehydrated tx with nonce ${state.nonce} for account ${account}`, formatViemError(err), {
145
+ nonce: state.nonce,
146
+ account
147
+ });
148
+ });
149
+ }
150
+ }
151
+ async signTransaction(txRequest) {
152
+ const signature = await this.signer(txRequest, this.getSenderAddress());
153
+ return serializeTransaction(txRequest, signature);
154
+ }
155
+ async prepareSignedTransaction(txData) {
156
+ const txRequest = await this.client.prepareTransactionRequest(txData);
157
+ return await this.signTransaction(txRequest);
158
+ }
159
+ async checkInterruptedOrTimedOut(gasConfig) {
160
+ if (this.interrupted) {
161
+ throw new InterruptError(`Transaction sending is interrupted`);
162
+ }
163
+ const now = new Date(await this.getL1Timestamp());
164
+ if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
165
+ throw new TimeoutError(`Transaction timed out before sending (now ${now.toISOString()} > timeoutAt ${gasConfig.txTimeoutAt.toISOString()})`);
166
+ }
167
+ return now;
168
+ }
169
+ /**
170
+ * Sends a transaction with gas estimation and pricing
171
+ * @param request - The transaction request (to, data, value)
172
+ * @param gasConfig - Optional gas configuration
173
+ * @returns The transaction hash and parameters used
174
+ */ async sendTransaction(request, gasConfigOverrides, blobInputs, stateChange = TxUtilsState.SENT) {
175
+ try {
176
+ const gasConfig = merge(this.config, gasConfigOverrides);
177
+ const account = this.getSenderAddress().toString();
178
+ // Fail fast before doing any work (gas estimation, balance check) if we've been interrupted
179
+ // or if the caller's deadline has already passed. The same check is repeated after gas
180
+ // estimation in case it took long enough to push us past the deadline.
181
+ await this.checkInterruptedOrTimedOut(gasConfig);
182
+ let gasLimit;
183
+ if (this.debugMaxGasLimit) {
184
+ gasLimit = MAX_L1_TX_LIMIT;
185
+ } else if (gasConfig.gasLimit) {
186
+ gasLimit = gasConfig.gasLimit;
187
+ } else {
188
+ gasLimit = await this.estimateGas(account, request, gasConfig);
189
+ }
190
+ this.logger.trace(`Computed gas limit ${gasLimit}`, {
191
+ gasLimit,
192
+ ...request
193
+ });
194
+ const feesPerGas = await this.getFeesPerGas(gasConfig, !!blobInputs);
195
+ const now = await this.checkInterruptedOrTimedOut(gasConfig);
196
+ let txHash;
197
+ let nonce;
198
+ let baseState;
199
+ await this.sendMutex.acquire();
200
+ try {
201
+ const chainNonce = await this.client.getTransactionCount({
202
+ address: account,
203
+ blockTag: 'pending'
204
+ });
205
+ // If a fallback RPC node returns a stale count (lower than what we last sent), use our
206
+ // local lower bound to avoid sending a duplicate of an already-pending transaction.
207
+ nonce = this.lastSentNonce !== undefined && chainNonce <= this.lastSentNonce ? this.lastSentNonce + 1 : chainNonce;
208
+ baseState = {
209
+ request,
210
+ gasLimit,
211
+ blobInputs,
212
+ feesPerGas,
213
+ nonce
214
+ };
215
+ const txData = this.makeTxData(baseState, {
216
+ isCancelTx: false
217
+ });
218
+ const signedRequest = await this.prepareSignedTransaction(txData);
219
+ txHash = await this.client.sendRawTransaction({
220
+ serializedTransaction: signedRequest
221
+ });
222
+ this.lastSentNonce = nonce;
223
+ } finally{
224
+ this.sendMutex.release();
225
+ }
226
+ // Create the new state for monitoring
227
+ const l1TxState = {
228
+ ...baseState,
229
+ id: await this.store?.consumeNextStateId(account) ?? Math.max(...this.txs.map((tx)=>tx.id), -1) + 1,
230
+ txHashes: [
231
+ txHash
232
+ ],
233
+ cancelTxHashes: [],
234
+ status: TxUtilsState.IDLE,
235
+ txConfigOverrides: gasConfigOverrides ?? {},
236
+ sentAtL1Ts: now,
237
+ lastSentAtL1Ts: now,
238
+ feesPerGasHistory: [
239
+ baseState.feesPerGas
240
+ ]
241
+ };
242
+ // And persist it
243
+ await this.updateState(l1TxState, stateChange);
244
+ await this.store?.saveBlobs(account, l1TxState.id, blobInputs);
245
+ this.txs.push(l1TxState);
246
+ // Clean up stale states
247
+ if (this.txs.length > MAX_L1_TX_STATES) {
248
+ const removed = this.txs.shift();
249
+ if (removed && this.store) {
250
+ await this.store.deleteState(account, removed.id);
251
+ }
252
+ }
253
+ this.logger.info(`Sent L1 transaction ${txHash}`, {
254
+ to: request.to,
255
+ value: request.value,
256
+ nonce,
257
+ account,
258
+ sentAt: now,
259
+ gasLimit,
260
+ maxFeePerGas: formatGwei(feesPerGas.maxFeePerGas),
261
+ maxPriorityFeePerGas: formatGwei(feesPerGas.maxPriorityFeePerGas),
262
+ ...feesPerGas.maxFeePerBlobGas && {
263
+ maxFeePerBlobGas: formatGwei(feesPerGas.maxFeePerBlobGas)
264
+ },
265
+ isBlobTx: !!blobInputs,
266
+ txConfig: gasConfigOverrides
267
+ });
268
+ return {
269
+ txHash,
270
+ state: l1TxState
271
+ };
272
+ } catch (err) {
273
+ const viemError = formatViemError(err, request.abi);
274
+ this.logger.error(`Failed to send L1 transaction: ${viemError.message}`, viemError, {
275
+ request: pick(request, 'to', 'value')
276
+ });
277
+ throw viemError;
278
+ }
279
+ }
280
+ async tryGetTxReceipt(txHashes, nonce, isCancelTx) {
281
+ for (const hash of txHashes){
282
+ try {
283
+ const receipt = await this.client.getTransactionReceipt({
284
+ hash
285
+ });
286
+ if (receipt) {
287
+ const account = this.getSenderAddress().toString();
288
+ const what = isCancelTx ? 'Cancellation L1 transaction' : 'L1 transaction';
289
+ if (receipt.status === 'reverted') {
290
+ this.logger.warn(`${what} ${hash} with nonce ${nonce} reverted`, {
291
+ receipt,
292
+ nonce,
293
+ account
294
+ });
295
+ } else {
296
+ this.logger.info(`${what} ${hash} with nonce ${nonce} mined`, {
297
+ receipt,
298
+ nonce,
299
+ account
300
+ });
301
+ }
302
+ return receipt;
303
+ }
304
+ } catch (err) {
305
+ if (err instanceof Error && err.name === 'TransactionReceiptNotFoundError') {
306
+ continue;
307
+ } else {
308
+ this.logger.error(`Error getting receipt for tx ${hash}`, err);
309
+ continue;
310
+ }
311
+ }
312
+ }
313
+ }
314
+ /**
315
+ * Returns whether a given tx should be considered as timed out and no longer monitored.
316
+ * Relies on the txTimeout setting for user txs, and on the txCancellationTimeout for cancel txs.
317
+ * @remarks We check against the latestBlockTimestamp as opposed to the current time to avoid a race condition where
318
+ * the tx is mined in a block with the same timestamp as txTimeoutAt, but our execution node has not yet processed it,
319
+ * or the loop here has not yet checked the tx before that timeout.
320
+ */ isTxTimedOut(state, l1Timestamp) {
321
+ const account = this.getSenderAddress().toString();
322
+ const { nonce } = state;
323
+ const txConfig = merge(this.config, state.txConfigOverrides);
324
+ const { txTimeoutAt, txTimeoutMs, maxSpeedUpAttempts } = txConfig;
325
+ const isCancelTx = state.cancelTxHashes.length > 0;
326
+ this.logger.trace(`Tx timeout check for ${account} with nonce ${nonce}`, {
327
+ nonce,
328
+ account,
329
+ l1Timestamp,
330
+ lastAttemptSent: state.lastSentAtL1Ts.getTime(),
331
+ initialTxTime: state.sentAtL1Ts.getTime(),
332
+ now: this.dateProvider.now(),
333
+ txTimeoutAt,
334
+ txTimeoutMs,
335
+ interrupted: this.interrupted
336
+ });
337
+ if (this.interrupted) {
338
+ this.logger.warn(`Tx monitoring interrupted during nonce ${nonce} for ${account} check`, {
339
+ nonce,
340
+ account
341
+ });
342
+ return true;
343
+ }
344
+ if (isCancelTx) {
345
+ // Note that we check against the lastSentAt time for cancellations, since we time them out
346
+ // after the last attempt to submit them, not the initial time.
347
+ const attempts = state.cancelTxHashes.length;
348
+ return attempts > maxSpeedUpAttempts && state.lastSentAtL1Ts.getTime() + txConfig.txCancellationFinalTimeoutMs <= l1Timestamp;
349
+ }
350
+ return txTimeoutAt !== undefined && l1Timestamp >= txTimeoutAt.getTime() || txTimeoutMs !== undefined && txTimeoutMs > 0 && l1Timestamp - state.sentAtL1Ts.getTime() >= txTimeoutMs;
351
+ }
352
+ /**
353
+ * Monitors a transaction until completion, handling speed-ups if needed
354
+ */ async monitorTransaction(state) {
355
+ const { nonce, gasLimit, blobInputs, txConfigOverrides: gasConfigOverrides } = state;
356
+ const gasConfig = merge(this.config, gasConfigOverrides);
357
+ const { maxSpeedUpAttempts, stallTimeMs } = gasConfig;
358
+ const isCancelTx = state.cancelTxHashes.length > 0;
359
+ const txHashes = isCancelTx ? state.cancelTxHashes : state.txHashes;
360
+ const isBlobTx = !!blobInputs;
361
+ const account = this.getSenderAddress().toString();
362
+ const initialTxHash = txHashes[0];
363
+ let currentTxHash = txHashes.at(-1);
364
+ let l1Timestamp = 0;
365
+ while(true){
366
+ try {
367
+ l1Timestamp = await this.getL1Timestamp();
368
+ } catch (err) {
369
+ // A transient RPC failure here must not abort monitoring with a rejection: callers that
370
+ // fire this loop in the background would surface it as an unhandled rejection (e.g. when a
371
+ // test tears down its L1 node while a monitor iteration is in flight). Exit quietly if we
372
+ // are shutting down, otherwise retry on the next interval.
373
+ if (this.interrupted) {
374
+ break;
375
+ }
376
+ this.logger.error(`Error fetching L1 timestamp while monitoring tx ${currentTxHash}`, err, {
377
+ nonce,
378
+ account
379
+ });
380
+ await sleep(gasConfig.checkIntervalMs);
381
+ continue;
382
+ }
383
+ try {
384
+ const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
385
+ const [currentNonce, pendingNonce] = await Promise.all([
386
+ this.client.getTransactionCount({
387
+ address: account,
388
+ blockTag: 'latest'
389
+ }),
390
+ this.client.getTransactionCount({
391
+ address: account,
392
+ blockTag: 'pending'
393
+ })
394
+ ]);
395
+ // If the current nonce on our account is greater than our transaction's nonce then a tx with the same nonce has been mined.
396
+ if (currentNonce > nonce) {
397
+ // We try getting the receipt twice, since sometimes anvil fails to return it if the tx has just been mined
398
+ const receipt = await this.tryGetTxReceipt(state.cancelTxHashes, nonce, true) ?? await this.tryGetTxReceipt(state.txHashes, nonce, false) ?? await sleep(500) ?? await this.tryGetTxReceipt(state.cancelTxHashes, nonce, true) ?? await this.tryGetTxReceipt(state.txHashes, nonce, false);
399
+ if (receipt) {
400
+ state.receipt = receipt;
401
+ await this.updateState(state, TxUtilsState.MINED, l1Timestamp);
402
+ return receipt;
403
+ }
404
+ // If we get here then we have checked all of our tx versions and not found anything.
405
+ // We should consider the nonce as MINED
406
+ await this.updateState(state, TxUtilsState.MINED, l1Timestamp);
407
+ throw new UnknownMinedTxError(nonce, account);
408
+ }
409
+ // If this is a cancel tx and its nonce is no longer on the mempool, we consider it dropped and stop monitoring
410
+ // If it is a regular tx, we let the loop speed it up after the stall time
411
+ if (isCancelTx && pendingNonce <= nonce && timePassed >= gasConfig.txUnseenConsideredDroppedMs) {
412
+ this.logger.warn(`Cancellation tx with nonce ${nonce} for account ${account} has been dropped from the visible mempool`, {
413
+ nonce,
414
+ account,
415
+ pendingNonce,
416
+ timePassed
417
+ });
418
+ await this.updateState(state, TxUtilsState.NOT_MINED);
419
+ throw new DroppedTransactionError(nonce, account);
420
+ }
421
+ // Break if the tx has timed out (ie expired)
422
+ if (this.isTxTimedOut(state, l1Timestamp)) {
423
+ break;
424
+ }
425
+ // Speed up the transaction if it appears to be stuck (exceeded stall time and still have retry attempts)
426
+ const attempts = txHashes.length;
427
+ if (timePassed >= stallTimeMs && attempts <= maxSpeedUpAttempts) {
428
+ const newFeesPerGas = await this.getFeesPerGas(gasConfig, isBlobTx, attempts, state.feesPerGas);
429
+ state.feesPerGas = newFeesPerGas;
430
+ state.feesPerGasHistory?.push(newFeesPerGas);
431
+ this.logger.debug(`Tx ${currentTxHash} with nonce ${nonce} from ${account} appears stuck. ` + `Attempting speed-up ${attempts}/${maxSpeedUpAttempts} ` + `with new priority fee ${formatGwei(newFeesPerGas.maxPriorityFeePerGas)} gwei.`, {
432
+ account,
433
+ nonce,
434
+ maxFeePerGas: formatGwei(newFeesPerGas.maxFeePerGas),
435
+ maxPriorityFeePerGas: formatGwei(newFeesPerGas.maxPriorityFeePerGas),
436
+ ...newFeesPerGas.maxFeePerBlobGas && {
437
+ maxFeePerBlobGas: formatGwei(newFeesPerGas.maxFeePerBlobGas)
438
+ }
439
+ });
440
+ const txData = this.makeTxData(state, {
441
+ isCancelTx
442
+ });
443
+ const signedRequest = await this.prepareSignedTransaction(txData);
444
+ const newHash = await this.client.sendRawTransaction({
445
+ serializedTransaction: signedRequest
446
+ });
447
+ this.logger.verbose(`Sent L1 speed-up tx ${newHash} replacing ${currentTxHash} for nonce ${nonce} from ${account}`, {
448
+ nonce,
449
+ account,
450
+ gasLimit,
451
+ maxFeePerGas: formatGwei(newFeesPerGas.maxFeePerGas),
452
+ maxPriorityFeePerGas: formatGwei(newFeesPerGas.maxPriorityFeePerGas),
453
+ txConfig: state.txConfigOverrides,
454
+ ...newFeesPerGas.maxFeePerBlobGas && {
455
+ maxFeePerBlobGas: formatGwei(newFeesPerGas.maxFeePerBlobGas)
456
+ }
457
+ });
458
+ currentTxHash = newHash;
459
+ txHashes.push(currentTxHash);
460
+ state.lastSentAtL1Ts = new Date(l1Timestamp);
461
+ await this.updateState(state, isCancelTx ? TxUtilsState.CANCELLED : TxUtilsState.SPEED_UP);
462
+ await sleep(gasConfig.checkIntervalMs);
463
+ continue;
464
+ }
465
+ this.logger.debug(`Tx ${currentTxHash} from ${account} with nonce ${nonce} still pending after ${timePassed}ms`, {
466
+ account,
467
+ nonce,
468
+ pendingNonce,
469
+ attempts,
470
+ timePassed,
471
+ isBlobTx,
472
+ isCancelTx,
473
+ ...pick(state.feesPerGas, 'maxFeePerGas', 'maxPriorityFeePerGas', 'maxFeePerBlobGas'),
474
+ ...pick(gasConfig, 'txUnseenConsideredDroppedMs', 'txCancellationFinalTimeoutMs', 'maxSpeedUpAttempts', 'stallTimeMs', 'txTimeoutAt', 'txTimeoutMs')
475
+ });
476
+ await sleep(gasConfig.checkIntervalMs);
477
+ } catch (err) {
478
+ if (err instanceof DroppedTransactionError || err instanceof UnknownMinedTxError) {
479
+ throw err;
480
+ }
481
+ const viemError = formatViemError(err);
482
+ this.logger.error(`Error while monitoring L1 tx ${currentTxHash}`, viemError, {
483
+ nonce,
484
+ account
485
+ });
486
+ await sleep(gasConfig.checkIntervalMs);
487
+ }
488
+ }
489
+ // Oh no, the transaction has timed out!
490
+ if (isCancelTx || !gasConfig.cancelTxOnTimeout) {
491
+ await this.updateState(state, TxUtilsState.NOT_MINED);
492
+ } else {
493
+ // Otherwise we fire the cancellation without awaiting to avoid blocking the caller,
494
+ // and monitor it in the background so we can speed it up as needed.
495
+ void this.attemptTxCancellation(state).catch(async (err)=>{
496
+ await this.updateState(state, TxUtilsState.NOT_MINED);
497
+ this.logger.error(`Failed to send cancellation for timed out tx ${initialTxHash} with nonce ${nonce}`, err, {
498
+ account,
499
+ nonce,
500
+ initialTxHash
501
+ });
502
+ });
503
+ }
504
+ const what = isCancelTx ? 'Cancellation L1' : 'L1';
505
+ this.logger.warn(`${what} transaction ${initialTxHash} with nonce ${nonce} from ${account} timed out`, {
506
+ initialTxHash,
507
+ currentTxHash,
508
+ nonce,
509
+ account,
510
+ txTimeoutAt: gasConfig.txTimeoutAt?.getTime(),
511
+ txTimeoutMs: gasConfig.txTimeoutMs,
512
+ txInitialTime: state.sentAtL1Ts.getTime(),
513
+ l1Timestamp,
514
+ now: this.dateProvider.now(),
515
+ attempts: txHashes.length - 1,
516
+ isInterrupted: this.interrupted
517
+ });
518
+ throw new TimeoutError(`L1 transaction ${initialTxHash} timed out`);
519
+ }
520
+ /**
521
+ * Creates tx data to be signed by viem signTransaction method, using the state as input.
522
+ * If isCancelTx is true, creates a 0-value tx to self with 21k gas and no data instead,
523
+ * and an empty blob input if the original tx also had blobs.
524
+ */ makeTxData(state, opts) {
525
+ const { request, gasLimit, blobInputs, feesPerGas, nonce } = state;
526
+ const isBlobTx = blobInputs !== undefined;
527
+ const baseTxOpts = {
528
+ nonce,
529
+ ...pick(feesPerGas, 'maxFeePerGas', 'maxPriorityFeePerGas')
530
+ };
531
+ if (opts.isCancelTx) {
532
+ const baseTxData = {
533
+ to: this.getSenderAddress().toString(),
534
+ value: 0n,
535
+ data: '0x',
536
+ gas: 21_000n,
537
+ ...baseTxOpts
538
+ };
539
+ return isBlobTx ? {
540
+ ...baseTxData,
541
+ ...this.makeEmptyBlobInputs(feesPerGas.maxFeePerBlobGas)
542
+ } : baseTxData;
543
+ }
544
+ const baseTxData = {
545
+ ...request,
546
+ ...baseTxOpts,
547
+ gas: gasLimit
548
+ };
549
+ return blobInputs ? {
550
+ ...baseTxData,
551
+ ...blobInputs,
552
+ maxFeePerBlobGas: feesPerGas.maxFeePerBlobGas
553
+ } : baseTxData;
554
+ }
555
+ /** Returns when all monitor loops have stopped. */ async waitMonitoringStopped(timeoutSeconds = 10) {
556
+ const account = this.getSenderAddress().toString();
557
+ await retryUntil(()=>this.txs.every((tx)=>TerminalTxUtilsState.includes(tx.status)), `monitoring stopped for ${account}`, timeoutSeconds, 0.1).catch(()=>this.logger.warn(`Timeout waiting for monitoring loops to stop for ${account}`));
558
+ }
559
+ /**
560
+ * Sends a transaction and monitors it until completion
561
+ * @param request - The transaction request (to, data, value)
562
+ * @param gasConfig - Optional gas configuration
563
+ * @returns The receipt of the successful transaction
564
+ */ async sendAndMonitorTransaction(request, gasConfig, blobInputs) {
565
+ const { state } = await this.sendTransaction(request, gasConfig, blobInputs);
566
+ try {
567
+ const receipt = await this.monitorTransaction(state);
568
+ return {
569
+ receipt,
570
+ state
571
+ };
572
+ } catch (err) {
573
+ if (err instanceof TimeoutError) {
574
+ // Snapshot the ladder now: the fire-and-forget cancellation mutates state.feesPerGas moments later.
575
+ throw new L1TxTimeoutError(err.message, {
576
+ feesPerGasHistory: state.feesPerGasHistory ? [
577
+ ...state.feesPerGasHistory
578
+ ] : undefined,
579
+ finalFeesPerGas: state.feesPerGas,
580
+ attempts: state.txHashes.length,
581
+ nonce: state.nonce,
582
+ gasLimit: state.gasLimit
583
+ });
584
+ }
585
+ throw err;
586
+ }
587
+ }
588
+ async simulate(request, _blockOverrides = {}, stateOverrides = [], abi = RollupAbi, _gasConfig) {
589
+ const blockOverrides = {
590
+ ..._blockOverrides
591
+ };
592
+ const gasConfig = merge(this.config, _gasConfig);
593
+ // Fee fields are deliberately omitted. Supplying them makes the node apply the EIP-1559 upfront funds
594
+ // check (sender balance >= gas * maxFeePerGas) against the worst-case gas cap below, which rejects the
595
+ // whole simulation request before any execution. Omitted fee fields default to a zero gas price.
596
+ const call = {
597
+ to: request.to,
598
+ data: request.data,
599
+ from: request.from ?? this.getSenderAddress().toString(),
600
+ gas: request.gas ?? MAX_L1_TX_LIMIT
601
+ };
602
+ if (!request.gas && !gasConfig.ignoreBlockGasLimit) {
603
+ // MAX_L1_TX_LIMIT is set as call.gas, ensure block gasLimit is sufficient
604
+ blockOverrides.gasLimit = MAX_L1_TX_LIMIT;
605
+ }
606
+ return await this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
607
+ }
608
+ /**
609
+ * Attempts to cancel a transaction by sending a 0-value tx to self with same nonce but higher gas prices
610
+ * Only sends the cancellation if the original tx is still pending, not if it was dropped
611
+ * @returns The hash of the cancellation transaction
612
+ */ async attemptTxCancellation(state) {
613
+ const isBlobTx = state.blobInputs !== undefined;
614
+ const { nonce, feesPerGas: previousFeesPerGas } = state;
615
+ const account = this.getSenderAddress().toString();
616
+ // Do not send cancellation if interrupted
617
+ if (this.interrupted) {
618
+ this.logger.warn(`Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as interrupted`, {
619
+ nonce,
620
+ account
621
+ });
622
+ await this.updateState(state, TxUtilsState.NOT_MINED);
623
+ return;
624
+ }
625
+ // Resolve the pending nonce and cancellation fees per gas up front. These are read-only RPC calls, so
626
+ // they are safe to retry; a transient RPC failure here must not permanently abandon the cancellation
627
+ // (which would leave the nonce stuck and the tx state stranded short of CANCELLED). We retry with a
628
+ // real backoff before giving up, unlike getFeesPerGas's tight internal retry which can be exhausted by
629
+ // a brief node hiccup. The retried block performs no state-changing send, so retrying cannot
630
+ // double-send the cancellation tx.
631
+ const { currentNonce, cancelFeesPerGas } = await retry(async ()=>{
632
+ const currentNonce = await this.client.getTransactionCount({
633
+ address: account,
634
+ blockTag: 'pending'
635
+ });
636
+ if (currentNonce >= nonce) {
637
+ // Get fees per gas with higher priority fee for cancellation
638
+ const cancelFeesPerGas = await this.getFeesPerGas({
639
+ ...this.config,
640
+ // Use high bump for cancellation to ensure it replaces the original tx
641
+ priorityFeeRetryBumpPercentage: 150
642
+ }, isBlobTx, state.txHashes.length, previousFeesPerGas);
643
+ return {
644
+ currentNonce,
645
+ cancelFeesPerGas
646
+ };
647
+ }
648
+ return {
649
+ currentNonce,
650
+ cancelFeesPerGas: undefined
651
+ };
652
+ }, `Preparing cancellation for L1 tx from account ${account} with nonce ${nonce}`, makeBackoff(CANCELLATION_PREP_RETRY_BACKOFF_S), this.logger);
653
+ if (cancelFeesPerGas === undefined) {
654
+ this.logger.verbose(`Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`, {
655
+ nonce,
656
+ account,
657
+ currentNonce
658
+ });
659
+ await this.updateState(state, TxUtilsState.NOT_MINED);
660
+ return;
661
+ }
662
+ const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelFeesPerGas;
663
+ this.logger.verbose(`Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`, {
664
+ maxFeePerGas: formatGwei(maxFeePerGas),
665
+ maxPriorityFeePerGas: formatGwei(maxPriorityFeePerGas),
666
+ ...maxFeePerBlobGas && {
667
+ maxFeePerBlobGas: formatGwei(maxFeePerBlobGas)
668
+ }
669
+ });
670
+ // Send 0-value tx to self with higher gas price
671
+ state.feesPerGas = cancelFeesPerGas;
672
+ state.lastSentAtL1Ts = new Date(await this.getL1Timestamp());
673
+ const txData = this.makeTxData(state, {
674
+ isCancelTx: true
675
+ });
676
+ const signedRequest = await this.prepareSignedTransaction(txData);
677
+ const cancelTxHash = await this.client.sendRawTransaction({
678
+ serializedTransaction: signedRequest
679
+ });
680
+ state.cancelTxHashes.push(cancelTxHash);
681
+ await this.updateState(state, TxUtilsState.CANCELLED);
682
+ this.logger.warn(`Sent cancellation tx ${cancelTxHash} for timed out tx from ${account} with nonce ${nonce}`, {
683
+ nonce,
684
+ cancelFeesPerGas,
685
+ isBlobTx,
686
+ txHashes: state.txHashes
687
+ });
688
+ // Do not await the cancel tx to be mined
689
+ void this.monitorTransaction(state).catch((err)=>{
690
+ this.logger.error(`Failed to mine cancellation tx ${cancelTxHash} for nonce ${nonce} account ${account}`, err, {
691
+ nonce,
692
+ account,
693
+ cancelTxHash
694
+ });
695
+ });
696
+ }
697
+ /** Returns L1 timestamps in milliseconds */ async getL1Timestamp() {
698
+ const { timestamp } = await this.client.getBlock({
699
+ blockTag: 'latest',
700
+ includeTransactions: false
701
+ });
702
+ return Number(timestamp) * 1000;
703
+ }
704
+ /** Makes empty blob inputs for the cancellation tx. */ makeEmptyBlobInputs(maxFeePerBlobGas) {
705
+ if (!this.kzg) {
706
+ throw new Error('Cannot make empty blob inputs for cancellation without kzg');
707
+ }
708
+ const blobData = new Uint8Array(131072).fill(0);
709
+ return {
710
+ blobs: [
711
+ blobData
712
+ ],
713
+ kzg: this.kzg,
714
+ maxFeePerBlobGas
715
+ };
716
+ }
717
+ /** Creates a new delayer instance. */ createDelayer(opts, bindings) {
718
+ return createDelayer(this.dateProvider, opts, bindings);
719
+ }
720
+ }