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