@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,223 @@
1
+ import { omit } from '@aztec-labs/foundation/collection';
2
+ import { createLogger } from '@aztec-labs/foundation/log';
3
+ import { retryUntil } from '@aztec-labs/foundation/retry';
4
+ import { inspect } from 'util';
5
+ import { keccak256, parseTransaction, publicActions, recoverTransactionAddress, serializeTransaction, walletActions } from 'viem';
6
+ const MAX_WAIT_TIME_SECONDS = 180;
7
+ export function waitUntilBlock(client, blockNumber, logger, timeout) {
8
+ const publicClient = 'getBlockNumber' in client && typeof client.getBlockNumber === 'function' ? client : client.extend(publicActions);
9
+ return retryUntil(async ()=>{
10
+ const currentBlockNumber = await publicClient.getBlockNumber({
11
+ cacheTime: 0
12
+ });
13
+ logger?.debug(`Block number is ${currentBlockNumber} (waiting until ${blockNumber})`);
14
+ return currentBlockNumber >= BigInt(blockNumber);
15
+ }, `Wait until L1 block ${blockNumber}`, timeout ?? MAX_WAIT_TIME_SECONDS, 0.1);
16
+ }
17
+ export function waitUntilL1Timestamp(client, timestamp, logger, timeout) {
18
+ const publicClient = 'getBlockNumber' in client && typeof client.getBlockNumber === 'function' ? client : client.extend(publicActions);
19
+ let lastBlock = undefined;
20
+ return retryUntil(async ()=>{
21
+ const currentBlockNumber = await publicClient.getBlockNumber({
22
+ cacheTime: 0
23
+ });
24
+ if (currentBlockNumber === lastBlock) {
25
+ return false;
26
+ }
27
+ lastBlock = currentBlockNumber;
28
+ const currentBlock = await publicClient.getBlock({
29
+ includeTransactions: false,
30
+ blockNumber: currentBlockNumber
31
+ });
32
+ const currentTs = currentBlock.timestamp;
33
+ logger?.debug(`Block timstamp is ${currentTs} (waiting until ${timestamp})`);
34
+ return currentTs >= BigInt(timestamp);
35
+ }, `Wait until L1 timestamp ${timestamp}`, timeout ?? MAX_WAIT_TIME_SECONDS, 0.1);
36
+ }
37
+ /** Manages tx delaying for testing, intercepting sendRawTransaction calls to delay or cancel them. */ export class Delayer {
38
+ dateProvider;
39
+ logger;
40
+ maxInclusionTimeIntoSlot;
41
+ ethereumSlotDuration;
42
+ nextWait;
43
+ sentTxHashes;
44
+ cancelledTxs;
45
+ constructor(dateProvider, opts, bindings){
46
+ this.dateProvider = dateProvider;
47
+ this.maxInclusionTimeIntoSlot = undefined;
48
+ this.nextWait = undefined;
49
+ this.sentTxHashes = [];
50
+ this.cancelledTxs = [];
51
+ this.ethereumSlotDuration = BigInt(opts.ethereumSlotDuration);
52
+ this.logger = createLogger('ethereum:tx_delayer', bindings);
53
+ }
54
+ /** Returns the logger instance used by this delayer. */ getLogger() {
55
+ return this.logger;
56
+ }
57
+ /** Returns the hashes of all effectively sent txs. */ getSentTxHashes() {
58
+ return this.sentTxHashes;
59
+ }
60
+ /** Returns the raw hex for all cancelled txs. */ getCancelledTxs() {
61
+ return this.cancelledTxs;
62
+ }
63
+ /** Delays the next tx to be sent so it lands on the given L1 block number. */ pauseNextTxUntilBlock(l1BlockNumber, timeoutSeconds) {
64
+ this.nextWait = {
65
+ l1BlockNumber: BigInt(l1BlockNumber),
66
+ timeoutSeconds
67
+ };
68
+ }
69
+ /** Delays the next tx to be sent so it lands on the given timestamp. */ pauseNextTxUntilTimestamp(l1Timestamp, timeoutSeconds) {
70
+ this.nextWait = {
71
+ l1Timestamp: BigInt(l1Timestamp),
72
+ timeoutSeconds
73
+ };
74
+ }
75
+ /** Delays the next tx to be sent indefinitely. */ cancelNextTx() {
76
+ this.nextWait = {
77
+ indefinitely: true
78
+ };
79
+ }
80
+ /**
81
+ * Sets max inclusion time into slot. If more than this many seconds have passed
82
+ * since the last L1 block was mined, then any tx will not be mined in the current
83
+ * L1 slot but will be deferred for the next one.
84
+ */ setMaxInclusionTimeIntoSlot(seconds) {
85
+ this.maxInclusionTimeIntoSlot = seconds;
86
+ }
87
+ }
88
+ /**
89
+ * Creates a new Delayer instance. Exposed so callers can create a single shared delayer
90
+ * and pass it to multiple `wrapClientWithDelayer` calls.
91
+ */ export function createDelayer(dateProvider, opts, bindings) {
92
+ return new Delayer(dateProvider, opts, bindings);
93
+ }
94
+ /** Tries to recover the sender address from a serialized signed transaction. */ async function tryRecoverSender(serializedTransaction) {
95
+ try {
96
+ return await recoverTransactionAddress({
97
+ serializedTransaction: serializedTransaction
98
+ });
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ /**
104
+ * Wraps a viem client with tx delaying logic. Returns the wrapped client.
105
+ * The delayer intercepts sendRawTransaction calls and delays them based on the delayer's state.
106
+ */ export function wrapClientWithDelayer(client, delayer) {
107
+ const logger = delayer.getLogger();
108
+ // Cast to ExtendedViemWalletClient for the extend chain since it has sendRawTransaction.
109
+ // The sendRawTransaction override is applied to all clients regardless of type.
110
+ const withRawTx = client// Tweak sendRawTransaction so it uses the delay defined in the delayer.
111
+ // Note that this will only work with local accounts (ie accounts for which we have the private key).
112
+ // Transactions signed by the node will not be delayed since they use sendTransaction directly,
113
+ // but we do not use them in our codebase at all.
114
+ .extend((client)=>({
115
+ async sendRawTransaction (...args) {
116
+ let wait;
117
+ let txHash;
118
+ const { serializedTransaction } = args[0];
119
+ const publicClient = client;
120
+ const sender = await tryRecoverSender(serializedTransaction);
121
+ if (delayer.nextWait !== undefined) {
122
+ // Check if we have been instructed to delay the next tx.
123
+ const waitUntil = delayer.nextWait;
124
+ delayer.nextWait = undefined;
125
+ // Compute the tx hash manually so we emulate sendRawTransaction response
126
+ txHash = computeTxHash(serializedTransaction);
127
+ // Cancel tx outright if instructed
128
+ if ('indefinitely' in waitUntil && waitUntil.indefinitely) {
129
+ logger.info(`Cancelling tx ${txHash}`, {
130
+ sender
131
+ });
132
+ delayer.cancelledTxs.push(serializedTransaction);
133
+ return Promise.resolve(txHash);
134
+ }
135
+ // Or wait until the desired block number or timestamp
136
+ wait = 'l1BlockNumber' in waitUntil ? waitUntilBlock(publicClient, waitUntil.l1BlockNumber - 1n, logger, waitUntil.timeoutSeconds) : 'l1Timestamp' in waitUntil ? waitUntilL1Timestamp(publicClient, waitUntil.l1Timestamp - delayer.ethereumSlotDuration, logger, waitUntil.timeoutSeconds) : undefined;
137
+ logger.info(`Delaying tx ${txHash} until ${inspect(waitUntil)}`, {
138
+ sender,
139
+ argsLen: args.length,
140
+ ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars')
141
+ });
142
+ } else if (delayer.maxInclusionTimeIntoSlot !== undefined) {
143
+ // Check if we need to delay txs sent too close to the end of the slot.
144
+ const currentBlock = await publicClient.getBlock({
145
+ includeTransactions: false
146
+ });
147
+ const { timestamp: lastBlockTimestamp, number } = currentBlock;
148
+ const now = delayer.dateProvider.now();
149
+ txHash = computeTxHash(serializedTransaction);
150
+ const logData = {
151
+ sender,
152
+ ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
153
+ lastBlockTimestamp,
154
+ now,
155
+ maxInclusionTimeIntoSlot: delayer.maxInclusionTimeIntoSlot
156
+ };
157
+ if (now / 1000 - Number(lastBlockTimestamp) > delayer.maxInclusionTimeIntoSlot) {
158
+ // If the last block was mined more than `maxInclusionTimeIntoSlot` seconds ago, then we cannot include
159
+ // any txs in the current slot, so we delay the tx until the next slot.
160
+ logger.info(`Delaying inclusion of tx ${txHash} until the next slot since it was sent too late`, logData);
161
+ wait = waitUntilBlock(publicClient, number + 1n, logger);
162
+ } else {
163
+ logger.debug(`Immediately sending tx ${txHash} as it was received early enough in the slot`, logData);
164
+ }
165
+ }
166
+ if (wait !== undefined) {
167
+ // Do not await here so we can return the tx hash immediately as if it had been sent on the spot.
168
+ // Instead, delay it so it lands on the desired block number or timestamp, assuming anvil will
169
+ // mine it immediately.
170
+ void wait.then(async ()=>{
171
+ const clientTxHash = await client.sendRawTransaction(...args);
172
+ if (clientTxHash !== txHash) {
173
+ logger.error(`Tx hash returned by the client does not match computed one`, {
174
+ clientTxHash,
175
+ computedTxHash: txHash
176
+ });
177
+ }
178
+ logger.info(`Sent previously delayed tx ${clientTxHash}`, {
179
+ sender
180
+ });
181
+ delayer.sentTxHashes.push(clientTxHash);
182
+ }).catch((err)=>logger.error(`Error sending tx after delay`, err));
183
+ return Promise.resolve(txHash);
184
+ } else {
185
+ const txHash = await client.sendRawTransaction(...args);
186
+ logger.debug(`Sent tx immediately ${txHash}`, {
187
+ sender
188
+ });
189
+ delayer.sentTxHashes.push(txHash);
190
+ return txHash;
191
+ }
192
+ }
193
+ }));
194
+ // Only re-bind wallet actions (sendTransaction, writeContract, deployContract) for wallet clients.
195
+ // This is needed for tests that use wallet actions directly rather than sendRawTransaction.
196
+ const isWalletClient = 'account' in client && client.account !== undefined;
197
+ const extended = isWalletClient ? withRawTx// Re-extend with sendTransaction so it uses the modified sendRawTransaction.
198
+ .extend((client)=>({
199
+ sendTransaction: walletActions(client).sendTransaction
200
+ }))// And with the actions that depend on the modified sendTransaction
201
+ .extend((client)=>({
202
+ writeContract: walletActions(client).writeContract,
203
+ deployContract: walletActions(client).deployContract
204
+ })) : withRawTx;
205
+ return extended;
206
+ }
207
+ /**
208
+ * Compute the tx hash given the serialized tx. Note that if this is a blob tx, we need to
209
+ * exclude the blobs, commitments, and proofs from the hash.
210
+ */ function computeTxHash(serializedTransaction) {
211
+ if (serializedTransaction.startsWith('0x03')) {
212
+ const parsed = parseTransaction(serializedTransaction);
213
+ if (parsed.blobs || parsed.sidecars) {
214
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
215
+ const { blobs, sidecars, ...rest } = parsed;
216
+ return keccak256(serializeTransaction({
217
+ type: 'eip4844',
218
+ ...rest
219
+ }));
220
+ }
221
+ }
222
+ return keccak256(serializedTransaction);
223
+ }
@@ -0,0 +1,93 @@
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
+ import type { L1TxUtilsConfig } from './config.js';
7
+ export interface L1TxRequest {
8
+ to: Address | null;
9
+ data?: Hex;
10
+ value?: bigint;
11
+ abi?: Abi;
12
+ }
13
+ export type L1TxConfig = Partial<L1TxUtilsConfig> & {
14
+ gasLimit?: bigint;
15
+ txTimeoutAt?: Date;
16
+ };
17
+ export interface L1BlobInputs {
18
+ blobs: Uint8Array[];
19
+ kzg: BlobKzgInstance;
20
+ maxFeePerBlobGas?: bigint;
21
+ }
22
+ export interface FeesPerGas {
23
+ maxFeePerGas: bigint;
24
+ maxPriorityFeePerGas: bigint;
25
+ maxFeePerBlobGas?: bigint;
26
+ }
27
+ export type TransactionStats = {
28
+ /** Address of the sender. */
29
+ sender: string;
30
+ /** Hash of the transaction. */
31
+ transactionHash: string;
32
+ /** Size in bytes of the tx calldata */
33
+ calldataSize: number;
34
+ /** Gas required to pay for the calldata inclusion (depends on size and number of zeros) */
35
+ calldataGas: number;
36
+ };
37
+ export declare enum TxUtilsState {
38
+ IDLE = 0,
39
+ SENT = 1,
40
+ SPEED_UP = 2,
41
+ CANCELLED = 3,
42
+ NOT_MINED = 4,
43
+ MINED = 5
44
+ }
45
+ export declare const TerminalTxUtilsState: TxUtilsState[];
46
+ export type L1TxState = {
47
+ id: number;
48
+ txHashes: Hex[];
49
+ cancelTxHashes: Hex[];
50
+ gasLimit: bigint;
51
+ feesPerGas: FeesPerGas;
52
+ /**
53
+ * Fees per gas used for each attempt (initial send followed by each speed-up), in order. Always set on
54
+ * newly sent txs; optional because states restored from the state store predate the field.
55
+ * In-memory only — not persisted by the state store.
56
+ */
57
+ feesPerGasHistory?: FeesPerGas[];
58
+ txConfigOverrides: L1TxConfig;
59
+ request: L1TxRequest;
60
+ status: TxUtilsState;
61
+ nonce: number;
62
+ sentAtL1Ts: Date;
63
+ lastSentAtL1Ts: Date;
64
+ receipt?: TransactionReceipt;
65
+ blobInputs: L1BlobInputs | undefined;
66
+ };
67
+ export type SigningCallback = (transaction: TransactionSerializable, signingAddress: EthAddress) => Promise<ViemTransactionSignature>;
68
+ export declare class UnknownMinedTxError extends Error {
69
+ constructor(nonce: number, account: string);
70
+ }
71
+ export declare class DroppedTransactionError extends Error {
72
+ constructor(nonce: number, account: string);
73
+ }
74
+ /** Snapshot of what a timed-out L1 tx tried to pay, taken when the timeout is raised. */
75
+ export type TimedOutTxState = {
76
+ /** Fees per gas used across the initial send and each speed-up, in order (undefined only for restored states). */
77
+ feesPerGasHistory?: FeesPerGas[];
78
+ /** The last fees per gas the tx was sent with before timing out. */
79
+ finalFeesPerGas: FeesPerGas;
80
+ /** Number of send attempts (initial + speed-ups). */
81
+ attempts: number;
82
+ nonce: number;
83
+ gasLimit: bigint;
84
+ };
85
+ /**
86
+ * Thrown by sendAndMonitorTransaction when a tx times out. Subclasses TimeoutError so existing
87
+ * `instanceof TimeoutError` checks keep working, while carrying the fees-per-gas ladder for diagnostics.
88
+ */
89
+ export declare class L1TxTimeoutError extends TimeoutError {
90
+ readonly txState: TimedOutTxState;
91
+ constructor(message: string, txState: TimedOutTxState);
92
+ }
93
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9sMV90eF91dGlscy90eXBlcy50cyJdLCJuYW1lcy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a,gBAAiB,SAAQ,YAAY;aAG9B,OAAO,EAAE,eAAe;IAF1C,YACE,OAAO,EAAE,MAAM,EACC,OAAO,EAAE,eAAe,EAGzC;CACF"}
@@ -0,0 +1,36 @@
1
+ import { TimeoutError } from '@aztec-labs/foundation/error';
2
+ export var TxUtilsState = /*#__PURE__*/ function(TxUtilsState) {
3
+ TxUtilsState[TxUtilsState["IDLE"] = 0] = "IDLE";
4
+ TxUtilsState[TxUtilsState["SENT"] = 1] = "SENT";
5
+ TxUtilsState[TxUtilsState["SPEED_UP"] = 2] = "SPEED_UP";
6
+ TxUtilsState[TxUtilsState["CANCELLED"] = 3] = "CANCELLED";
7
+ TxUtilsState[TxUtilsState["NOT_MINED"] = 4] = "NOT_MINED";
8
+ TxUtilsState[TxUtilsState["MINED"] = 5] = "MINED";
9
+ return TxUtilsState;
10
+ }({});
11
+ export const TerminalTxUtilsState = [
12
+ 0,
13
+ 5,
14
+ 4
15
+ ];
16
+ export class UnknownMinedTxError extends Error {
17
+ constructor(nonce, account){
18
+ super(`Nonce ${nonce} from account ${account} is MINED but not by one of our expected transactions`);
19
+ this.name = 'UnknownMinedTxError';
20
+ }
21
+ }
22
+ export class DroppedTransactionError extends Error {
23
+ constructor(nonce, account){
24
+ super(`Transaction with nonce ${nonce} from account ${account} was dropped from the mempool`);
25
+ this.name = 'DroppedTransactionError';
26
+ }
27
+ }
28
+ /**
29
+ * Thrown by sendAndMonitorTransaction when a tx times out. Subclasses TimeoutError so existing
30
+ * `instanceof TimeoutError` checks keep working, while carrying the fees-per-gas ladder for diagnostics.
31
+ */ export class L1TxTimeoutError extends TimeoutError {
32
+ txState;
33
+ constructor(message, txState){
34
+ super(message), this.txState = txState;
35
+ }
36
+ }
@@ -0,0 +1,4 @@
1
+ import type { ContractFunctionExecutionError } from 'viem';
2
+ export declare function tryGetCustomErrorNameContractFunction(err: ContractFunctionExecutionError): string;
3
+ export declare function getCalldataGasUsage(data: Uint8Array): number;
4
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9sMV90eF91dGlscy91dGlscy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEtBQUssRUFBRSw4QkFBOEIsRUFBRSxNQUFNLE1BQU0sQ0FBQztBQUUzRCx3QkFBZ0IscUNBQXFDLENBQUMsR0FBRyxFQUFFLDhCQUE4QixVQUV4RjtBQU9ELHdCQUFnQixtQkFBbUIsQ0FBQyxJQUFJLEVBQUUsVUFBVSxVQUVuRCJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/l1_tx_utils/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,MAAM,CAAC;AAE3D,wBAAgB,qCAAqC,CAAC,GAAG,EAAE,8BAA8B,UAExF;AAOD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,UAAU,UAEnD"}
@@ -0,0 +1,14 @@
1
+ import { compactArray } from '@aztec-labs/foundation/collection';
2
+ export function tryGetCustomErrorNameContractFunction(err) {
3
+ return compactArray([
4
+ err.shortMessage,
5
+ ...(err.metaMessages ?? []).slice(0, 2).map((s)=>s.trim())
6
+ ]).join(' ');
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
+ */ export function getCalldataGasUsage(data) {
13
+ return data.filter((byte)=>byte === 0).length * 4 + data.filter((byte)=>byte !== 0).length * 16;
14
+ }
@@ -0,0 +1,6 @@
1
+ import type { Buffer32 } from '@aztec-labs/foundation/buffer';
2
+ export type L1BlockId = {
3
+ l1BlockNumber: bigint;
4
+ l1BlockHash: Buffer32;
5
+ };
6
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibDFfdHlwZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9sMV90eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxRQUFRLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUU5RCxNQUFNLE1BQU0sU0FBUyxHQUFHO0lBQ3RCLGFBQWEsRUFBRSxNQUFNLENBQUM7SUFDdEIsV0FBVyxFQUFFLFFBQVEsQ0FBQztDQUN2QixDQUFDIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"l1_types.d.ts","sourceRoot":"","sources":["../src/l1_types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAE9D,MAAM,MAAM,SAAS,GAAG;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,QAAQ,CAAC;CACvB,CAAC"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,42 @@
1
+ import { type LoggerBindings } from '@aztec-labs/foundation/log';
2
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
3
+ import { L1TxUtils } from './l1_tx_utils/index.js';
4
+ export type PublisherFilter<UtilsType extends L1TxUtils> = (utils: UtilsType) => boolean;
5
+ /** Config accepted by PublisherManager. */
6
+ type PublisherManagerConfig = {
7
+ publisherAllowInvalidStates?: boolean;
8
+ publisherFundingThreshold?: bigint;
9
+ publisherFundingAmount?: bigint;
10
+ };
11
+ export declare class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
12
+ protected publishers: UtilsType[];
13
+ private log;
14
+ private config;
15
+ private static readonly FUNDING_CHECK_INTERVAL_MS;
16
+ protected funder?: UtilsType;
17
+ protected readonly fundingPromise?: RunningPromise;
18
+ private started;
19
+ constructor(publishers: UtilsType[], config: PublisherManagerConfig, opts?: {
20
+ bindings?: LoggerBindings;
21
+ funder?: UtilsType;
22
+ });
23
+ /**
24
+ * Clears any interrupted flag left by a previous {@link stop} so publishing works again after a restart,
25
+ * loads the state of all publishers and the funder, and starts periodic funding checks. Idempotent: a
26
+ * start while already started is a no-op, so it never re-runs `loadStateAndResumeMonitoring` (which
27
+ * would spawn a duplicate background monitor per pending nonce). Lifecycle calls are expected to be
28
+ * serialized by the caller.
29
+ */
30
+ start(): Promise<void>;
31
+ /**
32
+ * Stops the funding loop, interrupts all publishers so no further L1 txs are sent, and waits (bounded)
33
+ * for their in-flight tx monitor loops to wind down. Idempotent, and the manager may be restarted
34
+ * afterwards via {@link start}, which clears the interrupted flag.
35
+ */
36
+ stop(): Promise<void>;
37
+ getAvailablePublisher(filter?: PublisherFilter<UtilsType>): Promise<UtilsType>;
38
+ private triggerFundingIfNeeded;
39
+ private fundPublishers;
40
+ }
41
+ export {};
42
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGlzaGVyX21hbmFnZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9wdWJsaXNoZXJfbWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEVBQWUsS0FBSyxjQUFjLEVBQWdCLE1BQU0sNEJBQTRCLENBQUM7QUFDNUYsT0FBTyxFQUFFLGNBQWMsRUFBRSxNQUFNLHdDQUF3QyxDQUFDO0FBR3hFLE9BQU8sRUFBRSxTQUFTLEVBQWdCLE1BQU0sd0JBQXdCLENBQUM7QUF3QmpFLE1BQU0sTUFBTSxlQUFlLENBQUMsU0FBUyxTQUFTLFNBQVMsSUFBSSxDQUFDLEtBQUssRUFBRSxTQUFTLEtBQUssT0FBTyxDQUFDO0FBRXpGLDJDQUEyQztBQUMzQyxLQUFLLHNCQUFzQixHQUFHO0lBQzVCLDJCQUEyQixDQUFDLEVBQUUsT0FBTyxDQUFDO0lBQ3RDLHlCQUF5QixDQUFDLEVBQUUsTU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Ac;CAU7B"}
@@ -0,0 +1,199 @@
1
+ import { pick } from '@aztec-labs/foundation/collection';
2
+ import { createLogger } from '@aztec-labs/foundation/log';
3
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
4
+ import { Multicall3 } from './contracts/multicall.js';
5
+ import { TxUtilsState } from './l1_tx_utils/index.js';
6
+ // Defines the order in which we prioritise publishers based on their state (first is better)
7
+ const sortOrder = [
8
+ // Always prefer sending from idle publishers
9
+ TxUtilsState.IDLE,
10
+ // Then from publishers that have sent a tx and it got mined
11
+ TxUtilsState.MINED,
12
+ // Then from publishers that have sent a tx but it's in-flight
13
+ TxUtilsState.SPEED_UP,
14
+ TxUtilsState.SENT,
15
+ // We leave cancelled and not-mined states for last, since these represent failures to mines and could be problematic
16
+ TxUtilsState.CANCELLED,
17
+ TxUtilsState.NOT_MINED
18
+ ];
19
+ // Which states represent a busy publisher that we should avoid if possible
20
+ const busyStates = [
21
+ TxUtilsState.SENT,
22
+ TxUtilsState.SPEED_UP,
23
+ TxUtilsState.CANCELLED,
24
+ TxUtilsState.NOT_MINED
25
+ ];
26
+ export class PublisherManager {
27
+ publishers;
28
+ log;
29
+ config;
30
+ static FUNDING_CHECK_INTERVAL_MS = 2 * 60 * 1000;
31
+ funder;
32
+ fundingPromise;
33
+ started;
34
+ constructor(publishers, config, opts){
35
+ this.publishers = publishers;
36
+ this.started = false;
37
+ this.funder = opts?.funder;
38
+ this.log = createLogger('publisher:manager', opts?.bindings);
39
+ this.log.info(`PublisherManager initialized with ${publishers.length} publishers.`);
40
+ this.publishers = publishers;
41
+ this.config = pick(config, 'publisherAllowInvalidStates', 'publisherFundingThreshold', 'publisherFundingAmount');
42
+ const hasThreshold = this.config.publisherFundingThreshold !== undefined;
43
+ const hasAmount = this.config.publisherFundingAmount !== undefined;
44
+ if (hasThreshold !== hasAmount) {
45
+ this.log.warn(`Incomplete funding config: both publisherFundingThreshold and publisherFundingAmount must be set`);
46
+ }
47
+ if (this.funder) {
48
+ const funderAddress = this.funder.getSenderAddress();
49
+ if (publishers.some((p)=>p.getSenderAddress().equals(funderAddress))) {
50
+ this.log.error(`Funding account ${funderAddress} is also a publisher, disabling funding to avoid self-funding`);
51
+ this.funder = undefined;
52
+ }
53
+ }
54
+ if (this.funder && hasThreshold && hasAmount) {
55
+ this.fundingPromise = new RunningPromise(()=>this.triggerFundingIfNeeded(), this.log, PublisherManager.FUNDING_CHECK_INTERVAL_MS);
56
+ }
57
+ }
58
+ /**
59
+ * Clears any interrupted flag left by a previous {@link stop} so publishing works again after a restart,
60
+ * loads the state of all publishers and the funder, and starts periodic funding checks. Idempotent: a
61
+ * start while already started is a no-op, so it never re-runs `loadStateAndResumeMonitoring` (which
62
+ * would spawn a duplicate background monitor per pending nonce). Lifecycle calls are expected to be
63
+ * serialized by the caller.
64
+ */ async start() {
65
+ if (this.started) {
66
+ this.log.debug('PublisherManager already started, ignoring start');
67
+ return;
68
+ }
69
+ // Clear the interrupted flag set by a previous stop() so a restarted manager can publish again.
70
+ // On a first start this is a no-op (the flag is already clear).
71
+ this.publishers.forEach((pub)=>pub.restart());
72
+ this.funder?.restart();
73
+ await Promise.all([
74
+ ...this.publishers.map((pub)=>pub.loadStateAndResumeMonitoring()),
75
+ this.funder?.loadStateAndResumeMonitoring()
76
+ ]);
77
+ this.fundingPromise?.start();
78
+ // Marked started only once fully up, so a start that failed to load state can be retried.
79
+ this.started = true;
80
+ }
81
+ /**
82
+ * Stops the funding loop, interrupts all publishers so no further L1 txs are sent, and waits (bounded)
83
+ * for their in-flight tx monitor loops to wind down. Idempotent, and the manager may be restarted
84
+ * afterwards via {@link start}, which clears the interrupted flag.
85
+ */ async stop() {
86
+ this.started = false;
87
+ await this.fundingPromise?.stop();
88
+ this.publishers.forEach((pub)=>pub.interrupt());
89
+ this.funder?.interrupt();
90
+ // Wait for in-flight tx monitor loops to observe the interrupt, so no L1 requests are still
91
+ // being issued after shutdown (e.g. against an anvil instance a test is about to tear down).
92
+ await Promise.all([
93
+ ...this.publishers.map((pub)=>pub.waitMonitoringStopped()),
94
+ this.funder?.waitMonitoringStopped()
95
+ ]);
96
+ }
97
+ // Finds and prioritises available publishers based on
98
+ // 1. Validity as per the provided filter function
99
+ // 2. Validity based on the state the publisher is in
100
+ // 3. Priority based on state as defined by sortOrder
101
+ // 4. Then priority based on highest balance
102
+ // 5. Then priority based on least recently used
103
+ async getAvailablePublisher(filter = ()=>true) {
104
+ this.log.debug(`Getting available publisher`, {
105
+ publishers: this.publishers.map((p)=>({
106
+ address: p.getSenderAddress(),
107
+ state: p.state,
108
+ lastMined: p.lastMinedAtBlockNumber
109
+ }))
110
+ });
111
+ // Extract the valid publishers
112
+ let validPublishers = this.publishers.filter((pub)=>!busyStates.includes(pub.state) && filter(pub));
113
+ // If none found but we allow invalid (busy) states, try again including them
114
+ if (validPublishers.length === 0 && this.config.publisherAllowInvalidStates) {
115
+ this.log.warn(`No valid publishers found. Trying again including invalid states.`);
116
+ validPublishers = this.publishers.filter((pub)=>filter(pub));
117
+ }
118
+ // Error if none found
119
+ if (validPublishers.length === 0) {
120
+ throw new Error(`Failed to find an available publisher.`);
121
+ }
122
+ // Get the balances
123
+ const publishersWithBalance = await Promise.all(validPublishers.map(async (pub)=>{
124
+ return {
125
+ balance: await pub.getSenderBalance(),
126
+ publisher: pub
127
+ };
128
+ }));
129
+ // Discount unfunded publishers: a publisher with no ETH cannot send a tx, so it must never win
130
+ // selection regardless of how favourable its state or last-used time is. Fall back to the full
131
+ // set only if every candidate is unfunded, so behaviour is no worse than before.
132
+ let fundedPublishers = publishersWithBalance.filter((p)=>p.balance > 0n);
133
+ if (fundedPublishers.length === 0) {
134
+ this.log.warn(`All candidate publishers have zero balance; selecting from unfunded publishers.`);
135
+ fundedPublishers = publishersWithBalance;
136
+ }
137
+ // Sort based on state, then balance, then time since last use
138
+ const sortedPublishers = fundedPublishers.sort((a, b)=>{
139
+ const stateComparison = sortOrder.indexOf(a.publisher.state) - sortOrder.indexOf(b.publisher.state);
140
+ if (stateComparison !== 0) {
141
+ return stateComparison;
142
+ }
143
+ const balanceComparison = Number(b.balance - a.balance);
144
+ if (balanceComparison !== 0) {
145
+ return balanceComparison;
146
+ }
147
+ const lastUsedComparison = Number((a.publisher.lastMinedAtBlockNumber ?? 0n) - (b.publisher.lastMinedAtBlockNumber ?? 0n));
148
+ return lastUsedComparison;
149
+ });
150
+ return sortedPublishers[0].publisher;
151
+ }
152
+ /** Check all publisher balances and fund those below threshold. */ async triggerFundingIfNeeded() {
153
+ const { funder, config } = this;
154
+ if (!funder || config.publisherFundingThreshold === undefined || config.publisherFundingAmount === undefined) {
155
+ return;
156
+ }
157
+ const allBalances = await Promise.all(this.publishers.map(async (pub)=>({
158
+ balance: await pub.getSenderBalance(),
159
+ publisher: pub
160
+ })));
161
+ const lowBalance = allBalances.filter((p)=>p.balance < config.publisherFundingThreshold);
162
+ if (lowBalance.length === 0) {
163
+ return;
164
+ }
165
+ const fundingAmount = config.publisherFundingAmount;
166
+ const funderBalance = await funder.getSenderBalance();
167
+ if (funderBalance < 10n * fundingAmount) {
168
+ this.log.warn(`Funding account balance is low`, {
169
+ funderBalance,
170
+ threshold: 10n * fundingAmount
171
+ });
172
+ }
173
+ const affordableCount = Number(funderBalance / fundingAmount);
174
+ if (affordableCount === 0) {
175
+ this.log.error(`Funding account balance too low to fund any publisher`, {
176
+ funderBalance,
177
+ fundingAmount
178
+ });
179
+ return;
180
+ }
181
+ if (affordableCount < lowBalance.length) {
182
+ this.log.warn(`Funder can only afford ${affordableCount}/${lowBalance.length} publishers`, {
183
+ funderBalance,
184
+ fundingAmount
185
+ });
186
+ }
187
+ const toFund = lowBalance.slice(0, affordableCount).map((p)=>p.publisher);
188
+ await this.fundPublishers(toFund);
189
+ }
190
+ /** Fund publishers via a single Multicall3 aggregate3Value transaction. */ async fundPublishers(publishers) {
191
+ const fundingAmount = this.config.publisherFundingAmount;
192
+ const calls = publishers.map((pub)=>({
193
+ to: pub.getSenderAddress().toString(),
194
+ value: fundingAmount
195
+ }));
196
+ await Multicall3.forwardValue(calls, this.funder, this.log);
197
+ this.log.info(`Funded ${publishers.length} publishers`);
198
+ }
199
+ }