@aztec/ethereum 0.0.0-test.1 → 0.0.1-commit.017a351

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