semioscan 0.11.2

Production-grade Rust library for blockchain analytics: gas calculation, price extraction, and block window calculations for EVM chains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// SPDX-FileCopyrightText: 2025 Semiotic AI, Inc.
//
// SPDX-License-Identifier: Apache-2.0

//! Gas cost calculation for blockchain transactions
//!
//! This module provides tools for calculating total gas costs for transactions between
//! two addresses over a given block range. It handles both L1 (Ethereum) and L2 (Optimism Stack)
//! chains correctly, including L1 data fees for L2 transactions.
//!
//! # Examples
//!
//! ```rust,ignore
//! use semioscan::GasCalculator;
//! use alloy_provider::ProviderBuilder;
//!
//! let provider = ProviderBuilder::new().connect_http(rpc_url.parse()?);
//! let calculator = GasCalculator::new(provider.clone());
//!
//! let result = calculator
//!     .get_gas_cost(chain_id, from_addr, to_addr, start_block, end_block)
//!     .await?;
//!
//! println!("Total gas cost: {} wei", result.total_gas_cost);
//! println!("Transactions: {}", result.transaction_count);
//! ```

use std::sync::Arc;

use alloy_chains::NamedChain;
use alloy_network::Network;
use alloy_primitives::{Address, U256};
use alloy_provider::Provider;
use serde::Serialize;
use tokio::sync::Mutex;

use crate::config::SemioscanConfig;
use crate::gas::cache::GasCache;
use crate::retrieval::DecimalPrecision;
use crate::types::config::TransactionCount;
use crate::types::fees::L1DataFee;
use crate::types::gas::{BlobCount, BlobGasPrice, GasAmount, GasBreakdown, GasPrice};
use crate::types::wei::WeiAmount;

/// Gas data for a single transaction
///
/// This enum represents gas costs for either L1 or L2 transactions. L2 transactions
/// include additional L1 data fees that are automatically included in calculations.
#[derive(Debug, Clone)]
pub enum GasForTx {
    /// L1 (Ethereum) transaction gas data
    L1(L1Gas),
    /// L2 (Optimism Stack) transaction gas data with L1 data fee
    L2(L2Gas),
}

impl From<(U256, U256)> for GasForTx {
    fn from((gas_used, effective_gas_price): (U256, U256)) -> Self {
        Self::L1(L1Gas::from((gas_used, effective_gas_price)))
    }
}

impl From<(U256, U256, U256)> for GasForTx {
    fn from((gas_used, effective_gas_price, l1_data_fee): (U256, U256, U256)) -> Self {
        Self::L2(L2Gas::from((gas_used, effective_gas_price, l1_data_fee)))
    }
}

/// Gas data for L1 (Ethereum) transactions
///
/// L1 transactions have a gas cost calculation that may include blob gas (EIP-4844):
/// `total_cost = (gas_used * effective_gas_price) + blob_gas_cost`
#[derive(Debug, Clone)]
pub struct L1Gas {
    /// Amount of gas consumed by the transaction
    pub gas_used: GasAmount,
    /// Effective gas price paid per unit of gas (in wei)
    pub effective_gas_price: GasPrice,
    /// Number of blobs in this transaction (0 for non-EIP-4844)
    pub blob_count: BlobCount,
    /// Blob gas price (0 for non-EIP-4844)
    pub blob_gas_price: BlobGasPrice,
}

impl L1Gas {
    /// Calculate execution gas cost (gas_used * effective_gas_price)
    pub fn execution_cost(&self) -> U256 {
        self.gas_used * self.effective_gas_price
    }

    /// Calculate blob gas cost (blob_gas_used * blob_gas_price)
    pub fn blob_cost(&self) -> U256 {
        self.blob_gas_price.cost_for_blobs(self.blob_count)
    }

    /// Calculate total gas cost (execution + blob)
    pub fn total_cost(&self) -> U256 {
        self.execution_cost().saturating_add(self.blob_cost())
    }

    /// Convert to GasBreakdown for detailed analysis
    pub fn to_breakdown(&self) -> GasBreakdown {
        GasBreakdown::builder()
            .execution_gas_cost(self.execution_cost())
            .blob_gas_cost(self.blob_cost())
            .blob_count(self.blob_count)
            .blob_gas_price(self.blob_gas_price)
            .build()
    }
}

impl From<(U256, U256)> for L1Gas {
    fn from((gas_used, effective_gas_price): (U256, U256)) -> Self {
        Self {
            gas_used: GasAmount::from(gas_used),
            effective_gas_price: GasPrice::from(effective_gas_price),
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }
    }
}

impl From<(U256, U256, BlobCount, BlobGasPrice)> for L1Gas {
    fn from(
        (gas_used, effective_gas_price, blob_count, blob_gas_price): (
            U256,
            U256,
            BlobCount,
            BlobGasPrice,
        ),
    ) -> Self {
        Self {
            gas_used: GasAmount::from(gas_used),
            effective_gas_price: GasPrice::from(effective_gas_price),
            blob_count,
            blob_gas_price,
        }
    }
}

/// Gas data for L2 (Optimism Stack) transactions
///
/// L2 transactions have an additional L1 data fee component and may include blob gas:
/// `total_cost = (gas_used * effective_gas_price) + l1_data_fee + blob_gas_cost`
///
/// The L1 data fee covers the cost of posting transaction data to the L1 chain.
#[derive(Debug, Clone)]
pub struct L2Gas {
    /// Amount of L2 gas consumed by the transaction
    pub gas_used: GasAmount,
    /// Effective L2 gas price paid per unit of gas (in wei)
    pub effective_gas_price: GasPrice,
    /// L1 data fee for posting transaction to L1 chain
    pub l1_data_fee: L1DataFee,
    /// Number of blobs in this transaction (0 for non-EIP-4844)
    pub blob_count: BlobCount,
    /// Blob gas price (0 for non-EIP-4844)
    pub blob_gas_price: BlobGasPrice,
}

impl L2Gas {
    /// Calculate execution gas cost (gas_used * effective_gas_price)
    pub fn execution_cost(&self) -> U256 {
        self.gas_used * self.effective_gas_price
    }

    /// Calculate blob gas cost (blob_gas_used * blob_gas_price)
    pub fn blob_cost(&self) -> U256 {
        self.blob_gas_price.cost_for_blobs(self.blob_count)
    }

    /// Calculate total gas cost (execution + blob + L1 data fee)
    pub fn total_cost(&self) -> U256 {
        self.execution_cost()
            .saturating_add(self.blob_cost())
            .saturating_add(self.l1_data_fee.as_u256())
    }

    /// Convert to GasBreakdown for detailed analysis
    pub fn to_breakdown(&self) -> GasBreakdown {
        GasBreakdown::builder()
            .execution_gas_cost(self.execution_cost())
            .blob_gas_cost(self.blob_cost())
            .l1_data_fee(self.l1_data_fee.as_u256())
            .blob_count(self.blob_count)
            .blob_gas_price(self.blob_gas_price)
            .build()
    }
}

impl From<(U256, U256, U256)> for L2Gas {
    fn from((gas_used, effective_gas_price, l1_data_fee): (U256, U256, U256)) -> Self {
        Self {
            gas_used: GasAmount::from(gas_used),
            effective_gas_price: GasPrice::from(effective_gas_price),
            l1_data_fee: L1DataFee::new(l1_data_fee),
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }
    }
}

impl From<(U256, U256, U256, BlobCount, BlobGasPrice)> for L2Gas {
    fn from(
        (gas_used, effective_gas_price, l1_data_fee, blob_count, blob_gas_price): (
            U256,
            U256,
            U256,
            BlobCount,
            BlobGasPrice,
        ),
    ) -> Self {
        Self {
            gas_used: GasAmount::from(gas_used),
            effective_gas_price: GasPrice::from(effective_gas_price),
            l1_data_fee: L1DataFee::new(l1_data_fee),
            blob_count,
            blob_gas_price,
        }
    }
}

/// Result of gas cost calculation over a block range
///
/// Contains the total gas costs paid for all transactions from one address to another,
/// along with the number of transactions processed and a detailed gas breakdown.
///
/// # Units
///
/// All gas costs are in wei (the smallest unit of native chain currency).
///
/// # L2 Handling
///
/// For L2 chains (Arbitrum, Base, Optimism, etc.), the `total_gas_cost` automatically
/// includes both L2 execution gas and L1 data fees.
///
/// # EIP-4844 Blob Gas
///
/// For transactions with blobs, the `breakdown` field separates blob gas costs from
/// execution gas costs, allowing detailed analysis of EIP-4844 transaction costs.
#[derive(Default, Debug, Clone, Serialize)]
pub struct GasCostResult {
    /// Chain where the transactions occurred
    pub chain: NamedChain,
    /// Address that sent the transactions
    pub from: Address,
    /// Address that received the transactions
    pub to: Address,
    /// Total gas cost in wei (includes L1 data fees for L2 chains and blob gas)
    pub total_gas_cost: WeiAmount,
    /// Number of transactions processed
    pub transaction_count: TransactionCount,
    /// Detailed breakdown of gas costs (execution vs blob vs L1 data)
    pub breakdown: GasBreakdown,
}

impl GasCostResult {
    pub fn new(chain: NamedChain, from: Address, to: Address) -> Self {
        Self {
            from,
            to,
            chain,
            total_gas_cost: WeiAmount::ZERO,
            transaction_count: TransactionCount::ZERO,
            breakdown: GasBreakdown::new(),
        }
    }

    pub fn add_l1_fee(&mut self, l1_fee: L1DataFee) {
        self.total_gas_cost = self.total_gas_cost + WeiAmount::from(l1_fee.as_u256());
        self.breakdown.l1_data_fee = self.breakdown.l1_data_fee.saturating_add(l1_fee.as_u256());
    }

    /// Add a transaction to the gas cost result
    ///
    /// This will add the gas cost for the transaction to the total gas cost
    /// and increment the transaction count. The breakdown is automatically updated
    /// to separate execution gas, blob gas, and L1 data fees.
    ///
    /// For EIP-4844 transactions, blob gas costs are tracked separately in the breakdown.
    pub fn add_transaction(&mut self, gas: GasForTx) {
        match gas {
            GasForTx::L1(ref g) => {
                let tx_breakdown = g.to_breakdown();
                self.total_gas_cost =
                    self.total_gas_cost + WeiAmount::from(tx_breakdown.total_cost());
                self.breakdown.merge(&tx_breakdown);
                self.transaction_count.increment();
            }
            GasForTx::L2(ref g) => {
                let tx_breakdown = g.to_breakdown();
                self.total_gas_cost =
                    self.total_gas_cost + WeiAmount::from(tx_breakdown.total_cost());
                self.breakdown.merge(&tx_breakdown);
                self.transaction_count.increment();
            }
        }
    }

    /// Merge another gas cost result into this one
    pub fn merge(&mut self, other: &Self) {
        self.total_gas_cost = self.total_gas_cost + other.total_gas_cost;
        self.transaction_count += other.transaction_count;
        self.breakdown.merge(&other.breakdown);
    }

    /// Check if any transactions in this result used blob gas (EIP-4844)
    pub fn has_blob_transactions(&self) -> bool {
        self.breakdown.has_blob_gas()
    }

    /// Get total blob gas cost across all transactions
    pub fn total_blob_gas_cost(&self) -> U256 {
        self.breakdown.blob_gas_cost
    }

    /// Get total execution gas cost (excluding blob gas and L1 data fees)
    pub fn total_execution_gas_cost(&self) -> U256 {
        self.breakdown.execution_gas_cost
    }

    /// Get total L1 data fee (for L2 chains)
    pub fn total_l1_data_fee(&self) -> U256 {
        self.breakdown.l1_data_fee
    }

    /// Get total blob count across all transactions
    pub fn total_blob_count(&self) -> BlobCount {
        self.breakdown.blob_count
    }

    /// Get the total gas cost formatted as a string
    pub fn formatted_gas_cost(&self) -> String {
        self.format_gas_cost()
    }

    fn format_gas_cost(&self) -> String {
        let gas_cost = self.total_gas_cost.as_u256();

        let decimals = DecimalPrecision::NativeToken.decimals();

        let divisor = U256::from(10).pow(U256::from(decimals));

        let whole = gas_cost / divisor;
        let fractional = gas_cost % divisor;

        // Convert fractional part to string with leading zeros
        let fractional_str = format!("{:0width$}", fractional, width = decimals as usize);

        // Format with proper decimal places, ensuring we don't have trailing zeros
        format!("{}.{}", whole, fractional_str.trim_end_matches('0'))
    }
}

pub struct GasCostCalculator<N: Network, P: Provider<N>> {
    pub(crate) provider: P,
    pub(crate) gas_cache: Arc<Mutex<GasCache>>,
    pub(crate) config: SemioscanConfig,
    pub(crate) _phantom: std::marker::PhantomData<N>,
}

impl<N: Network, P: Provider<N>> GasCostCalculator<N, P> {
    /// Create a new gas cost calculator with default configuration
    pub fn new(provider: P) -> Self {
        Self::with_config(provider, SemioscanConfig::default())
    }

    /// Create a gas cost calculator with custom configuration
    pub fn with_config(provider: P, config: SemioscanConfig) -> Self {
        Self {
            provider,
            gas_cache: Arc::new(Mutex::new(GasCache::default())),
            config,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a gas cost calculator with custom cache and configuration
    pub fn with_cache_and_config(
        provider: P,
        gas_cache: Arc<Mutex<GasCache>>,
        config: SemioscanConfig,
    ) -> Self {
        Self {
            provider,
            gas_cache,
            config,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a gas cost calculator with custom cache (uses default config)
    pub fn with_cache(provider: P, gas_cache: Arc<Mutex<GasCache>>) -> Self {
        Self::with_cache_and_config(provider, gas_cache, SemioscanConfig::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_primitives::address;

    #[test]
    fn test_gas_cost_result_add_transaction_l1() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let mut result = GasCostResult::new(NamedChain::Mainnet, from, to);

        // Add first transaction: 21000 gas at 50 gwei = 1,050,000,000,000,000 wei
        result.add_transaction(GasForTx::L1(L1Gas {
            gas_used: GasAmount::new(21000),
            effective_gas_price: GasPrice::from_gwei(50),
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }));

        assert_eq!(result.transaction_count, TransactionCount::new(1));
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(1_050_000_000_000_000u64)
        );

        // Add second transaction: 100000 gas at 60 gwei = 6,000,000,000,000,000 wei
        result.add_transaction(GasForTx::L1(L1Gas {
            gas_used: GasAmount::new(100000),
            effective_gas_price: GasPrice::from_gwei(60),
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }));

        assert_eq!(result.transaction_count, TransactionCount::new(2));
        // Total: 1,050,000,000,000,000 + 6,000,000,000,000,000 = 7,050,000,000,000,000
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(7_050_000_000_000_000u64)
        );
        // Verify breakdown tracks execution gas correctly
        assert_eq!(
            result.breakdown.execution_gas_cost,
            U256::from(7_050_000_000_000_000u64)
        );
        assert_eq!(result.breakdown.blob_gas_cost, U256::ZERO);
    }

    #[test]
    fn test_gas_cost_result_add_transaction_l1_with_blobs() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let mut result = GasCostResult::new(NamedChain::Mainnet, from, to);

        // Add EIP-4844 transaction: 21000 gas at 50 gwei + 2 blobs at 1 gwei
        // Execution: 21000 * 50 gwei = 1,050,000,000,000,000 wei
        // Blob: 2 * 131072 * 1 gwei = 262,144,000,000,000 wei
        // Total: 1,312,144,000,000,000 wei
        result.add_transaction(GasForTx::L1(L1Gas {
            gas_used: GasAmount::new(21000),
            effective_gas_price: GasPrice::from_gwei(50),
            blob_count: BlobCount::new(2),
            blob_gas_price: BlobGasPrice::from_gwei(1),
        }));

        assert_eq!(result.transaction_count, TransactionCount::new(1));
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(1_312_144_000_000_000u64)
        );
        // Verify breakdown separates execution and blob gas
        assert_eq!(
            result.breakdown.execution_gas_cost,
            U256::from(1_050_000_000_000_000u64)
        );
        assert_eq!(
            result.breakdown.blob_gas_cost,
            U256::from(262_144_000_000_000u64)
        );
        assert_eq!(result.breakdown.blob_count, BlobCount::new(2));
        assert!(result.has_blob_transactions());
    }

    #[test]
    fn test_gas_cost_result_add_transaction_l2() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let mut result = GasCostResult::new(NamedChain::Arbitrum, from, to); // Arbitrum

        // Add L2 transaction: 150000 gas at 0.1 gwei + 0.005 ETH L1 data fee
        result.add_transaction(GasForTx::L2(L2Gas {
            gas_used: GasAmount::new(150000),
            effective_gas_price: GasPrice::new(100_000_000), // 0.1 gwei
            l1_data_fee: L1DataFee::new(U256::from(5_000_000_000_000_000u64)), // 0.005 ETH
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }));

        assert_eq!(result.transaction_count, TransactionCount::new(1));
        // L2 gas: 150000 * 100,000,000 = 15,000,000,000,000
        // L1 fee: 5,000,000,000,000,000
        // Total: 5,015,000,000,000,000
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(5_015_000_000_000_000u64)
        );
        // Verify breakdown tracks L1 data fee correctly
        assert_eq!(
            result.breakdown.l1_data_fee,
            U256::from(5_000_000_000_000_000u64)
        );
        assert_eq!(
            result.breakdown.execution_gas_cost,
            U256::from(15_000_000_000_000u64)
        );
    }

    #[test]
    fn test_gas_cost_result_merge() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");

        let mut result1 = GasCostResult {
            chain: NamedChain::Mainnet,
            from,
            to,
            total_gas_cost: WeiAmount::from(1_000_000_000_000_000u64),
            transaction_count: TransactionCount::new(5),
            breakdown: GasBreakdown::builder()
                .execution_gas_cost(U256::from(1_000_000_000_000_000u64))
                .build(),
        };

        let result2 = GasCostResult {
            chain: NamedChain::Mainnet,
            from,
            to,
            total_gas_cost: WeiAmount::from(500_000_000_000_000u64),
            transaction_count: TransactionCount::new(3),
            breakdown: GasBreakdown::builder()
                .execution_gas_cost(U256::from(500_000_000_000_000u64))
                .build(),
        };

        result1.merge(&result2);

        // Test that merge adds both gas costs and transaction counts
        assert_eq!(
            result1.total_gas_cost,
            WeiAmount::from(1_500_000_000_000_000u64)
        );
        assert_eq!(result1.transaction_count, TransactionCount::new(8));
        // Verify breakdown is also merged
        assert_eq!(
            result1.breakdown.execution_gas_cost,
            U256::from(1_500_000_000_000_000u64)
        );
    }

    #[test]
    fn test_gas_cost_result_merge_with_zero() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");

        let mut result = GasCostResult {
            chain: NamedChain::Mainnet,
            from,
            to,
            total_gas_cost: WeiAmount::from(1_000_000u64),
            transaction_count: TransactionCount::new(5),
            breakdown: GasBreakdown::builder()
                .execution_gas_cost(U256::from(1_000_000u64))
                .build(),
        };

        let empty = GasCostResult::new(NamedChain::Mainnet, from, to);

        result.merge(&empty);

        // Merging with empty result should not change values
        assert_eq!(result.total_gas_cost, WeiAmount::from(1_000_000u64));
        assert_eq!(result.transaction_count, TransactionCount::new(5));
    }

    #[test]
    fn test_gas_cost_overflow_protection() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let mut result = GasCostResult::new(NamedChain::Mainnet, from, to);

        // Set to near-max value
        result.total_gas_cost = WeiAmount::from(U256::MAX - U256::from(1000u64));

        // Add transaction that would overflow - should saturate
        result.add_transaction(GasForTx::L1(L1Gas {
            gas_used: GasAmount::new(1000000),
            effective_gas_price: GasPrice::new(1000000),
            blob_count: BlobCount::ZERO,
            blob_gas_price: BlobGasPrice::ZERO,
        }));

        // Should saturate at U256::MAX, not wrap around
        assert_eq!(result.total_gas_cost, WeiAmount::from(U256::MAX));
        assert_eq!(result.transaction_count, TransactionCount::new(1));
    }

    #[test]
    fn test_gas_cost_merge_overflow_protection() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");

        let mut result1 = GasCostResult {
            chain: NamedChain::Mainnet,
            from,
            to,
            total_gas_cost: WeiAmount::from(U256::MAX - U256::from(100u64)),
            transaction_count: TransactionCount::new(5),
            breakdown: GasBreakdown::new(),
        };

        let result2 = GasCostResult {
            chain: NamedChain::Mainnet,
            from,
            to,
            total_gas_cost: WeiAmount::from(500u64),
            transaction_count: TransactionCount::new(3),
            breakdown: GasBreakdown::new(),
        };

        result1.merge(&result2);

        // Should saturate at U256::MAX
        assert_eq!(result1.total_gas_cost, WeiAmount::from(U256::MAX));
        assert_eq!(result1.transaction_count, TransactionCount::new(8));
    }

    #[test]
    fn test_gas_cost_result_zero_transactions() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let result = GasCostResult::new(NamedChain::Mainnet, from, to);

        assert_eq!(result.total_gas_cost, WeiAmount::ZERO);
        assert_eq!(result.transaction_count, TransactionCount::ZERO);
        assert_eq!(result.chain, NamedChain::Mainnet);
        assert_eq!(result.from, from);
        assert_eq!(result.to, to);
    }

    #[test]
    fn test_add_l1_fee() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");
        let mut result = GasCostResult::new(NamedChain::Arbitrum, from, to);

        result.add_l1_fee(L1DataFee::new(U256::from(1_000_000_000_000_000u64)));
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(1_000_000_000_000_000u64)
        );
        // Verify breakdown tracks L1 fees
        assert_eq!(
            result.breakdown.l1_data_fee,
            U256::from(1_000_000_000_000_000u64)
        );

        result.add_l1_fee(L1DataFee::new(U256::from(500_000_000_000_000u64)));
        assert_eq!(
            result.total_gas_cost,
            WeiAmount::from(1_500_000_000_000_000u64)
        );
        assert_eq!(
            result.breakdown.l1_data_fee,
            U256::from(1_500_000_000_000_000u64)
        );
    }

    #[test]
    fn test_formatted_gas_cost() {
        let from = address!("1111111111111111111111111111111111111111");
        let to = address!("2222222222222222222222222222222222222222");

        let mut result = GasCostResult::new(NamedChain::Mainnet, from, to);
        result.total_gas_cost = WeiAmount::from(1_500_000_000_000_000_000u64); // 1.5 ETH

        let formatted = result.formatted_gas_cost();
        // Should format as "1.5" (trailing zeros removed)
        assert!(formatted.starts_with("1.5"));
    }
}