@aztec/ethereum 0.0.0-test.0 → 0.0.1-commit.001888fc

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