@aztec-labs/ethereum 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/README.md +3 -0
  2. package/dest/account.d.ts +2 -0
  3. package/dest/account.d.ts.map +1 -0
  4. package/dest/account.js +4 -0
  5. package/dest/chain.d.ts +25 -0
  6. package/dest/chain.d.ts.map +1 -0
  7. package/dest/chain.js +53 -0
  8. package/dest/client.d.ts +42 -0
  9. package/dest/client.d.ts.map +1 -0
  10. package/dest/client.js +104 -0
  11. package/dest/config.d.ts +103 -0
  12. package/dest/config.d.ts.map +1 -0
  13. package/dest/config.js +233 -0
  14. package/dest/constants.d.ts +4 -0
  15. package/dest/constants.d.ts.map +1 -0
  16. package/dest/constants.js +2 -0
  17. package/dest/contracts/chain_state_override.d.ts +81 -0
  18. package/dest/contracts/chain_state_override.d.ts.map +1 -0
  19. package/dest/contracts/chain_state_override.js +139 -0
  20. package/dest/contracts/empire_base.d.ts +30 -0
  21. package/dest/contracts/empire_base.d.ts.map +1 -0
  22. package/dest/contracts/empire_base.js +84 -0
  23. package/dest/contracts/errors.d.ts +7 -0
  24. package/dest/contracts/errors.d.ts.map +1 -0
  25. package/dest/contracts/errors.js +12 -0
  26. package/dest/contracts/fee_asset_handler.d.ts +20 -0
  27. package/dest/contracts/fee_asset_handler.d.ts.map +1 -0
  28. package/dest/contracts/fee_asset_handler.js +59 -0
  29. package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
  30. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  31. package/dest/contracts/fee_asset_price_oracle.js +656 -0
  32. package/dest/contracts/fee_juice.d.ts +14 -0
  33. package/dest/contracts/fee_juice.d.ts.map +1 -0
  34. package/dest/contracts/fee_juice.js +59 -0
  35. package/dest/contracts/governance.d.ts +192 -0
  36. package/dest/contracts/governance.d.ts.map +1 -0
  37. package/dest/contracts/governance.js +471 -0
  38. package/dest/contracts/governance_proposer.d.ts +63 -0
  39. package/dest/contracts/governance_proposer.d.ts.map +1 -0
  40. package/dest/contracts/governance_proposer.js +536 -0
  41. package/dest/contracts/gse.d.ts +38 -0
  42. package/dest/contracts/gse.d.ts.map +1 -0
  43. package/dest/contracts/gse.js +81 -0
  44. package/dest/contracts/inbox.d.ts +94 -0
  45. package/dest/contracts/inbox.d.ts.map +1 -0
  46. package/dest/contracts/inbox.js +141 -0
  47. package/dest/contracts/index.d.ts +18 -0
  48. package/dest/contracts/index.d.ts.map +1 -0
  49. package/dest/contracts/index.js +17 -0
  50. package/dest/contracts/log.d.ts +13 -0
  51. package/dest/contracts/log.d.ts.map +1 -0
  52. package/dest/contracts/log.js +1 -0
  53. package/dest/contracts/multicall.d.ts +138 -0
  54. package/dest/contracts/multicall.d.ts.map +1 -0
  55. package/dest/contracts/multicall.js +266 -0
  56. package/dest/contracts/outbox.d.ts +64 -0
  57. package/dest/contracts/outbox.d.ts.map +1 -0
  58. package/dest/contracts/outbox.js +113 -0
  59. package/dest/contracts/registry.d.ts +31 -0
  60. package/dest/contracts/registry.d.ts.map +1 -0
  61. package/dest/contracts/registry.js +142 -0
  62. package/dest/contracts/rollup.d.ts +5836 -0
  63. package/dest/contracts/rollup.d.ts.map +1 -0
  64. package/dest/contracts/rollup.js +1612 -0
  65. package/dest/contracts/slasher_contract.d.ts +44 -0
  66. package/dest/contracts/slasher_contract.d.ts.map +1 -0
  67. package/dest/contracts/slasher_contract.js +75 -0
  68. package/dest/contracts/slashing_proposer.d.ts +174 -0
  69. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  70. package/dest/contracts/slashing_proposer.js +755 -0
  71. package/dest/contracts/utils.d.ts +3 -0
  72. package/dest/contracts/utils.d.ts.map +1 -0
  73. package/dest/contracts/utils.js +11 -0
  74. package/dest/contracts/watch_event.d.ts +36 -0
  75. package/dest/contracts/watch_event.d.ts.map +1 -0
  76. package/dest/contracts/watch_event.js +66 -0
  77. package/dest/deploy_aztec_l1_contracts.d.ts +267 -0
  78. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -0
  79. package/dest/deploy_aztec_l1_contracts.js +424 -0
  80. package/dest/deploy_l1_contract.d.ts +68 -0
  81. package/dest/deploy_l1_contract.d.ts.map +1 -0
  82. package/dest/deploy_l1_contract.js +312 -0
  83. package/dest/eth-signer/eth-signer.d.ts +21 -0
  84. package/dest/eth-signer/eth-signer.d.ts.map +1 -0
  85. package/dest/eth-signer/eth-signer.js +5 -0
  86. package/dest/eth-signer/index.d.ts +2 -0
  87. package/dest/eth-signer/index.d.ts.map +1 -0
  88. package/dest/eth-signer/index.js +1 -0
  89. package/dest/forwarder_proxy.d.ts +32 -0
  90. package/dest/forwarder_proxy.d.ts.map +1 -0
  91. package/dest/forwarder_proxy.js +93 -0
  92. package/dest/foundry_binary.d.ts +13 -0
  93. package/dest/foundry_binary.d.ts.map +1 -0
  94. package/dest/foundry_binary.js +52 -0
  95. package/dest/l1_artifacts.d.ts +81896 -0
  96. package/dest/l1_artifacts.d.ts.map +1 -0
  97. package/dest/l1_artifacts.js +151 -0
  98. package/dest/l1_contract_addresses.d.ts +73 -0
  99. package/dest/l1_contract_addresses.d.ts.map +1 -0
  100. package/dest/l1_contract_addresses.js +120 -0
  101. package/dest/l1_reader.d.ts +18 -0
  102. package/dest/l1_reader.d.ts.map +1 -0
  103. package/dest/l1_reader.js +35 -0
  104. package/dest/l1_tx_utils/config.d.ts +65 -0
  105. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  106. package/dest/l1_tx_utils/config.js +109 -0
  107. package/dest/l1_tx_utils/constants.d.ts +12 -0
  108. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  109. package/dest/l1_tx_utils/constants.js +39 -0
  110. package/dest/l1_tx_utils/factory.d.ts +32 -0
  111. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  112. package/dest/l1_tx_utils/factory.js +22 -0
  113. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  114. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  115. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  116. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  117. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  118. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  119. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  120. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  121. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  122. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  123. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  124. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  125. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
  126. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
  127. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +42 -0
  128. package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
  129. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
  130. package/dest/l1_tx_utils/index-blobs.js +2 -0
  131. package/dest/l1_tx_utils/index.d.ts +13 -0
  132. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  133. package/dest/l1_tx_utils/index.js +13 -0
  134. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  135. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  136. package/dest/l1_tx_utils/interfaces.js +4 -0
  137. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +252 -0
  138. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  139. package/dest/l1_tx_utils/l1_fee_analyzer.js +568 -0
  140. package/dest/l1_tx_utils/l1_tx_utils.d.ts +113 -0
  141. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  142. package/dest/l1_tx_utils/l1_tx_utils.js +720 -0
  143. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +83 -0
  144. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  145. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +357 -0
  146. package/dest/l1_tx_utils/signer.d.ts +4 -0
  147. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  148. package/dest/l1_tx_utils/signer.js +16 -0
  149. package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
  150. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  151. package/dest/l1_tx_utils/tx_delayer.js +223 -0
  152. package/dest/l1_tx_utils/types.d.ts +93 -0
  153. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  154. package/dest/l1_tx_utils/types.js +36 -0
  155. package/dest/l1_tx_utils/utils.d.ts +4 -0
  156. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  157. package/dest/l1_tx_utils/utils.js +14 -0
  158. package/dest/l1_types.d.ts +6 -0
  159. package/dest/l1_types.d.ts.map +1 -0
  160. package/dest/l1_types.js +1 -0
  161. package/dest/publisher_manager.d.ts +42 -0
  162. package/dest/publisher_manager.d.ts.map +1 -0
  163. package/dest/publisher_manager.js +199 -0
  164. package/dest/queries.d.ts +25 -0
  165. package/dest/queries.d.ts.map +1 -0
  166. package/dest/queries.js +144 -0
  167. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  168. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  169. package/dest/test/blob_kzg_warmup.js +64 -0
  170. package/dest/test/chain_monitor.d.ts +126 -0
  171. package/dest/test/chain_monitor.d.ts.map +1 -0
  172. package/dest/test/chain_monitor.js +314 -0
  173. package/dest/test/eth_cheat_codes.d.ts +260 -0
  174. package/dest/test/eth_cheat_codes.d.ts.map +1 -0
  175. package/dest/test/eth_cheat_codes.js +608 -0
  176. package/dest/test/eth_cheat_codes_with_state.d.ts +18 -0
  177. package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -0
  178. package/dest/test/eth_cheat_codes_with_state.js +34 -0
  179. package/dest/test/index.d.ts +8 -0
  180. package/dest/test/index.d.ts.map +1 -0
  181. package/dest/test/index.js +7 -0
  182. package/dest/test/recording_rpc_server.d.ts +18 -0
  183. package/dest/test/recording_rpc_server.d.ts.map +1 -0
  184. package/dest/test/recording_rpc_server.js +68 -0
  185. package/dest/test/rollup_cheat_codes.d.ts +142 -0
  186. package/dest/test/rollup_cheat_codes.d.ts.map +1 -0
  187. package/dest/test/rollup_cheat_codes.js +338 -0
  188. package/dest/test/start_anvil.d.ts +40 -0
  189. package/dest/test/start_anvil.d.ts.map +1 -0
  190. package/dest/test/start_anvil.js +210 -0
  191. package/dest/test/upgrade_utils.d.ts +12 -0
  192. package/dest/test/upgrade_utils.d.ts.map +1 -0
  193. package/dest/test/upgrade_utils.js +111 -0
  194. package/dest/types.d.ts +68 -0
  195. package/dest/types.d.ts.map +1 -0
  196. package/dest/types.js +3 -0
  197. package/dest/utils.d.ts +45 -0
  198. package/dest/utils.d.ts.map +1 -0
  199. package/dest/utils.js +260 -0
  200. package/dest/zkPassportVerifierAddress.d.ts +15 -0
  201. package/dest/zkPassportVerifierAddress.d.ts.map +1 -0
  202. package/dest/zkPassportVerifierAddress.js +11 -0
  203. package/package.json +122 -0
  204. package/src/account.ts +5 -0
  205. package/src/chain.ts +71 -0
  206. package/src/client.ts +165 -0
  207. package/src/config.ts +342 -0
  208. package/src/constants.ts +4 -0
  209. package/src/contracts/README.md +157 -0
  210. package/src/contracts/chain_state_override.ts +203 -0
  211. package/src/contracts/empire_base.ts +89 -0
  212. package/src/contracts/errors.ts +13 -0
  213. package/src/contracts/fee_asset_handler.ts +66 -0
  214. package/src/contracts/fee_asset_price_oracle.ts +284 -0
  215. package/src/contracts/fee_juice.ts +57 -0
  216. package/src/contracts/governance.ts +597 -0
  217. package/src/contracts/governance_proposer.ts +181 -0
  218. package/src/contracts/gse.ts +105 -0
  219. package/src/contracts/inbox.ts +223 -0
  220. package/src/contracts/index.ts +17 -0
  221. package/src/contracts/log.ts +13 -0
  222. package/src/contracts/multicall.ts +298 -0
  223. package/src/contracts/outbox.ts +132 -0
  224. package/src/contracts/registry.ts +161 -0
  225. package/src/contracts/rollup.ts +1502 -0
  226. package/src/contracts/slasher_contract.ts +89 -0
  227. package/src/contracts/slashing_proposer.ts +397 -0
  228. package/src/contracts/utils.ts +14 -0
  229. package/src/contracts/watch_event.ts +109 -0
  230. package/src/deploy_aztec_l1_contracts.ts +663 -0
  231. package/src/deploy_l1_contract.ts +361 -0
  232. package/src/eth-signer/eth-signer.ts +24 -0
  233. package/src/eth-signer/index.ts +1 -0
  234. package/src/forwarder_proxy.ts +107 -0
  235. package/src/foundry_binary.ts +57 -0
  236. package/src/l1_artifacts.ts +231 -0
  237. package/src/l1_contract_addresses.ts +149 -0
  238. package/src/l1_reader.ts +57 -0
  239. package/src/l1_tx_utils/README.md +177 -0
  240. package/src/l1_tx_utils/config.ts +181 -0
  241. package/src/l1_tx_utils/constants.ts +29 -0
  242. package/src/l1_tx_utils/factory.ts +64 -0
  243. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  244. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +162 -0
  245. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +244 -0
  246. package/src/l1_tx_utils/fee-strategies/types.ts +55 -0
  247. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +107 -0
  248. package/src/l1_tx_utils/index-blobs.ts +2 -0
  249. package/src/l1_tx_utils/index.ts +15 -0
  250. package/src/l1_tx_utils/interfaces.ts +86 -0
  251. package/src/l1_tx_utils/l1_fee_analyzer.ts +874 -0
  252. package/src/l1_tx_utils/l1_tx_utils.ts +840 -0
  253. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +459 -0
  254. package/src/l1_tx_utils/signer.ts +27 -0
  255. package/src/l1_tx_utils/tx_delayer.ts +302 -0
  256. package/src/l1_tx_utils/types.ts +116 -0
  257. package/src/l1_tx_utils/utils.ts +15 -0
  258. package/src/l1_types.ts +6 -0
  259. package/src/publisher_manager.ts +239 -0
  260. package/src/queries.ts +189 -0
  261. package/src/test/blob_kzg_warmup.ts +65 -0
  262. package/src/test/chain_monitor.ts +389 -0
  263. package/src/test/eth_cheat_codes.ts +624 -0
  264. package/src/test/eth_cheat_codes_with_state.ts +38 -0
  265. package/src/test/index.ts +7 -0
  266. package/src/test/recording_rpc_server.ts +69 -0
  267. package/src/test/rollup_cheat_codes.ts +398 -0
  268. package/src/test/start_anvil.ts +255 -0
  269. package/src/test/upgrade_utils.ts +109 -0
  270. package/src/types.ts +97 -0
  271. package/src/utils.ts +344 -0
  272. package/src/zkPassportVerifierAddress.ts +15 -0
@@ -0,0 +1,302 @@
1
+ import { omit } from '@aztec-labs/foundation/collection';
2
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec-labs/foundation/log';
3
+ import { retryUntil } from '@aztec-labs/foundation/retry';
4
+ import type { DateProvider } from '@aztec-labs/foundation/timer';
5
+ import { inspect } from 'util';
6
+ import {
7
+ type Client,
8
+ type Hex,
9
+ type PublicClient,
10
+ type TransactionSerializableEIP4844,
11
+ type TransactionSerialized,
12
+ keccak256,
13
+ parseTransaction,
14
+ publicActions,
15
+ recoverTransactionAddress,
16
+ serializeTransaction,
17
+ walletActions,
18
+ } from 'viem';
19
+
20
+ import type { ExtendedViemWalletClient, ViemClient } from '../types.js';
21
+
22
+ const MAX_WAIT_TIME_SECONDS = 180;
23
+
24
+ export function waitUntilBlock<T extends Client>(
25
+ client: T,
26
+ blockNumber: number | bigint,
27
+ logger?: Logger,
28
+ timeout?: number,
29
+ ) {
30
+ const publicClient =
31
+ 'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
32
+ ? (client as unknown as PublicClient)
33
+ : client.extend(publicActions);
34
+
35
+ return retryUntil(
36
+ async () => {
37
+ const currentBlockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });
38
+ logger?.debug(`Block number is ${currentBlockNumber} (waiting until ${blockNumber})`);
39
+ return currentBlockNumber >= BigInt(blockNumber);
40
+ },
41
+ `Wait until L1 block ${blockNumber}`,
42
+ timeout ?? MAX_WAIT_TIME_SECONDS,
43
+ 0.1,
44
+ );
45
+ }
46
+
47
+ export function waitUntilL1Timestamp<T extends Client>(
48
+ client: T,
49
+ timestamp: number | bigint,
50
+ logger?: Logger,
51
+ timeout?: number,
52
+ ) {
53
+ const publicClient =
54
+ 'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
55
+ ? (client as unknown as PublicClient)
56
+ : client.extend(publicActions);
57
+
58
+ let lastBlock: bigint | undefined = undefined;
59
+ return retryUntil(
60
+ async () => {
61
+ const currentBlockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });
62
+ if (currentBlockNumber === lastBlock) {
63
+ return false;
64
+ }
65
+ lastBlock = currentBlockNumber;
66
+ const currentBlock = await publicClient.getBlock({ includeTransactions: false, blockNumber: currentBlockNumber });
67
+ const currentTs = currentBlock.timestamp;
68
+ logger?.debug(`Block timstamp is ${currentTs} (waiting until ${timestamp})`);
69
+ return currentTs >= BigInt(timestamp);
70
+ },
71
+ `Wait until L1 timestamp ${timestamp}`,
72
+ timeout ?? MAX_WAIT_TIME_SECONDS,
73
+ 0.1,
74
+ );
75
+ }
76
+
77
+ /** Manages tx delaying for testing, intercepting sendRawTransaction calls to delay or cancel them. */
78
+ export class Delayer {
79
+ private logger: Logger;
80
+
81
+ public maxInclusionTimeIntoSlot: number | undefined = undefined;
82
+ public ethereumSlotDuration: bigint;
83
+ public nextWait:
84
+ | { l1Timestamp: bigint; timeoutSeconds?: number }
85
+ | { l1BlockNumber: bigint; timeoutSeconds?: number }
86
+ | { indefinitely: true }
87
+ | undefined = undefined;
88
+ public sentTxHashes: Hex[] = [];
89
+ public cancelledTxs: Hex[] = [];
90
+
91
+ constructor(
92
+ public dateProvider: DateProvider,
93
+ opts: { ethereumSlotDuration: bigint | number },
94
+ bindings: LoggerBindings,
95
+ ) {
96
+ this.ethereumSlotDuration = BigInt(opts.ethereumSlotDuration);
97
+ this.logger = createLogger('ethereum:tx_delayer', bindings);
98
+ }
99
+
100
+ /** Returns the logger instance used by this delayer. */
101
+ getLogger(): Logger {
102
+ return this.logger;
103
+ }
104
+
105
+ /** Returns the hashes of all effectively sent txs. */
106
+ getSentTxHashes() {
107
+ return this.sentTxHashes;
108
+ }
109
+
110
+ /** Returns the raw hex for all cancelled txs. */
111
+ getCancelledTxs(): Hex[] {
112
+ return this.cancelledTxs;
113
+ }
114
+
115
+ /** Delays the next tx to be sent so it lands on the given L1 block number. */
116
+ pauseNextTxUntilBlock(l1BlockNumber: number | bigint, timeoutSeconds?: number) {
117
+ this.nextWait = { l1BlockNumber: BigInt(l1BlockNumber), timeoutSeconds };
118
+ }
119
+
120
+ /** Delays the next tx to be sent so it lands on the given timestamp. */
121
+ pauseNextTxUntilTimestamp(l1Timestamp: number | bigint, timeoutSeconds?: number) {
122
+ this.nextWait = { l1Timestamp: BigInt(l1Timestamp), timeoutSeconds };
123
+ }
124
+
125
+ /** Delays the next tx to be sent indefinitely. */
126
+ cancelNextTx() {
127
+ this.nextWait = { indefinitely: true };
128
+ }
129
+
130
+ /**
131
+ * Sets max inclusion time into slot. If more than this many seconds have passed
132
+ * since the last L1 block was mined, then any tx will not be mined in the current
133
+ * L1 slot but will be deferred for the next one.
134
+ */
135
+ setMaxInclusionTimeIntoSlot(seconds: number | undefined) {
136
+ this.maxInclusionTimeIntoSlot = seconds;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Creates a new Delayer instance. Exposed so callers can create a single shared delayer
142
+ * and pass it to multiple `wrapClientWithDelayer` calls.
143
+ */
144
+ export function createDelayer(
145
+ dateProvider: DateProvider,
146
+ opts: { ethereumSlotDuration: bigint | number },
147
+ bindings: LoggerBindings,
148
+ ): Delayer {
149
+ return new Delayer(dateProvider, opts, bindings);
150
+ }
151
+
152
+ /** Tries to recover the sender address from a serialized signed transaction. */
153
+ async function tryRecoverSender(serializedTransaction: Hex): Promise<string | undefined> {
154
+ try {
155
+ return await recoverTransactionAddress({
156
+ serializedTransaction: serializedTransaction as TransactionSerialized,
157
+ });
158
+ } catch {
159
+ return undefined;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Wraps a viem client with tx delaying logic. Returns the wrapped client.
165
+ * The delayer intercepts sendRawTransaction calls and delays them based on the delayer's state.
166
+ */
167
+ export function wrapClientWithDelayer<T extends ViemClient>(client: T, delayer: Delayer): T {
168
+ const logger = delayer.getLogger();
169
+
170
+ // Cast to ExtendedViemWalletClient for the extend chain since it has sendRawTransaction.
171
+ // The sendRawTransaction override is applied to all clients regardless of type.
172
+ const withRawTx = (client as unknown as ExtendedViemWalletClient)
173
+ // Tweak sendRawTransaction so it uses the delay defined in the delayer.
174
+ // Note that this will only work with local accounts (ie accounts for which we have the private key).
175
+ // Transactions signed by the node will not be delayed since they use sendTransaction directly,
176
+ // but we do not use them in our codebase at all.
177
+ .extend(client => ({
178
+ async sendRawTransaction(...args) {
179
+ let wait: Promise<unknown> | undefined;
180
+ let txHash: Hex | undefined;
181
+
182
+ const { serializedTransaction } = args[0];
183
+ const publicClient = client as unknown as PublicClient;
184
+ const sender = await tryRecoverSender(serializedTransaction);
185
+
186
+ if (delayer.nextWait !== undefined) {
187
+ // Check if we have been instructed to delay the next tx.
188
+ const waitUntil = delayer.nextWait;
189
+ delayer.nextWait = undefined;
190
+
191
+ // Compute the tx hash manually so we emulate sendRawTransaction response
192
+ txHash = computeTxHash(serializedTransaction);
193
+
194
+ // Cancel tx outright if instructed
195
+ if ('indefinitely' in waitUntil && waitUntil.indefinitely) {
196
+ logger.info(`Cancelling tx ${txHash}`, { sender });
197
+ delayer.cancelledTxs.push(serializedTransaction);
198
+ return Promise.resolve(txHash);
199
+ }
200
+
201
+ // Or wait until the desired block number or timestamp
202
+ wait =
203
+ 'l1BlockNumber' in waitUntil
204
+ ? waitUntilBlock(publicClient, waitUntil.l1BlockNumber - 1n, logger, waitUntil.timeoutSeconds)
205
+ : 'l1Timestamp' in waitUntil
206
+ ? waitUntilL1Timestamp(
207
+ publicClient,
208
+ waitUntil.l1Timestamp - delayer.ethereumSlotDuration,
209
+ logger,
210
+ waitUntil.timeoutSeconds,
211
+ )
212
+ : undefined;
213
+
214
+ logger.info(`Delaying tx ${txHash} until ${inspect(waitUntil)}`, {
215
+ sender,
216
+ argsLen: args.length,
217
+ ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
218
+ });
219
+ } else if (delayer.maxInclusionTimeIntoSlot !== undefined) {
220
+ // Check if we need to delay txs sent too close to the end of the slot.
221
+ const currentBlock = await publicClient.getBlock({ includeTransactions: false });
222
+ const { timestamp: lastBlockTimestamp, number } = currentBlock;
223
+ const now = delayer.dateProvider.now();
224
+
225
+ txHash = computeTxHash(serializedTransaction);
226
+ const logData = {
227
+ sender,
228
+ ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
229
+ lastBlockTimestamp,
230
+ now,
231
+ maxInclusionTimeIntoSlot: delayer.maxInclusionTimeIntoSlot,
232
+ };
233
+
234
+ if (now / 1000 - Number(lastBlockTimestamp) > delayer.maxInclusionTimeIntoSlot) {
235
+ // If the last block was mined more than `maxInclusionTimeIntoSlot` seconds ago, then we cannot include
236
+ // any txs in the current slot, so we delay the tx until the next slot.
237
+ logger.info(`Delaying inclusion of tx ${txHash} until the next slot since it was sent too late`, logData);
238
+ wait = waitUntilBlock(publicClient, number + 1n, logger);
239
+ } else {
240
+ logger.debug(`Immediately sending tx ${txHash} as it was received early enough in the slot`, logData);
241
+ }
242
+ }
243
+
244
+ if (wait !== undefined) {
245
+ // Do not await here so we can return the tx hash immediately as if it had been sent on the spot.
246
+ // Instead, delay it so it lands on the desired block number or timestamp, assuming anvil will
247
+ // mine it immediately.
248
+ void wait!
249
+ .then(async () => {
250
+ const clientTxHash = await client.sendRawTransaction(...args);
251
+ if (clientTxHash !== txHash) {
252
+ logger.error(`Tx hash returned by the client does not match computed one`, {
253
+ clientTxHash,
254
+ computedTxHash: txHash,
255
+ });
256
+ }
257
+ logger.info(`Sent previously delayed tx ${clientTxHash}`, { sender });
258
+ delayer.sentTxHashes.push(clientTxHash);
259
+ })
260
+ .catch(err => logger.error(`Error sending tx after delay`, err));
261
+ return Promise.resolve(txHash!);
262
+ } else {
263
+ const txHash = await client.sendRawTransaction(...args);
264
+ logger.debug(`Sent tx immediately ${txHash}`, { sender });
265
+ delayer.sentTxHashes.push(txHash);
266
+ return txHash;
267
+ }
268
+ },
269
+ }));
270
+
271
+ // Only re-bind wallet actions (sendTransaction, writeContract, deployContract) for wallet clients.
272
+ // This is needed for tests that use wallet actions directly rather than sendRawTransaction.
273
+ const isWalletClient = 'account' in client && client.account !== undefined;
274
+ const extended = isWalletClient
275
+ ? withRawTx
276
+ // Re-extend with sendTransaction so it uses the modified sendRawTransaction.
277
+ .extend(client => ({ sendTransaction: walletActions(client).sendTransaction }))
278
+ // And with the actions that depend on the modified sendTransaction
279
+ .extend(client => ({
280
+ writeContract: walletActions(client).writeContract,
281
+ deployContract: walletActions(client).deployContract,
282
+ }))
283
+ : withRawTx;
284
+
285
+ return extended as T;
286
+ }
287
+
288
+ /**
289
+ * Compute the tx hash given the serialized tx. Note that if this is a blob tx, we need to
290
+ * exclude the blobs, commitments, and proofs from the hash.
291
+ */
292
+ function computeTxHash(serializedTransaction: Hex) {
293
+ if (serializedTransaction.startsWith('0x03')) {
294
+ const parsed = parseTransaction(serializedTransaction);
295
+ if (parsed.blobs || parsed.sidecars) {
296
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
297
+ const { blobs, sidecars, ...rest } = parsed;
298
+ return keccak256(serializeTransaction({ type: 'eip4844', ...rest } as TransactionSerializableEIP4844));
299
+ }
300
+ }
301
+ return keccak256(serializedTransaction);
302
+ }
@@ -0,0 +1,116 @@
1
+ import type { BlobKzgInstance } from '@aztec-labs/blob-lib/types';
2
+ import { TimeoutError } from '@aztec-labs/foundation/error';
3
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
4
+ import type { ViemTransactionSignature } from '@aztec-labs/foundation/eth-signature';
5
+ import type { Abi, Address, Hex, TransactionReceipt, TransactionSerializable } from 'viem';
6
+
7
+ import type { L1TxUtilsConfig } from './config.js';
8
+
9
+ export interface L1TxRequest {
10
+ to: Address | null;
11
+ data?: Hex;
12
+ value?: bigint;
13
+ abi?: Abi;
14
+ }
15
+
16
+ export type L1TxConfig = Partial<L1TxUtilsConfig> & { gasLimit?: bigint; txTimeoutAt?: Date };
17
+
18
+ export interface L1BlobInputs {
19
+ blobs: Uint8Array[];
20
+ kzg: BlobKzgInstance;
21
+ maxFeePerBlobGas?: bigint;
22
+ }
23
+
24
+ export interface FeesPerGas {
25
+ maxFeePerGas: bigint;
26
+ maxPriorityFeePerGas: bigint;
27
+ maxFeePerBlobGas?: bigint;
28
+ }
29
+
30
+ export type TransactionStats = {
31
+ /** Address of the sender. */
32
+ sender: string;
33
+ /** Hash of the transaction. */
34
+ transactionHash: string;
35
+ /** Size in bytes of the tx calldata */
36
+ calldataSize: number;
37
+ /** Gas required to pay for the calldata inclusion (depends on size and number of zeros) */
38
+ calldataGas: number;
39
+ };
40
+
41
+ export enum TxUtilsState {
42
+ IDLE,
43
+ SENT,
44
+ SPEED_UP,
45
+ CANCELLED,
46
+ NOT_MINED,
47
+ MINED,
48
+ }
49
+
50
+ export const TerminalTxUtilsState = [TxUtilsState.IDLE, TxUtilsState.MINED, TxUtilsState.NOT_MINED];
51
+
52
+ export type L1TxState = {
53
+ id: number;
54
+ txHashes: Hex[];
55
+ cancelTxHashes: Hex[];
56
+ gasLimit: bigint;
57
+ feesPerGas: FeesPerGas;
58
+ /**
59
+ * Fees per gas used for each attempt (initial send followed by each speed-up), in order. Always set on
60
+ * newly sent txs; optional because states restored from the state store predate the field.
61
+ * In-memory only — not persisted by the state store.
62
+ */
63
+ feesPerGasHistory?: FeesPerGas[];
64
+ txConfigOverrides: L1TxConfig;
65
+ request: L1TxRequest;
66
+ status: TxUtilsState;
67
+ nonce: number;
68
+ sentAtL1Ts: Date;
69
+ lastSentAtL1Ts: Date;
70
+ receipt?: TransactionReceipt;
71
+ blobInputs: L1BlobInputs | undefined;
72
+ };
73
+
74
+ export type SigningCallback = (
75
+ transaction: TransactionSerializable,
76
+ signingAddress: EthAddress,
77
+ ) => Promise<ViemTransactionSignature>;
78
+
79
+ export class UnknownMinedTxError extends Error {
80
+ constructor(nonce: number, account: string) {
81
+ super(`Nonce ${nonce} from account ${account} is MINED but not by one of our expected transactions`);
82
+ this.name = 'UnknownMinedTxError';
83
+ }
84
+ }
85
+
86
+ export class DroppedTransactionError extends Error {
87
+ constructor(nonce: number, account: string) {
88
+ super(`Transaction with nonce ${nonce} from account ${account} was dropped from the mempool`);
89
+ this.name = 'DroppedTransactionError';
90
+ }
91
+ }
92
+
93
+ /** Snapshot of what a timed-out L1 tx tried to pay, taken when the timeout is raised. */
94
+ export type TimedOutTxState = {
95
+ /** Fees per gas used across the initial send and each speed-up, in order (undefined only for restored states). */
96
+ feesPerGasHistory?: FeesPerGas[];
97
+ /** The last fees per gas the tx was sent with before timing out. */
98
+ finalFeesPerGas: FeesPerGas;
99
+ /** Number of send attempts (initial + speed-ups). */
100
+ attempts: number;
101
+ nonce: number;
102
+ gasLimit: bigint;
103
+ };
104
+
105
+ /**
106
+ * Thrown by sendAndMonitorTransaction when a tx times out. Subclasses TimeoutError so existing
107
+ * `instanceof TimeoutError` checks keep working, while carrying the fees-per-gas ladder for diagnostics.
108
+ */
109
+ export class L1TxTimeoutError extends TimeoutError {
110
+ constructor(
111
+ message: string,
112
+ public readonly txState: TimedOutTxState,
113
+ ) {
114
+ super(message);
115
+ }
116
+ }
@@ -0,0 +1,15 @@
1
+ import { compactArray } from '@aztec-labs/foundation/collection';
2
+ import type { ContractFunctionExecutionError } from 'viem';
3
+
4
+ export function tryGetCustomErrorNameContractFunction(err: ContractFunctionExecutionError) {
5
+ return compactArray([err.shortMessage, ...(err.metaMessages ?? []).slice(0, 2).map(s => s.trim())]).join(' ');
6
+ }
7
+
8
+ /*
9
+ * Returns cost of calldata usage in Ethereum.
10
+ * @param data - Calldata.
11
+ * @returns 4 for each zero byte, 16 for each nonzero.
12
+ */
13
+ export function getCalldataGasUsage(data: Uint8Array) {
14
+ return data.filter(byte => byte === 0).length * 4 + data.filter(byte => byte !== 0).length * 16;
15
+ }
@@ -0,0 +1,6 @@
1
+ import type { Buffer32 } from '@aztec-labs/foundation/buffer';
2
+
3
+ export type L1BlockId = {
4
+ l1BlockNumber: bigint;
5
+ l1BlockHash: Buffer32;
6
+ };
@@ -0,0 +1,239 @@
1
+ import { pick } from '@aztec-labs/foundation/collection';
2
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec-labs/foundation/log';
3
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
4
+
5
+ import { Multicall3 } from './contracts/multicall.js';
6
+ import { L1TxUtils, TxUtilsState } from './l1_tx_utils/index.js';
7
+
8
+ // Defines the order in which we prioritise publishers based on their state (first is better)
9
+ const sortOrder = [
10
+ // Always prefer sending from idle publishers
11
+ TxUtilsState.IDLE,
12
+ // Then from publishers that have sent a tx and it got mined
13
+ TxUtilsState.MINED,
14
+ // Then from publishers that have sent a tx but it's in-flight
15
+ TxUtilsState.SPEED_UP,
16
+ TxUtilsState.SENT,
17
+ // We leave cancelled and not-mined states for last, since these represent failures to mines and could be problematic
18
+ TxUtilsState.CANCELLED,
19
+ TxUtilsState.NOT_MINED,
20
+ ];
21
+
22
+ // Which states represent a busy publisher that we should avoid if possible
23
+ const busyStates: TxUtilsState[] = [
24
+ TxUtilsState.SENT,
25
+ TxUtilsState.SPEED_UP,
26
+ TxUtilsState.CANCELLED,
27
+ TxUtilsState.NOT_MINED,
28
+ ];
29
+
30
+ export type PublisherFilter<UtilsType extends L1TxUtils> = (utils: UtilsType) => boolean;
31
+
32
+ /** Config accepted by PublisherManager. */
33
+ type PublisherManagerConfig = {
34
+ publisherAllowInvalidStates?: boolean;
35
+ publisherFundingThreshold?: bigint;
36
+ publisherFundingAmount?: bigint;
37
+ };
38
+
39
+ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
40
+ private log: Logger;
41
+ private config: PublisherManagerConfig;
42
+ private static readonly FUNDING_CHECK_INTERVAL_MS = 2 * 60 * 1000;
43
+ protected funder?: UtilsType;
44
+ protected readonly fundingPromise?: RunningPromise;
45
+ private started = false;
46
+
47
+ constructor(
48
+ protected publishers: UtilsType[],
49
+ config: PublisherManagerConfig,
50
+ opts?: { bindings?: LoggerBindings; funder?: UtilsType },
51
+ ) {
52
+ this.funder = opts?.funder;
53
+ this.log = createLogger('publisher:manager', opts?.bindings);
54
+ this.log.info(`PublisherManager initialized with ${publishers.length} publishers.`);
55
+ this.publishers = publishers;
56
+ this.config = pick(config, 'publisherAllowInvalidStates', 'publisherFundingThreshold', 'publisherFundingAmount');
57
+
58
+ const hasThreshold = this.config.publisherFundingThreshold !== undefined;
59
+ const hasAmount = this.config.publisherFundingAmount !== undefined;
60
+ if (hasThreshold !== hasAmount) {
61
+ this.log.warn(`Incomplete funding config: both publisherFundingThreshold and publisherFundingAmount must be set`);
62
+ }
63
+
64
+ if (this.funder) {
65
+ const funderAddress = this.funder.getSenderAddress();
66
+ if (publishers.some(p => p.getSenderAddress().equals(funderAddress))) {
67
+ this.log.error(`Funding account ${funderAddress} is also a publisher, disabling funding to avoid self-funding`);
68
+ this.funder = undefined;
69
+ }
70
+ }
71
+
72
+ if (this.funder && hasThreshold && hasAmount) {
73
+ this.fundingPromise = new RunningPromise(
74
+ () => this.triggerFundingIfNeeded(),
75
+ this.log,
76
+ PublisherManager.FUNDING_CHECK_INTERVAL_MS,
77
+ );
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Clears any interrupted flag left by a previous {@link stop} so publishing works again after a restart,
83
+ * loads the state of all publishers and the funder, and starts periodic funding checks. Idempotent: a
84
+ * start while already started is a no-op, so it never re-runs `loadStateAndResumeMonitoring` (which
85
+ * would spawn a duplicate background monitor per pending nonce). Lifecycle calls are expected to be
86
+ * serialized by the caller.
87
+ */
88
+ public async start(): Promise<void> {
89
+ if (this.started) {
90
+ this.log.debug('PublisherManager already started, ignoring start');
91
+ return;
92
+ }
93
+
94
+ // Clear the interrupted flag set by a previous stop() so a restarted manager can publish again.
95
+ // On a first start this is a no-op (the flag is already clear).
96
+ this.publishers.forEach(pub => pub.restart());
97
+ this.funder?.restart();
98
+
99
+ await Promise.all([
100
+ ...this.publishers.map(pub => pub.loadStateAndResumeMonitoring()),
101
+ this.funder?.loadStateAndResumeMonitoring(),
102
+ ]);
103
+
104
+ this.fundingPromise?.start();
105
+ // Marked started only once fully up, so a start that failed to load state can be retried.
106
+ this.started = true;
107
+ }
108
+
109
+ /**
110
+ * Stops the funding loop, interrupts all publishers so no further L1 txs are sent, and waits (bounded)
111
+ * for their in-flight tx monitor loops to wind down. Idempotent, and the manager may be restarted
112
+ * afterwards via {@link start}, which clears the interrupted flag.
113
+ */
114
+ public async stop(): Promise<void> {
115
+ this.started = false;
116
+ await this.fundingPromise?.stop();
117
+ this.publishers.forEach(pub => pub.interrupt());
118
+ this.funder?.interrupt();
119
+ // Wait for in-flight tx monitor loops to observe the interrupt, so no L1 requests are still
120
+ // being issued after shutdown (e.g. against an anvil instance a test is about to tear down).
121
+ await Promise.all([
122
+ ...this.publishers.map(pub => pub.waitMonitoringStopped()),
123
+ this.funder?.waitMonitoringStopped(),
124
+ ]);
125
+ }
126
+
127
+ // Finds and prioritises available publishers based on
128
+ // 1. Validity as per the provided filter function
129
+ // 2. Validity based on the state the publisher is in
130
+ // 3. Priority based on state as defined by sortOrder
131
+ // 4. Then priority based on highest balance
132
+ // 5. Then priority based on least recently used
133
+ public async getAvailablePublisher(filter: PublisherFilter<UtilsType> = () => true): Promise<UtilsType> {
134
+ this.log.debug(`Getting available publisher`, {
135
+ publishers: this.publishers.map(p => ({
136
+ address: p.getSenderAddress(),
137
+ state: p.state,
138
+ lastMined: p.lastMinedAtBlockNumber,
139
+ })),
140
+ });
141
+
142
+ // Extract the valid publishers
143
+ let validPublishers = this.publishers.filter((pub: UtilsType) => !busyStates.includes(pub.state) && filter(pub));
144
+
145
+ // If none found but we allow invalid (busy) states, try again including them
146
+ if (validPublishers.length === 0 && this.config.publisherAllowInvalidStates) {
147
+ this.log.warn(`No valid publishers found. Trying again including invalid states.`);
148
+ validPublishers = this.publishers.filter(pub => filter(pub));
149
+ }
150
+
151
+ // Error if none found
152
+ if (validPublishers.length === 0) {
153
+ throw new Error(`Failed to find an available publisher.`);
154
+ }
155
+
156
+ // Get the balances
157
+ const publishersWithBalance = await Promise.all(
158
+ validPublishers.map(async pub => {
159
+ return { balance: await pub.getSenderBalance(), publisher: pub };
160
+ }),
161
+ );
162
+
163
+ // Discount unfunded publishers: a publisher with no ETH cannot send a tx, so it must never win
164
+ // selection regardless of how favourable its state or last-used time is. Fall back to the full
165
+ // set only if every candidate is unfunded, so behaviour is no worse than before.
166
+ let fundedPublishers = publishersWithBalance.filter(p => p.balance > 0n);
167
+ if (fundedPublishers.length === 0) {
168
+ this.log.warn(`All candidate publishers have zero balance; selecting from unfunded publishers.`);
169
+ fundedPublishers = publishersWithBalance;
170
+ }
171
+
172
+ // Sort based on state, then balance, then time since last use
173
+ const sortedPublishers = fundedPublishers.sort((a, b) => {
174
+ const stateComparison = sortOrder.indexOf(a.publisher.state) - sortOrder.indexOf(b.publisher.state);
175
+ if (stateComparison !== 0) {
176
+ return stateComparison;
177
+ }
178
+ const balanceComparison = Number(b.balance - a.balance);
179
+ if (balanceComparison !== 0) {
180
+ return balanceComparison;
181
+ }
182
+ const lastUsedComparison = Number(
183
+ (a.publisher.lastMinedAtBlockNumber ?? 0n) - (b.publisher.lastMinedAtBlockNumber ?? 0n),
184
+ );
185
+ return lastUsedComparison;
186
+ });
187
+
188
+ return sortedPublishers[0].publisher;
189
+ }
190
+
191
+ /** Check all publisher balances and fund those below threshold. */
192
+ private async triggerFundingIfNeeded(): Promise<void> {
193
+ const { funder, config } = this;
194
+ if (!funder || config.publisherFundingThreshold === undefined || config.publisherFundingAmount === undefined) {
195
+ return;
196
+ }
197
+
198
+ const allBalances = await Promise.all(
199
+ this.publishers.map(async pub => ({ balance: await pub.getSenderBalance(), publisher: pub })),
200
+ );
201
+ const lowBalance = allBalances.filter(p => p.balance < config.publisherFundingThreshold!);
202
+ if (lowBalance.length === 0) {
203
+ return;
204
+ }
205
+
206
+ const fundingAmount = config.publisherFundingAmount!;
207
+ const funderBalance = await funder.getSenderBalance();
208
+
209
+ if (funderBalance < 10n * fundingAmount) {
210
+ this.log.warn(`Funding account balance is low`, { funderBalance, threshold: 10n * fundingAmount });
211
+ }
212
+ const affordableCount = Number(funderBalance / fundingAmount);
213
+ if (affordableCount === 0) {
214
+ this.log.error(`Funding account balance too low to fund any publisher`, { funderBalance, fundingAmount });
215
+ return;
216
+ }
217
+ if (affordableCount < lowBalance.length) {
218
+ this.log.warn(`Funder can only afford ${affordableCount}/${lowBalance.length} publishers`, {
219
+ funderBalance,
220
+ fundingAmount,
221
+ });
222
+ }
223
+
224
+ const toFund = lowBalance.slice(0, affordableCount).map(p => p.publisher);
225
+ await this.fundPublishers(toFund);
226
+ }
227
+
228
+ /** Fund publishers via a single Multicall3 aggregate3Value transaction. */
229
+ private async fundPublishers(publishers: UtilsType[]): Promise<void> {
230
+ const fundingAmount = this.config.publisherFundingAmount!;
231
+ const calls = publishers.map(pub => ({
232
+ to: pub.getSenderAddress().toString(),
233
+ value: fundingAmount,
234
+ }));
235
+
236
+ await Multicall3.forwardValue(calls, this.funder!, this.log);
237
+ this.log.info(`Funded ${publishers.length} publishers`);
238
+ }
239
+ }