@aztec/ethereum 3.0.0-rc.5 → 4.0.0-nightly.20260107

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 (84) hide show
  1. package/dest/client.js +6 -2
  2. package/dest/config.d.ts +4 -1
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +6 -0
  5. package/dest/contracts/empire_base.d.ts +2 -1
  6. package/dest/contracts/empire_base.d.ts.map +1 -1
  7. package/dest/contracts/empire_slashing_proposer.d.ts +2 -1
  8. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  9. package/dest/contracts/empire_slashing_proposer.js +9 -0
  10. package/dest/contracts/governance_proposer.d.ts +2 -1
  11. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  12. package/dest/contracts/governance_proposer.js +391 -8
  13. package/dest/contracts/inbox.d.ts +5 -1
  14. package/dest/contracts/inbox.d.ts.map +1 -1
  15. package/dest/contracts/inbox.js +4 -0
  16. package/dest/contracts/rollup.d.ts +125 -73
  17. package/dest/contracts/rollup.d.ts.map +1 -1
  18. package/dest/contracts/rollup.js +614 -125
  19. package/dest/deploy_aztec_l1_contracts.d.ts +3 -1
  20. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  21. package/dest/deploy_aztec_l1_contracts.js +7 -2
  22. package/dest/l1_artifacts.d.ts +3370 -104
  23. package/dest/l1_artifacts.d.ts.map +1 -1
  24. package/dest/l1_contract_addresses.d.ts +1 -1
  25. package/dest/l1_contract_addresses.d.ts.map +1 -1
  26. package/dest/l1_contract_addresses.js +3 -3
  27. package/dest/l1_tx_utils/constants.d.ts +7 -1
  28. package/dest/l1_tx_utils/constants.d.ts.map +1 -1
  29. package/dest/l1_tx_utils/constants.js +25 -0
  30. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  31. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  32. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  33. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  34. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  35. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  36. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  37. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  38. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  39. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  40. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  41. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  42. package/dest/l1_tx_utils/index.d.ts +3 -1
  43. package/dest/l1_tx_utils/index.d.ts.map +1 -1
  44. package/dest/l1_tx_utils/index.js +2 -0
  45. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +233 -0
  46. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  47. package/dest/l1_tx_utils/l1_fee_analyzer.js +506 -0
  48. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +4 -15
  49. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  50. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +34 -142
  51. package/dest/queries.d.ts +1 -1
  52. package/dest/queries.d.ts.map +1 -1
  53. package/dest/queries.js +8 -3
  54. package/dest/test/chain_monitor.js +1 -2
  55. package/dest/test/eth_cheat_codes.js +3 -1
  56. package/dest/test/rollup_cheat_codes.js +3 -1
  57. package/dest/test/tx_delayer.js +1 -1
  58. package/dest/utils.d.ts +14 -2
  59. package/dest/utils.d.ts.map +1 -1
  60. package/dest/utils.js +18 -0
  61. package/package.json +6 -5
  62. package/src/client.ts +2 -2
  63. package/src/config.ts +8 -0
  64. package/src/contracts/empire_base.ts +1 -1
  65. package/src/contracts/empire_slashing_proposer.ts +6 -1
  66. package/src/contracts/governance_proposer.ts +6 -1
  67. package/src/contracts/inbox.ts +5 -0
  68. package/src/contracts/rollup.ts +252 -84
  69. package/src/deploy_aztec_l1_contracts.ts +12 -2
  70. package/src/l1_contract_addresses.ts +22 -20
  71. package/src/l1_tx_utils/constants.ts +11 -0
  72. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  73. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +163 -0
  74. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +245 -0
  75. package/src/l1_tx_utils/fee-strategies/types.ts +56 -0
  76. package/src/l1_tx_utils/index.ts +2 -0
  77. package/src/l1_tx_utils/l1_fee_analyzer.ts +803 -0
  78. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +46 -184
  79. package/src/queries.ts +8 -2
  80. package/src/test/chain_monitor.ts +1 -1
  81. package/src/test/eth_cheat_codes.ts +1 -1
  82. package/src/test/rollup_cheat_codes.ts +1 -1
  83. package/src/test/tx_delayer.ts +1 -1
  84. package/src/utils.ts +29 -0
@@ -0,0 +1,803 @@
1
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+ import { retryUntil } from '@aztec/foundation/retry';
4
+ import { DateProvider } from '@aztec/foundation/timer';
5
+
6
+ import { type Block, type FormattedTransaction, type Hex, formatGwei } from 'viem';
7
+
8
+ import type { ViemClient } from '../types.js';
9
+ import { calculatePercentile, isBlobTransaction } from '../utils.js';
10
+ import type { L1TxUtilsConfig } from './config.js';
11
+ import { BLOB_CAPACITY_SCHEDULE, GAS_PER_BLOB, WEI_CONST } from './constants.js';
12
+ import {
13
+ DEFAULT_PRIORITY_FEE_STRATEGIES,
14
+ type PriorityFeeStrategy,
15
+ type PriorityFeeStrategyContext,
16
+ } from './fee-strategies/index.js';
17
+ import type { L1BlobInputs, L1TxRequest } from './types.js';
18
+
19
+ /**
20
+ * Information about a blob transaction in the pending pool or mined block
21
+ */
22
+ export interface BlobTxInfo {
23
+ hash: Hex;
24
+ maxPriorityFeePerGas: bigint;
25
+ maxFeePerGas: bigint;
26
+ maxFeePerBlobGas: bigint;
27
+ blobCount: number;
28
+ gas: bigint;
29
+ }
30
+
31
+ /**
32
+ * Snapshot of the pending block state at the time of analysis
33
+ */
34
+ export interface PendingBlockSnapshot {
35
+ /** Timestamp when the snapshot was taken */
36
+ timestamp: number;
37
+ /** The latest L1 block number at the time of snapshot */
38
+ latestBlockNumber: bigint;
39
+ /** Base fee per gas of the latest block */
40
+ baseFeePerGas: bigint;
41
+ /** Blob base fee at the time of snapshot */
42
+ blobBaseFee: bigint;
43
+ /** Total number of transactions in the pending block */
44
+ pendingTxCount: number;
45
+ /** Number of blob transactions in the pending block */
46
+ pendingBlobTxCount: number;
47
+ /** Total number of blobs in pending blob transactions */
48
+ pendingBlobCount: number;
49
+ /** Details of blob transactions in the pending pool */
50
+ pendingBlobTxs: BlobTxInfo[];
51
+ /** 75th percentile priority fee from pending transactions */
52
+ pendingP75PriorityFee: bigint;
53
+ /** 75th percentile priority fee from pending blob transactions */
54
+ pendingBlobP75PriorityFee: bigint;
55
+ }
56
+
57
+ /**
58
+ * Result of a strategy's priority fee calculation for analysis
59
+ */
60
+ export interface StrategyAnalysisResult {
61
+ /** Strategy ID */
62
+ strategyId: string;
63
+ /** Strategy name */
64
+ strategyName: string;
65
+ /** Calculated priority fee from this strategy */
66
+ calculatedPriorityFee: bigint;
67
+ /** Debug info from the strategy calculation */
68
+ debugInfo?: Record<string, string | number>;
69
+ /** Whether this transaction would have been included with this strategy's fee */
70
+ wouldBeIncluded?: boolean;
71
+ /** If not included, reason why */
72
+ exclusionReason?: 'priority_fee_too_low' | 'block_full';
73
+ /** Priority fee delta compared to minimum included fee */
74
+ priorityFeeDelta?: bigint;
75
+ /** Estimated total cost in ETH for this strategy */
76
+ estimatedCostEth?: number;
77
+ /** Estimated overpayment in ETH vs minimum required */
78
+ estimatedOverpaymentEth?: number;
79
+ }
80
+
81
+ /**
82
+ * Transaction metadata and strategy analysis results
83
+ */
84
+ export interface ComputedGasPrices {
85
+ /** Estimated gas limit for the transaction */
86
+ gasLimit: bigint;
87
+ /** Number of blobs in our transaction */
88
+ blobCount: number;
89
+ /** Results from all strategies analyzed */
90
+ strategyResults?: StrategyAnalysisResult[];
91
+ }
92
+
93
+ /**
94
+ * Information about what actually got included in the mined block
95
+ */
96
+ export interface MinedBlockInfo {
97
+ /** The block number that was mined */
98
+ blockNumber: bigint;
99
+ /** The block hash */
100
+ blockHash: Hex;
101
+ /** Timestamp of the mined block */
102
+ blockTimestamp: bigint;
103
+ /** Base fee per gas in the mined block */
104
+ baseFeePerGas: bigint;
105
+ /** Blob gas used in the mined block */
106
+ blobGasUsed: bigint;
107
+ /** Total number of transactions in the mined block */
108
+ txCount: number;
109
+ /** Number of blob transactions that got included */
110
+ includedBlobTxCount: number;
111
+ /** Total number of blobs included in the block */
112
+ includedBlobCount: number;
113
+ /** Details of blob transactions that got included */
114
+ includedBlobTxs: BlobTxInfo[];
115
+ /** Minimum priority fee among included transactions */
116
+ minIncludedPriorityFee: bigint;
117
+ /** Minimum priority fee among included blob transactions */
118
+ minIncludedBlobPriorityFee: bigint;
119
+ }
120
+
121
+ /**
122
+ * Complete fee analysis result comparing our estimates to what happened
123
+ */
124
+ export interface L1FeeAnalysisResult {
125
+ /** Unique identifier for this analysis */
126
+ id: string;
127
+ /** L2 slot number this analysis was performed for */
128
+ l2SlotNumber: SlotNumber;
129
+ /** Snapshot of pending state when we computed our fees */
130
+ pendingSnapshot: PendingBlockSnapshot;
131
+ /** Our computed gas prices */
132
+ computedPrices: ComputedGasPrices;
133
+ /** Information about what we were trying to send */
134
+ txInfo: {
135
+ requestCount: number;
136
+ hasBlobData: boolean;
137
+ totalEstimatedGas: bigint;
138
+ };
139
+ /** Information about the block that was eventually mined (populated after block mines) */
140
+ minedBlock?: MinedBlockInfo;
141
+ /** Analysis results (populated after block mines) */
142
+ analysis?: {
143
+ /** Time in ms between our snapshot and block mining */
144
+ timeBeforeBlockMs: number;
145
+ /** How many blob txs from pending actually got included */
146
+ pendingBlobTxsIncludedCount: number;
147
+ /** How many blob txs from pending were NOT included */
148
+ pendingBlobTxsExcludedCount: number;
149
+ /** Number of blobs in the mined block */
150
+ blobsInBlock: number;
151
+ /** Maximum blob capacity for this block */
152
+ maxBlobCapacity: number;
153
+ /** Whether the block's blob space was full */
154
+ blockBlobsFull: boolean;
155
+ /** Actual cost in ETH if this analysis is linked to a mined tx */
156
+ actualCostEth?: number;
157
+ /** Strategy results ranked by estimated cost */
158
+ costRanking?: Array<{
159
+ strategyId: string;
160
+ strategyName: string;
161
+ estimatedCostEth: number;
162
+ wouldBeIncluded: boolean;
163
+ }>;
164
+ };
165
+ }
166
+
167
+ /** Callback type for when an analysis is completed */
168
+ export type L1FeeAnalysisCallback = (analysis: L1FeeAnalysisResult) => void;
169
+
170
+ /**
171
+ * Result of processing transactions to extract blob tx info and priority fees
172
+ */
173
+ interface ProcessedTransactions {
174
+ blobTxs: BlobTxInfo[];
175
+ allPriorityFees: bigint[];
176
+ blobPriorityFees: bigint[];
177
+ totalBlobCount: number;
178
+ }
179
+
180
+ /**
181
+ * Gets the maximum blob capacity for a given block timestamp
182
+ */
183
+ function getMaxBlobCapacity(blockTimestamp: bigint): number {
184
+ const timestamp = Number(blockTimestamp);
185
+ // Find the applicable schedule entry (sorted by timestamp descending)
186
+ for (const schedule of BLOB_CAPACITY_SCHEDULE) {
187
+ if (timestamp >= schedule.timestamp) {
188
+ return schedule.max;
189
+ }
190
+ }
191
+ // Fallback (should never hit)
192
+ return BLOB_CAPACITY_SCHEDULE[BLOB_CAPACITY_SCHEDULE.length - 1].max;
193
+ }
194
+
195
+ /**
196
+ * Processes a list of transactions to extract blob transaction info and priority fees.
197
+ * Handles both pending and mined transactions.
198
+ * Note: Only works with blocks fetched with includeTransactions: true
199
+ */
200
+ function processTransactions(transactions: readonly FormattedTransaction[] | undefined): ProcessedTransactions {
201
+ const blobTxs: BlobTxInfo[] = [];
202
+ const allPriorityFees: bigint[] = [];
203
+ const blobPriorityFees: bigint[] = [];
204
+ let totalBlobCount = 0;
205
+
206
+ if (!transactions) {
207
+ return { blobTxs, allPriorityFees, blobPriorityFees, totalBlobCount };
208
+ }
209
+
210
+ for (const tx of transactions) {
211
+ const priorityFee = tx.maxPriorityFeePerGas || 0n;
212
+ if (priorityFee > 0n) {
213
+ allPriorityFees.push(priorityFee);
214
+ }
215
+
216
+ // Check if this is a blob transaction
217
+ if (isBlobTransaction(tx)) {
218
+ const blobCount = tx.blobVersionedHashes.length;
219
+ totalBlobCount += blobCount;
220
+
221
+ if (priorityFee > 0n) {
222
+ blobPriorityFees.push(priorityFee);
223
+ }
224
+
225
+ blobTxs.push({
226
+ hash: tx.hash,
227
+ maxPriorityFeePerGas: priorityFee,
228
+ maxFeePerGas: tx.maxFeePerGas || 0n,
229
+ maxFeePerBlobGas: tx.maxFeePerBlobGas,
230
+ blobCount,
231
+ gas: tx.gas,
232
+ });
233
+ }
234
+ }
235
+
236
+ return { blobTxs, allPriorityFees, blobPriorityFees, totalBlobCount };
237
+ }
238
+
239
+ /**
240
+ * Analyzes L1 transaction fees in fisherman mode.
241
+ * Captures pending block state, records gas calculations, and compares to what gets included.
242
+ * Supports multiple priority fee calculation strategies for comparison.
243
+ */
244
+ export class L1FeeAnalyzer {
245
+ private pendingAnalyses: Map<string, L1FeeAnalysisResult> = new Map();
246
+ private pendingCallbacks: Map<string, L1FeeAnalysisCallback> = new Map();
247
+ private completedAnalyses: L1FeeAnalysisResult[] = [];
248
+ private analysisCounter = 0;
249
+ private strategies: PriorityFeeStrategy[];
250
+
251
+ constructor(
252
+ private client: ViemClient,
253
+ private dateProvider: DateProvider = new DateProvider(),
254
+ private logger: Logger = createLogger('ethereum:l1-fee-analyzer'),
255
+ private maxCompletedAnalyses: number = 100,
256
+ strategies: PriorityFeeStrategy[] = DEFAULT_PRIORITY_FEE_STRATEGIES,
257
+ private gasConfig: L1TxUtilsConfig = {},
258
+ ) {
259
+ this.strategies = strategies;
260
+ }
261
+
262
+ /**
263
+ * Executes all configured strategies and returns their results.
264
+ * Each strategy handles its own RPC calls internally.
265
+ * @param isBlobTx - Whether this is a blob transaction
266
+ * @returns Array of strategy results
267
+ */
268
+ async executeAllStrategies(isBlobTx: boolean): Promise<StrategyAnalysisResult[]> {
269
+ const results: StrategyAnalysisResult[] = [];
270
+ const context: PriorityFeeStrategyContext = {
271
+ gasConfig: this.gasConfig,
272
+ isBlobTx,
273
+ logger: this.logger,
274
+ };
275
+
276
+ for (const strategy of this.strategies) {
277
+ try {
278
+ const result = await strategy.execute(this.client, context);
279
+
280
+ results.push({
281
+ strategyId: strategy.id,
282
+ strategyName: strategy.name,
283
+ calculatedPriorityFee: result.priorityFee,
284
+ debugInfo: result.debugInfo,
285
+ });
286
+
287
+ this.logger.debug(`Strategy "${strategy.name}" calculated priority fee`, {
288
+ strategyId: strategy.id,
289
+ priorityFee: formatGwei(result.priorityFee),
290
+ ...result.debugInfo,
291
+ });
292
+ } catch (err) {
293
+ this.logger.error(`Error calculating priority fee for strategy "${strategy.name}"`, err, {
294
+ strategyId: strategy.id,
295
+ });
296
+ }
297
+ }
298
+
299
+ return results;
300
+ }
301
+
302
+ /**
303
+ * Captures a snapshot of the current pending block state
304
+ */
305
+ async capturePendingSnapshot(): Promise<PendingBlockSnapshot> {
306
+ const timestamp = this.dateProvider.now();
307
+
308
+ // Fetch data in parallel
309
+ const [latestBlock, pendingBlock, blobBaseFee] = await Promise.all([
310
+ this.client.getBlock({ blockTag: 'latest' }),
311
+ this.client.getBlock({ blockTag: 'pending', includeTransactions: true }).catch(() => null),
312
+ this.client.getBlobBaseFee().catch(() => 0n),
313
+ ]);
314
+
315
+ const baseFeePerGas = latestBlock.baseFeePerGas || 0n;
316
+ const latestBlockNumber = latestBlock.number;
317
+
318
+ // Extract blob transaction info from pending block
319
+ const {
320
+ blobTxs: pendingBlobTxs,
321
+ allPriorityFees: allPendingPriorityFees,
322
+ blobPriorityFees: pendingBlobPriorityFees,
323
+ totalBlobCount: pendingBlobCount,
324
+ } = processTransactions(pendingBlock?.transactions);
325
+
326
+ // Calculate 75th percentile priority fees
327
+ const pendingP75PriorityFee = calculatePercentile(allPendingPriorityFees, 75);
328
+ const pendingBlobP75PriorityFee = calculatePercentile(pendingBlobPriorityFees, 75);
329
+
330
+ const pendingTxCount = pendingBlock?.transactions?.length || 0;
331
+
332
+ return {
333
+ timestamp,
334
+ latestBlockNumber,
335
+ baseFeePerGas,
336
+ blobBaseFee,
337
+ pendingTxCount,
338
+ pendingBlobTxCount: pendingBlobTxs.length,
339
+ pendingBlobCount,
340
+ pendingBlobTxs,
341
+ pendingP75PriorityFee,
342
+ pendingBlobP75PriorityFee,
343
+ };
344
+ }
345
+
346
+ /**
347
+ * Starts a fee analysis for a transaction bundle
348
+ * @param l2SlotNumber - The L2 slot this analysis is for
349
+ * @param gasLimit - The estimated gas limit
350
+ * @param requests - The transaction requests being analyzed
351
+ * @param blobInputs - Blob inputs if this is a blob transaction
352
+ * @param onComplete - Optional callback to invoke when analysis completes
353
+ * @returns The analysis ID for tracking
354
+ */
355
+ async startAnalysis(
356
+ l2SlotNumber: SlotNumber,
357
+ gasLimit: bigint,
358
+ requests: L1TxRequest[],
359
+ blobInputs?: L1BlobInputs,
360
+ onComplete?: L1FeeAnalysisCallback,
361
+ ): Promise<string> {
362
+ const id = `fee-analysis-${++this.analysisCounter}-${Date.now()}`;
363
+
364
+ const blobCount = blobInputs?.blobs?.length || 0;
365
+ const isBlobTx = blobCount > 0;
366
+
367
+ // Execute all strategies and capture pending snapshot in parallel
368
+ const [pendingSnapshot, strategyResults] = await Promise.all([
369
+ this.capturePendingSnapshot(),
370
+ this.executeAllStrategies(isBlobTx),
371
+ ]);
372
+
373
+ const analysis: L1FeeAnalysisResult = {
374
+ id,
375
+ l2SlotNumber,
376
+ pendingSnapshot,
377
+ computedPrices: {
378
+ gasLimit,
379
+ blobCount,
380
+ strategyResults,
381
+ },
382
+ txInfo: {
383
+ requestCount: requests.length,
384
+ hasBlobData: isBlobTx,
385
+ totalEstimatedGas: gasLimit,
386
+ },
387
+ };
388
+
389
+ this.pendingAnalyses.set(id, analysis);
390
+ if (onComplete) {
391
+ this.pendingCallbacks.set(id, onComplete);
392
+ }
393
+
394
+ // Log strategy calculations
395
+ const strategyLogInfo = strategyResults.reduce(
396
+ (acc, s) => {
397
+ acc[`strategy_${s.strategyId}`] = formatGwei(s.calculatedPriorityFee);
398
+ return acc;
399
+ },
400
+ {} as Record<string, string>,
401
+ );
402
+
403
+ this.logger.debug('Started fee analysis with strategy calculations', {
404
+ id,
405
+ l2SlotNumber: l2SlotNumber.toString(),
406
+ pendingBlobTxCount: pendingSnapshot.pendingBlobTxCount,
407
+ pendingBlobCount: pendingSnapshot.pendingBlobCount,
408
+ pendingBlobP75: formatGwei(pendingSnapshot.pendingBlobP75PriorityFee),
409
+ strategiesAnalyzed: strategyResults.length,
410
+ ...strategyLogInfo,
411
+ });
412
+
413
+ // Start watching for the next block
414
+ void this.watchForNextBlock(id, pendingSnapshot.latestBlockNumber);
415
+
416
+ return id;
417
+ }
418
+
419
+ /**
420
+ * Watches for the next block to be mined and completes the analysis
421
+ */
422
+ private async watchForNextBlock(analysisId: string, startBlockNumber: bigint): Promise<void> {
423
+ const analysis = this.pendingAnalyses.get(analysisId);
424
+ if (!analysis) {
425
+ return;
426
+ }
427
+
428
+ try {
429
+ // wait for next block
430
+ await retryUntil(
431
+ async () => {
432
+ const currentBlockNumber = await this.client.getBlockNumber();
433
+ if (currentBlockNumber > startBlockNumber) {
434
+ return true;
435
+ }
436
+ return false;
437
+ },
438
+ 'Wait for next block',
439
+ 13_000,
440
+ 0.5,
441
+ );
442
+
443
+ const minedBlock = await this.client.getBlock({
444
+ includeTransactions: true,
445
+ });
446
+ this.completeAnalysis(analysisId, minedBlock);
447
+ } catch (err) {
448
+ this.logger.error('Error waiting for next block in fee analysis', err, { analysisId });
449
+ } finally {
450
+ this.pendingAnalyses.delete(analysisId);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Completes the analysis once the next block is mined
456
+ */
457
+ private completeAnalysis(analysisId: string, minedBlock: Block<bigint, true, 'latest'>): void {
458
+ const analysis = this.pendingAnalyses.get(analysisId);
459
+ if (!analysis) {
460
+ return;
461
+ }
462
+
463
+ // Extract blob transaction info from mined block
464
+ const {
465
+ blobTxs: includedBlobTxs,
466
+ allPriorityFees: includedPriorityFees,
467
+ blobPriorityFees: includedBlobPriorityFees,
468
+ totalBlobCount: includedBlobCount,
469
+ } = processTransactions(minedBlock.transactions);
470
+
471
+ // Get minimum included fees
472
+ const minIncludedPriorityFee = includedPriorityFees.length > 0 ? this.minBigInt(includedPriorityFees) : 0n;
473
+ const minIncludedBlobPriorityFee =
474
+ includedBlobPriorityFees.length > 0 ? this.minBigInt(includedBlobPriorityFees) : 0n;
475
+
476
+ // Populate mined block info
477
+ analysis.minedBlock = {
478
+ blockNumber: minedBlock.number,
479
+ blockHash: minedBlock.hash,
480
+ blockTimestamp: minedBlock.timestamp,
481
+ baseFeePerGas: minedBlock.baseFeePerGas || 0n,
482
+ blobGasUsed: minedBlock.blobGasUsed || 0n,
483
+ txCount: minedBlock.transactions?.length || 0,
484
+ includedBlobTxCount: includedBlobTxs.length,
485
+ includedBlobCount,
486
+ includedBlobTxs,
487
+ minIncludedPriorityFee,
488
+ minIncludedBlobPriorityFee,
489
+ };
490
+
491
+ // Calculate time before block mined
492
+ const blockTimestampMs = Number(minedBlock.timestamp) * 1000;
493
+ const timeBeforeBlockMs = blockTimestampMs - analysis.pendingSnapshot.timestamp;
494
+
495
+ // Calculate how many blobs were actually in the mined block
496
+ const blobsInBlock = minedBlock.blobGasUsed > 0n ? Number(minedBlock.blobGasUsed / GAS_PER_BLOB) : 0;
497
+ const maxBlobCapacity = getMaxBlobCapacity(minedBlock.timestamp);
498
+ const blockBlobsFull = blobsInBlock >= maxBlobCapacity;
499
+
500
+ // Count how many pending blob txs actually got included
501
+ const pendingBlobHashes = new Set(analysis.pendingSnapshot.pendingBlobTxs.map(tx => tx.hash));
502
+ const includedBlobHashes = new Set(includedBlobTxs.map(tx => tx.hash));
503
+ const pendingBlobTxsIncludedCount = [...pendingBlobHashes].filter(h => includedBlobHashes.has(h)).length;
504
+ const pendingBlobTxsExcludedCount = analysis.pendingSnapshot.pendingBlobTxCount - pendingBlobTxsIncludedCount;
505
+
506
+ analysis.analysis = {
507
+ timeBeforeBlockMs,
508
+ pendingBlobTxsIncludedCount,
509
+ pendingBlobTxsExcludedCount,
510
+ blobsInBlock,
511
+ maxBlobCapacity,
512
+ blockBlobsFull,
513
+ };
514
+
515
+ // Evaluate each strategy against the mined block
516
+ const isBlobTx = analysis.computedPrices.blobCount > 0;
517
+ const minPriorityFeeToCompare = isBlobTx ? minIncludedBlobPriorityFee : minIncludedPriorityFee;
518
+ const gasLimit = analysis.computedPrices.gasLimit;
519
+
520
+ if (analysis.computedPrices.strategyResults) {
521
+ for (const strategyResult of analysis.computedPrices.strategyResults) {
522
+ const strategyPriorityFee = strategyResult.calculatedPriorityFee;
523
+ const strategyPriorityFeeDelta = strategyPriorityFee - minPriorityFeeToCompare;
524
+
525
+ // Determine if this strategy would have resulted in inclusion
526
+ let strategyWouldBeIncluded = true;
527
+ let strategyExclusionReason: 'priority_fee_too_low' | 'block_full' | undefined;
528
+
529
+ if (isBlobTx) {
530
+ // For blob txs, only consider priority fee if blob space was full
531
+ if (
532
+ includedBlobPriorityFees.length > 0 &&
533
+ strategyPriorityFee < minIncludedBlobPriorityFee &&
534
+ blockBlobsFull
535
+ ) {
536
+ strategyWouldBeIncluded = false;
537
+ strategyExclusionReason = 'priority_fee_too_low';
538
+ }
539
+ } else {
540
+ // For non-blob txs, use the old logic
541
+ if (includedPriorityFees.length > 0 && strategyPriorityFee < minIncludedPriorityFee) {
542
+ strategyWouldBeIncluded = false;
543
+ strategyExclusionReason = 'priority_fee_too_low';
544
+ }
545
+ }
546
+
547
+ // Calculate estimated cost in ETH for this strategy
548
+ // Cost = gasLimit * (baseFee + priorityFee)
549
+ const baseFee = analysis.minedBlock.baseFeePerGas;
550
+
551
+ // Execution cost: gasLimit * (baseFee + priorityFee)
552
+ const executionCostWei = gasLimit * (baseFee + strategyPriorityFee);
553
+ const estimatedCostEth = Number(executionCostWei) / 1e18;
554
+
555
+ // Calculate minimum cost needed for inclusion
556
+ const minExecutionCostWei = gasLimit * (baseFee + minPriorityFeeToCompare);
557
+ const minCostEth = Number(minExecutionCostWei) / 1e18;
558
+
559
+ // Overpayment is the difference
560
+ const estimatedOverpaymentEth = estimatedCostEth - minCostEth;
561
+
562
+ // Update the strategy result with analysis data
563
+ strategyResult.wouldBeIncluded = strategyWouldBeIncluded;
564
+ strategyResult.exclusionReason = strategyExclusionReason;
565
+ strategyResult.priorityFeeDelta = strategyPriorityFeeDelta;
566
+ strategyResult.estimatedCostEth = estimatedCostEth;
567
+ strategyResult.estimatedOverpaymentEth = estimatedOverpaymentEth;
568
+
569
+ // Log per-strategy results
570
+ this.logger.info(`Strategy "${strategyResult.strategyName}" analysis`, {
571
+ id: analysisId,
572
+ strategyId: strategyResult.strategyId,
573
+ strategyName: strategyResult.strategyName,
574
+ calculatedPriorityFee: formatGwei(strategyPriorityFee),
575
+ minIncludedPriorityFee: formatGwei(minPriorityFeeToCompare),
576
+ priorityFeeDelta: formatGwei(strategyPriorityFeeDelta),
577
+ wouldBeIncluded: strategyWouldBeIncluded,
578
+ exclusionReason: strategyExclusionReason,
579
+ estimatedCostEth: estimatedCostEth.toFixed(6),
580
+ estimatedOverpaymentEth: estimatedOverpaymentEth.toFixed(6),
581
+ });
582
+ }
583
+
584
+ // Create cost ranking
585
+ const costRanking = analysis.computedPrices.strategyResults
586
+ .map(s => ({
587
+ strategyId: s.strategyId,
588
+ strategyName: s.strategyName,
589
+ estimatedCostEth: s.estimatedCostEth!,
590
+ wouldBeIncluded: s.wouldBeIncluded!,
591
+ }))
592
+ .sort((a, b) => a.estimatedCostEth - b.estimatedCostEth);
593
+
594
+ analysis.analysis!.costRanking = costRanking;
595
+
596
+ // Log cost ranking summary
597
+ this.logger.info('Strategy cost ranking', {
598
+ id: analysisId,
599
+ cheapestStrategy: costRanking[0]?.strategyName,
600
+ cheapestCost: costRanking[0]?.estimatedCostEth.toFixed(6),
601
+ cheapestWouldBeIncluded: costRanking[0]?.wouldBeIncluded,
602
+ mostExpensiveStrategy: costRanking[costRanking.length - 1]?.strategyName,
603
+ mostExpensiveCost: costRanking[costRanking.length - 1]?.estimatedCostEth.toFixed(6),
604
+ mostExpensiveWouldBeIncluded: costRanking[costRanking.length - 1]?.wouldBeIncluded,
605
+ costSpread:
606
+ costRanking.length > 1
607
+ ? (costRanking[costRanking.length - 1].estimatedCostEth - costRanking[0].estimatedCostEth).toFixed(6)
608
+ : '0',
609
+ });
610
+ }
611
+
612
+ // Log the overall results
613
+ this.logger.info('Fee analysis completed', {
614
+ id: analysisId,
615
+ l2SlotNumber: analysis.l2SlotNumber.toString(),
616
+ timeBeforeBlockMs,
617
+ pendingBlobTxCount: analysis.pendingSnapshot.pendingBlobTxCount,
618
+ includedBlobTxCount: analysis.minedBlock.includedBlobTxCount,
619
+ pendingBlobTxsIncludedCount,
620
+ pendingBlobTxsExcludedCount,
621
+ blobsInBlock,
622
+ maxBlobCapacity,
623
+ blockBlobsFull,
624
+ minIncludedPriorityFee: formatGwei(minIncludedPriorityFee),
625
+ minIncludedBlobPriorityFee: formatGwei(minIncludedBlobPriorityFee),
626
+ strategiesAnalyzed: analysis.computedPrices.strategyResults?.length ?? 0,
627
+ });
628
+
629
+ // Move to completed analyses
630
+ this.pendingAnalyses.delete(analysisId);
631
+ this.completedAnalyses.push(analysis);
632
+
633
+ // Trim old completed analyses if needed
634
+ while (this.completedAnalyses.length > this.maxCompletedAnalyses) {
635
+ this.completedAnalyses.shift();
636
+ }
637
+
638
+ // Invoke the callback for this specific analysis
639
+ const callback = this.pendingCallbacks.get(analysisId);
640
+ if (callback) {
641
+ try {
642
+ callback(analysis);
643
+ } catch (err) {
644
+ this.logger.error('Error in analysis complete callback', err);
645
+ }
646
+ this.pendingCallbacks.delete(analysisId);
647
+ }
648
+ }
649
+
650
+ /**
651
+ * Gets a specific analysis result by ID
652
+ */
653
+ getAnalysis(id: string): L1FeeAnalysisResult | undefined {
654
+ return this.pendingAnalyses.get(id) || this.completedAnalyses.find(a => a.id === id);
655
+ }
656
+
657
+ /**
658
+ * Gets all completed analyses
659
+ */
660
+ getCompletedAnalyses(): L1FeeAnalysisResult[] {
661
+ return [...this.completedAnalyses];
662
+ }
663
+
664
+ /**
665
+ * Gets statistics about all completed analyses
666
+ */
667
+ getAnalysisStats(): {
668
+ totalAnalyses: number;
669
+ avgTimeBeforeBlockMs: number;
670
+ avgBlobsInBlock: number;
671
+ blocksBlobsFull: number;
672
+ } {
673
+ const completed = this.completedAnalyses.filter(a => a.analysis);
674
+
675
+ if (completed.length === 0) {
676
+ return {
677
+ totalAnalyses: 0,
678
+ avgTimeBeforeBlockMs: 0,
679
+ avgBlobsInBlock: 0,
680
+ blocksBlobsFull: 0,
681
+ };
682
+ }
683
+
684
+ const avgTimeBeforeBlockMs =
685
+ completed.reduce((sum, a) => sum + a.analysis!.timeBeforeBlockMs, 0) / completed.length;
686
+
687
+ const avgBlobsInBlock = completed.reduce((sum, a) => sum + a.analysis!.blobsInBlock, 0) / completed.length;
688
+
689
+ const blocksBlobsFull = completed.filter(a => a.analysis!.blockBlobsFull).length;
690
+
691
+ return {
692
+ totalAnalyses: completed.length,
693
+ avgTimeBeforeBlockMs,
694
+ avgBlobsInBlock,
695
+ blocksBlobsFull,
696
+ };
697
+ }
698
+
699
+ /**
700
+ * Gets comparative statistics for all strategies across completed analyses
701
+ */
702
+ getStrategyComparison(): Array<{
703
+ strategyId: string;
704
+ strategyName: string;
705
+ totalAnalyses: number;
706
+ inclusionCount: number;
707
+ inclusionRate: number;
708
+ avgEstimatedCostEth: number;
709
+ totalEstimatedCostEth: number;
710
+ avgOverpaymentEth: number;
711
+ totalOverpaymentEth: number;
712
+ avgPriorityFeeDeltaGwei: number;
713
+ }> {
714
+ const completed = this.completedAnalyses.filter(a => a.analysis);
715
+
716
+ if (completed.length === 0) {
717
+ return [];
718
+ }
719
+
720
+ // Collect data by strategy ID
721
+ const strategyData = new Map<
722
+ string,
723
+ {
724
+ strategyName: string;
725
+ analyses: number;
726
+ inclusions: number;
727
+ totalCostEth: number;
728
+ totalOverpaymentEth: number;
729
+ totalPriorityFeeDelta: number;
730
+ }
731
+ >();
732
+
733
+ for (const analysis of completed) {
734
+ if (!analysis.computedPrices.strategyResults) {
735
+ continue;
736
+ }
737
+
738
+ for (const strategyResult of analysis.computedPrices.strategyResults) {
739
+ if (!strategyData.has(strategyResult.strategyId)) {
740
+ strategyData.set(strategyResult.strategyId, {
741
+ strategyName: strategyResult.strategyName,
742
+ analyses: 0,
743
+ inclusions: 0,
744
+ totalCostEth: 0,
745
+ totalOverpaymentEth: 0,
746
+ totalPriorityFeeDelta: 0,
747
+ });
748
+ }
749
+
750
+ const data = strategyData.get(strategyResult.strategyId)!;
751
+ data.analyses++;
752
+
753
+ if (strategyResult.wouldBeIncluded) {
754
+ data.inclusions++;
755
+ }
756
+
757
+ if (strategyResult.estimatedCostEth !== undefined) {
758
+ data.totalCostEth += strategyResult.estimatedCostEth;
759
+ }
760
+
761
+ if (strategyResult.estimatedOverpaymentEth !== undefined) {
762
+ data.totalOverpaymentEth += strategyResult.estimatedOverpaymentEth;
763
+ }
764
+
765
+ if (strategyResult.priorityFeeDelta !== undefined) {
766
+ data.totalPriorityFeeDelta += Number(strategyResult.priorityFeeDelta);
767
+ }
768
+ }
769
+ }
770
+
771
+ // Convert to output format
772
+ const results = Array.from(strategyData.entries()).map(([strategyId, data]) => ({
773
+ strategyId,
774
+ strategyName: data.strategyName,
775
+ totalAnalyses: data.analyses,
776
+ inclusionCount: data.inclusions,
777
+ inclusionRate: data.analyses > 0 ? data.inclusions / data.analyses : 0,
778
+ avgEstimatedCostEth: data.analyses > 0 ? data.totalCostEth / data.analyses : 0,
779
+ totalEstimatedCostEth: data.totalCostEth,
780
+ avgOverpaymentEth: data.analyses > 0 ? data.totalOverpaymentEth / data.analyses : 0,
781
+ totalOverpaymentEth: data.totalOverpaymentEth,
782
+ avgPriorityFeeDeltaGwei: data.analyses > 0 ? data.totalPriorityFeeDelta / data.analyses / Number(WEI_CONST) : 0,
783
+ }));
784
+
785
+ // Sort by inclusion rate descending, then by avg cost ascending
786
+ return results.sort((a, b) => {
787
+ if (Math.abs(a.inclusionRate - b.inclusionRate) > 0.01) {
788
+ return b.inclusionRate - a.inclusionRate;
789
+ }
790
+ return a.avgEstimatedCostEth - b.avgEstimatedCostEth;
791
+ });
792
+ }
793
+
794
+ /**
795
+ * Gets the minimum value from an array of bigints
796
+ */
797
+ private minBigInt(values: bigint[]): bigint {
798
+ if (values.length === 0) {
799
+ return 0n;
800
+ }
801
+ return values.reduce((min, val) => (val < min ? val : min), values[0]);
802
+ }
803
+ }