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