semioscan 0.10.1

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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// SPDX-FileCopyrightText: 2025 Semiotic AI, Inc.
//
// SPDX-License-Identifier: Apache-2.0

use alloy_chains::NamedChain;
use alloy_erc20::LazyToken;
use alloy_primitives::{Address, BlockNumber, B256, U256};
use alloy_provider::Provider;
use alloy_rpc_types::Filter;
use futures::future::join_all;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
use tracing::{error, info, warn};

use crate::config::SemioscanConfig;
use crate::errors::PriceCalculationError;
use crate::events::scanner::EventScanner;
use crate::price::cache::PriceCache;
use crate::price::{PriceSource, PriceSourceError, SwapData};
use crate::{NormalizedAmount, TokenAmount, TokenDecimals, TokenPrice, TransactionCount, UsdValue};

// Internal type for swap data processing
struct SwapAmounts {
    token_amount: NormalizedAmount,
    usdc_amount: UsdValue,
}

// Price calculation result
#[derive(Debug, Clone, Serialize)]
pub struct TokenPriceResult {
    pub token_address: Address,
    pub total_token_amount: NormalizedAmount,
    pub total_usdc_amount: UsdValue,
    pub transaction_count: TransactionCount,
}

impl Default for TokenPriceResult {
    fn default() -> Self {
        Self {
            token_address: Address::ZERO,
            total_token_amount: NormalizedAmount::ZERO,
            total_usdc_amount: UsdValue::ZERO,
            transaction_count: TransactionCount::ZERO,
        }
    }
}

impl TokenPriceResult {
    pub fn new(token_address: Address) -> Self {
        Self {
            token_address,
            total_token_amount: NormalizedAmount::ZERO,
            total_usdc_amount: UsdValue::ZERO,
            transaction_count: TransactionCount::ZERO,
        }
    }

    fn add_swap(&mut self, token_amount: f64, usdc_amount: f64) {
        self.total_token_amount += NormalizedAmount::new(token_amount);
        self.total_usdc_amount += UsdValue::new(usdc_amount);
        self.transaction_count += TransactionCount::new(1);
    }

    /// Get the average price of the token
    pub fn get_average_price(&self) -> TokenPrice {
        if self.total_token_amount.is_zero() {
            return TokenPrice::ZERO;
        }
        TokenPrice::new(self.total_usdc_amount.as_f64() / self.total_token_amount.as_f64())
    }

    /// Merge two price results together
    pub fn merge(&mut self, other: &Self) {
        self.total_token_amount += other.total_token_amount;
        self.total_usdc_amount += other.total_usdc_amount;
        self.transaction_count += other.transaction_count;
    }

    /// Get the total token amount
    pub fn total_token_amount(&self) -> NormalizedAmount {
        self.total_token_amount
    }

    /// Get the total USDC amount
    pub fn total_usdc_amount(&self) -> UsdValue {
        self.total_usdc_amount
    }

    /// Get the transaction count
    pub fn transaction_count(&self) -> TransactionCount {
        self.transaction_count
    }
}

/// A single raw swap with normalized amounts and transaction metadata.
///
/// This struct provides per-transaction granularity for swap data,
/// useful when you need individual swap details rather than aggregated totals.
#[derive(Debug, Clone, Serialize)]
pub struct RawSwapResult {
    /// The raw swap data from the DEX event
    pub swap: SwapData,
    /// Normalized amount of input token (accounting for decimals)
    pub normalized_token_in_amount: NormalizedAmount,
    /// Normalized amount of output token (accounting for decimals)
    pub normalized_token_out_amount: NormalizedAmount,
    /// Decimals for the input token
    pub token_in_decimals: TokenDecimals,
    /// Decimals for the output token
    pub token_out_decimals: TokenDecimals,
}

impl RawSwapResult {
    /// Get the transaction hash if available
    pub fn tx_hash(&self) -> Option<B256> {
        self.swap.tx_hash
    }

    /// Get the block number if available
    pub fn block_number(&self) -> Option<BlockNumber> {
        self.swap.block_number
    }

    /// Get the sender address if available
    pub fn sender(&self) -> Option<Address> {
        self.swap.sender
    }
}

/// Calculates token prices from blockchain swap events using a configurable price source.
///
/// This calculator fetches swap events from the blockchain, extracts price information,
/// and provides caching to minimize RPC calls. It's designed to work with any DEX protocol
/// through the [`PriceSource`] trait.
///
/// # Performance with CallBatchLayer
///
/// For optimal performance, construct your provider with Alloy's `CallBatchLayer`.
/// This automatically batches concurrent `eth_call` requests (like token decimals
/// fetches) into a single Multicall3 RPC request:
///
/// ```rust,ignore
/// use alloy_provider::{layers::CallBatchLayer, ProviderBuilder};
/// use std::time::Duration;
///
/// let provider = ProviderBuilder::new()
///     .layer(CallBatchLayer::new().wait(Duration::from_millis(10)))
///     .connect_http(rpc_url);
///
/// let calculator = PriceCalculator::new(provider, chain, usdc_address, price_source);
/// ```
///
/// Without `CallBatchLayer`, the calculator still benefits from parallel fetching
/// but each call is sent as a separate RPC request.
///
/// # Caching and Thread Safety
///
/// The calculator uses an internal cache (protected by a mutex) to store price results
/// for block ranges. This cache is thread-safe and can be shared across async tasks.
///
/// **Panic Behavior**: If a panic occurs while holding the cache mutex lock, the mutex
/// will become "poisoned" and subsequent operations will panic with a descriptive error
/// message. This is an intentional fail-fast behavior, as mutex poisoning indicates a
/// serious bug in the price calculation logic that should be investigated.
///
/// # Examples
///
/// See [`PriceCalculator::new`] for usage examples.
pub struct PriceCalculator<P> {
    provider: P,
    price_source: Box<dyn PriceSource>,
    usdc_address: Address,
    chain: NamedChain,
    token_decimals_cache: HashMap<Address, TokenDecimals>,
    price_cache: Mutex<PriceCache>,
    config: SemioscanConfig,
}

impl<P: Provider + Clone> PriceCalculator<P> {
    /// Create a new PriceCalculator with a custom price source
    ///
    /// # Arguments
    ///
    /// * `provider` - Blockchain provider for querying logs and token data
    /// * `usdc_address` - Address of the stablecoin to calculate prices against
    /// * `price_source` - Implementation of PriceSource trait for extracting swap data
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use semioscan::price::odos::OdosPriceSource;
    /// use semioscan::price_calculator::PriceCalculator;
    ///
    /// let price_source = OdosPriceSource::new(router_address)
    ///     .with_liquidator_filter(liquidator_address);
    /// let calculator = PriceCalculator::new(provider, usdc_address, Box::new(price_source));
    /// ```
    pub fn new(
        provider: P,
        chain: NamedChain,
        usdc_address: Address,
        price_source: Box<dyn PriceSource>,
    ) -> Self {
        Self::with_config(
            provider,
            chain,
            usdc_address,
            price_source,
            crate::SemioscanConfig::default(),
        )
    }

    /// Create a new PriceCalculator with custom configuration
    ///
    /// # Arguments
    ///
    /// * `provider` - Blockchain provider for querying logs and token data
    /// * `chain` - The blockchain network (used for config lookups)
    /// * `usdc_address` - Address of the stablecoin to calculate prices against
    /// * `price_source` - Implementation of PriceSource trait for extracting swap data
    /// * `config` - Configuration for RPC behavior (block ranges, rate limiting)
    pub fn with_config(
        provider: P,
        chain: NamedChain,
        usdc_address: Address,
        price_source: Box<dyn PriceSource>,
        config: crate::SemioscanConfig,
    ) -> Self {
        Self {
            provider,
            price_source,
            usdc_address,
            chain,
            token_decimals_cache: HashMap::new(),
            price_cache: Default::default(),
            config,
        }
    }

    async fn get_token_decimals(
        &mut self,
        token_address: Address,
    ) -> Result<TokenDecimals, PriceCalculationError> {
        if let Some(&decimals) = self.token_decimals_cache.get(&token_address) {
            return Ok(decimals);
        }

        let token_contract = LazyToken::new(token_address, self.provider.clone());
        let decimals_raw = token_contract
            .decimals()
            .await
            .map_err(|e| PriceCalculationError::metadata_fetch_failed(token_address, e))?;
        let decimals = TokenDecimals::new(*decimals_raw);
        self.token_decimals_cache.insert(token_address, decimals);

        Ok(decimals)
    }

    /// Batch fetch token decimals for multiple addresses in parallel.
    ///
    /// This method fetches decimals for all provided token addresses concurrently,
    /// which significantly reduces RPC latency when processing many tokens.
    ///
    /// When combined with Alloy's `CallBatchLayer`, these parallel calls are
    /// automatically batched into a single Multicall3 RPC request, reducing
    /// network overhead even further.
    ///
    /// Tokens that are already cached are skipped. Tokens that fail to fetch
    /// are logged as warnings but don't cause the entire batch to fail.
    async fn batch_fetch_token_decimals(&mut self, token_addresses: &[Address]) {
        // Filter out already-cached addresses
        let uncached: Vec<Address> = token_addresses
            .iter()
            .filter(|addr| !self.token_decimals_cache.contains_key(*addr))
            .copied()
            .collect();

        if uncached.is_empty() {
            return;
        }

        info!(
            count = uncached.len(),
            "Batch fetching token decimals for uncached tokens"
        );

        // Create futures for all uncached token fetches
        let fetch_futures: Vec<_> = uncached
            .iter()
            .map(|&addr| {
                let provider = self.provider.clone();
                async move {
                    let token_contract = LazyToken::new(addr, provider);
                    let result = token_contract.decimals().await.copied();
                    (addr, result)
                }
            })
            .collect();

        // Execute all fetches in parallel
        // When CallBatchLayer is enabled, these will be automatically batched
        let results = join_all(fetch_futures).await;

        // Process results and update cache
        for (addr, result) in results {
            match result {
                Ok(decimals_raw) => {
                    let decimals = TokenDecimals::new(decimals_raw);
                    self.token_decimals_cache.insert(addr, decimals);
                }
                Err(e) => {
                    warn!(
                        token = ?addr,
                        error = ?e,
                        "Failed to fetch decimals for token, will retry on demand"
                    );
                }
            }
        }
    }

    fn normalize_amount(&self, amount: U256, decimals: TokenDecimals) -> NormalizedAmount {
        TokenAmount::new(amount).normalize(decimals)
    }

    /// Process a single gap by fetching logs with automatic chunking and rate limiting
    ///
    /// Scans the block range for swap events, processes each event to extract price data,
    /// and accumulates results for the token.
    ///
    /// # Performance Optimization
    ///
    /// This method uses a two-pass approach to enable batch RPC calls:
    /// 1. First pass: Extract all swap data from logs and collect unique token addresses
    /// 2. Batch fetch all token decimals in parallel (benefits from `CallBatchLayer`)
    /// 3. Second pass: Process swaps using cached decimals
    ///
    /// When the provider is constructed with `CallBatchLayer`, the parallel decimals
    /// fetches are automatically batched into a single Multicall3 RPC request.
    async fn process_gap_for_price(
        &mut self,
        token_address: Address,
        gap_start: BlockNumber,
        gap_end: BlockNumber,
    ) -> Result<TokenPriceResult, PriceCalculationError> {
        let mut gap_result = TokenPriceResult::new(token_address);
        let event_topics = self.price_source.event_topics();

        // Create a scanner to handle chunking and rate limiting
        let scanner = EventScanner::new(&self.provider, self.config.clone());

        // Build a filter for swap events from the price source
        let filter = Filter::new()
            .address(self.price_source.router_address())
            .event_signature(event_topics.clone());

        // Scan for all swap events in this gap
        let logs = scanner
            .scan(self.chain, filter, gap_start, gap_end)
            .await
            .map_err(|e| {
                PriceCalculationError::processing_failed(format!(
                    "Failed to scan swap events from {gap_start} to {gap_end}: {e}"
                ))
            })?;

        info!(
            logs_count = logs.len(),
            gap_start = gap_start,
            gap_end = gap_end,
            "Fetched logs for gap"
        );

        // First pass: Extract all swap data and collect unique token addresses
        let mut swaps = Vec::new();
        let mut token_addresses = HashSet::new();

        for log in &logs {
            match self.price_source.extract_swap_from_log(log) {
                Ok(Some(swap_data)) => {
                    if !self.price_source.should_include_swap(&swap_data) {
                        continue;
                    }

                    // Check if this swap involves our target token
                    let is_relevant = (swap_data.token_in == token_address
                        && swap_data.token_out == self.usdc_address)
                        || (swap_data.token_in == self.usdc_address
                            && swap_data.token_out == token_address);

                    if is_relevant {
                        // Collect token addresses for batch fetching
                        token_addresses.insert(swap_data.token_in);
                        token_addresses.insert(swap_data.token_out);
                        swaps.push(swap_data);
                    }
                }
                Ok(None) => {
                    // Log is not a relevant swap event
                }
                Err(e @ PriceSourceError::DecodeError(_)) => {
                    error!(error = ?e, "Failed to decode log");
                }
                Err(
                    e @ (PriceSourceError::EmptyTokenArrays
                    | PriceSourceError::ArrayLengthMismatch { .. }
                    | PriceSourceError::InvalidSwapData { .. }),
                ) => {
                    error!(error = ?e, "Invalid swap data in log");
                }
            }
        }

        // Batch fetch all token decimals in parallel
        // When CallBatchLayer is enabled, these parallel calls are automatically
        // batched into a single Multicall3 RPC request
        let addresses: Vec<Address> = token_addresses.into_iter().collect();
        self.batch_fetch_token_decimals(&addresses).await;

        // Second pass: Process swaps using cached decimals
        for swap_data in swaps {
            match self.process_swap_data(&swap_data, token_address).await {
                Ok(Some(amounts)) => {
                    gap_result
                        .add_swap(amounts.token_amount.as_f64(), amounts.usdc_amount.as_f64());
                }
                Ok(None) => {
                    // Not relevant for our token (shouldn't happen since we filtered above)
                }
                Err(e) => {
                    error!(error = ?e, "Error processing swap data");
                }
            }
        }

        Ok(gap_result)
    }

    async fn process_swap_data(
        &mut self,
        swap: &crate::price::SwapData,
        token_address: Address,
    ) -> Result<Option<SwapAmounts>, PriceCalculationError> {
        // Check if this swap involves our target token being sold for USDC
        if swap.token_in == token_address && swap.token_out == self.usdc_address {
            let token_decimals = self.get_token_decimals(token_address).await?;
            let usdc_decimals = self.get_token_decimals(self.usdc_address).await?;

            let token_amount = self.normalize_amount(swap.token_in_amount, token_decimals);
            let usdc_amount = self.normalize_amount(swap.token_out_amount, usdc_decimals);

            return Ok(Some(SwapAmounts {
                token_amount,
                usdc_amount: UsdValue::new(usdc_amount.as_f64()),
            }));
        }

        // Check if this swap involves USDC being sold for our target token (reverse direction)
        // This provides price information too: if someone buys our token with USDC
        if swap.token_in == self.usdc_address && swap.token_out == token_address {
            let token_decimals = self.get_token_decimals(token_address).await?;
            let usdc_decimals = self.get_token_decimals(self.usdc_address).await?;

            let token_amount = self.normalize_amount(swap.token_out_amount, token_decimals);
            let usdc_amount = self.normalize_amount(swap.token_in_amount, usdc_decimals);

            return Ok(Some(SwapAmounts {
                token_amount,
                usdc_amount: UsdValue::new(usdc_amount.as_f64()),
            }));
        }

        Ok(None)
    }

    pub async fn calculate_price_between_blocks(
        &mut self,
        token_address: Address,
        start_block: BlockNumber,
        end_block: BlockNumber,
    ) -> Result<TokenPriceResult, PriceCalculationError> {
        info!(
            token_address = ?token_address,
            start_block = start_block,
            end_block = end_block,
            "Starting price calculation"
        );

        // Check cache and calculate gaps that need to be filled
        let (cached_result, gaps) = {
            let cache = self.price_cache.lock().expect(
                "Price cache mutex poisoned - indicates a panic occurred while holding the lock",
            );
            cache.calculate_gaps(token_address, start_block, end_block)
        };

        // If there are no gaps, we can return the cached result
        if let Some(result) = cached_result.clone() {
            if gaps.is_empty() {
                info!(
                    token_address = ?token_address,
                    "Using complete cached result for block range"
                );
                return Ok(result);
            }
        }

        // Initialize with any cached data or create new result
        let mut price_data = cached_result.unwrap_or_else(|| TokenPriceResult::new(token_address));

        // Process each gap
        for gap in gaps {
            info!(
                token_address = ?token_address,
                gap_start = gap.start,
                gap_end = gap.end,
                "Processing uncached block range"
            );

            // Process the gap by fetching logs in chunks with rate limiting
            let gap_result = self
                .process_gap_for_price(token_address, gap.start, gap.end)
                .await?;

            // Cache the gap result
            {
                let mut cache = self.price_cache.lock()
                    .expect("Price cache mutex poisoned - indicates a panic occurred while holding the lock");
                cache.insert(token_address, gap.start, gap.end, gap_result.clone());
            }

            // Merge the gap result with our main result
            price_data.merge(&gap_result);
        }

        // Cache the complete result
        {
            let mut cache = self.price_cache.lock().expect(
                "Price cache mutex poisoned - indicates a panic occurred while holding the lock",
            );
            cache.insert(token_address, start_block, end_block, price_data.clone());
        }

        info!(
            token_address = ?token_address,
            total_token_amount = price_data.total_token_amount.as_f64(),
            total_usdc_amount = price_data.total_usdc_amount.as_f64(),
            transaction_count = price_data.transaction_count.as_usize(),
            "Finished price calculation"
        );

        Ok(price_data)
    }

    /// Extract raw swap data per transaction from a block range.
    ///
    /// Unlike [`calculate_price_between_blocks`](Self::calculate_price_between_blocks) which
    /// returns aggregated totals, this method returns individual swap data for each transaction.
    /// This is useful when you need per-transaction granularity, such as for fee calculations
    /// or detailed swap analysis.
    ///
    /// # Arguments
    ///
    /// * `start_block` - The starting block number (inclusive)
    /// * `end_block` - The ending block number (inclusive)
    ///
    /// # Returns
    ///
    /// A vector of `RawSwapResult` containing each swap with normalized amounts and metadata.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let swaps = calculator.extract_raw_swaps(start_block, end_block).await?;
    ///
    /// for swap in swaps {
    ///     println!(
    ///         "Tx: {:?}, Token In: {:?}, Amount: {}",
    ///         swap.tx_hash(),
    ///         swap.swap.token_in,
    ///         swap.normalized_token_in_amount.as_f64()
    ///     );
    /// }
    /// ```
    pub async fn extract_raw_swaps(
        &mut self,
        start_block: BlockNumber,
        end_block: BlockNumber,
    ) -> Result<Vec<RawSwapResult>, PriceCalculationError> {
        info!(
            start_block = start_block,
            end_block = end_block,
            "Extracting raw swaps"
        );

        let event_topics = self.price_source.event_topics();

        // Create a scanner to handle chunking and rate limiting
        let scanner = EventScanner::new(&self.provider, self.config.clone());

        // Build a filter for swap events from the price source
        let filter = Filter::new()
            .address(self.price_source.router_address())
            .event_signature(event_topics.clone());

        // Scan for all swap events in this range
        let logs = scanner
            .scan(self.chain, filter, start_block, end_block)
            .await
            .map_err(|e| {
                PriceCalculationError::processing_failed(format!(
                    "Failed to scan swap events from {start_block} to {end_block}: {e}"
                ))
            })?;

        info!(
            logs_count = logs.len(),
            start_block = start_block,
            end_block = end_block,
            "Fetched logs for raw swap extraction"
        );

        // First pass: Extract all swap data and collect unique token addresses
        let mut swaps = Vec::new();
        let mut token_addresses = HashSet::new();

        for log in &logs {
            match self.price_source.extract_swap_from_log(log) {
                Ok(Some(swap_data)) => {
                    if !self.price_source.should_include_swap(&swap_data) {
                        continue;
                    }

                    // Collect token addresses for batch fetching
                    token_addresses.insert(swap_data.token_in);
                    token_addresses.insert(swap_data.token_out);
                    swaps.push(swap_data);
                }
                Ok(None) => {
                    // Log is not a relevant swap event
                }
                Err(e @ PriceSourceError::DecodeError(_)) => {
                    error!(error = ?e, "Failed to decode log");
                }
                Err(
                    e @ (PriceSourceError::EmptyTokenArrays
                    | PriceSourceError::ArrayLengthMismatch { .. }
                    | PriceSourceError::InvalidSwapData { .. }),
                ) => {
                    error!(error = ?e, "Invalid swap data in log");
                }
            }
        }

        // Batch fetch all token decimals in parallel
        let addresses: Vec<Address> = token_addresses.into_iter().collect();
        self.batch_fetch_token_decimals(&addresses).await;

        // Second pass: Create RawSwapResult with normalized amounts
        let mut results = Vec::with_capacity(swaps.len());
        for swap in swaps {
            // Get decimals for both tokens
            let token_in_decimals = match self.get_token_decimals(swap.token_in).await {
                Ok(d) => d,
                Err(e) => {
                    warn!(token = ?swap.token_in, error = ?e, "Failed to get decimals for token_in, skipping swap");
                    continue;
                }
            };

            let token_out_decimals = match self.get_token_decimals(swap.token_out).await {
                Ok(d) => d,
                Err(e) => {
                    warn!(token = ?swap.token_out, error = ?e, "Failed to get decimals for token_out, skipping swap");
                    continue;
                }
            };

            let normalized_token_in =
                self.normalize_amount(swap.token_in_amount, token_in_decimals);
            let normalized_token_out =
                self.normalize_amount(swap.token_out_amount, token_out_decimals);

            results.push(RawSwapResult {
                swap,
                normalized_token_in_amount: normalized_token_in,
                normalized_token_out_amount: normalized_token_out,
                token_in_decimals,
                token_out_decimals,
            });
        }

        info!(swap_count = results.len(), "Finished raw swap extraction");

        Ok(results)
    }
}

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

    #[test]
    fn test_add_swap_accumulates_amounts() {
        let token = address!("1111111111111111111111111111111111111111");
        let mut result = TokenPriceResult::new(token);

        // Add first swap
        result.add_swap(100.0, 200.0);
        assert_eq!(result.total_token_amount().as_f64(), 100.0);
        assert_eq!(result.total_usdc_amount().as_f64(), 200.0);
        assert_eq!(result.transaction_count().as_usize(), 1);

        // Add second swap
        result.add_swap(50.0, 75.0);
        assert_eq!(result.total_token_amount().as_f64(), 150.0);
        assert_eq!(result.total_usdc_amount().as_f64(), 275.0);
        assert_eq!(result.transaction_count().as_usize(), 2);
    }

    #[test]
    fn test_get_average_price_normal_case() {
        let token = address!("1111111111111111111111111111111111111111");
        let mut result = TokenPriceResult::new(token);

        // Add swaps with known prices
        // Swap 1: 100 tokens for 200 USDC = $2.00 per token
        result.add_swap(100.0, 200.0);
        // Swap 2: 50 tokens for 150 USDC = $3.00 per token
        result.add_swap(50.0, 150.0);

        // Average: 350 USDC / 150 tokens = $2.333... per token
        let avg_price = result.get_average_price();
        assert!((avg_price.as_f64() - 2.333333).abs() < 0.0001);
    }

    #[test]
    fn test_get_average_price_zero_volume() {
        let token = address!("1111111111111111111111111111111111111111");
        let result = TokenPriceResult::new(token);

        // Edge case: no volume should return 0.0, not panic
        assert_eq!(result.get_average_price(), TokenPrice::ZERO);
    }

    #[test]
    fn test_get_average_price_zero_token_amount_after_swaps() {
        let token = address!("1111111111111111111111111111111111111111");
        let mut result = TokenPriceResult::new(token);

        // Edge case: USDC amount but zero token amount
        // This shouldn't happen in practice but we handle it gracefully
        result.add_swap(0.0, 100.0);
        assert_eq!(result.get_average_price(), TokenPrice::ZERO);
    }

    #[test]
    fn test_merge_combines_results() {
        let token = address!("1111111111111111111111111111111111111111");

        let mut result1 = TokenPriceResult::new(token);
        result1.add_swap(100.0, 200.0);
        result1.add_swap(50.0, 100.0);

        let mut result2 = TokenPriceResult::new(token);
        result2.add_swap(25.0, 50.0);

        // Merge result2 into result1
        result1.merge(&result2);

        // Check combined values
        assert_eq!(result1.total_token_amount().as_f64(), 175.0); // 100 + 50 + 25
        assert_eq!(result1.total_usdc_amount().as_f64(), 350.0); // 200 + 100 + 50
        assert_eq!(result1.transaction_count().as_usize(), 3);
    }

    #[test]
    fn test_merge_with_empty_result() {
        let token = address!("1111111111111111111111111111111111111111");

        let mut result = TokenPriceResult::new(token);
        result.add_swap(100.0, 200.0);

        let empty = TokenPriceResult::new(token);

        // Merge empty result should not change values
        result.merge(&empty);

        assert_eq!(result.total_token_amount().as_f64(), 100.0);
        assert_eq!(result.total_usdc_amount().as_f64(), 200.0);
        assert_eq!(result.transaction_count().as_usize(), 1);
    }

    #[test]
    fn test_merge_two_empty_results() {
        let token = address!("1111111111111111111111111111111111111111");

        let mut result1 = TokenPriceResult::new(token);
        let result2 = TokenPriceResult::new(token);

        result1.merge(&result2);

        assert_eq!(result1.total_token_amount().as_f64(), 0.0);
        assert_eq!(result1.total_usdc_amount().as_f64(), 0.0);
        assert_eq!(result1.transaction_count().as_usize(), 0);
        assert_eq!(result1.get_average_price(), TokenPrice::ZERO);
    }

    #[test]
    fn test_large_amounts() {
        let token = address!("1111111111111111111111111111111111111111");
        let mut result = TokenPriceResult::new(token);

        // Test with large amounts (billions of dollars)
        result.add_swap(1_000_000_000.0, 2_000_000_000.0);
        result.add_swap(500_000_000.0, 1_000_000_000.0);

        assert_eq!(result.total_token_amount().as_f64(), 1_500_000_000.0);
        assert_eq!(result.total_usdc_amount().as_f64(), 3_000_000_000.0);
        assert_eq!(result.get_average_price().as_f64(), 2.0);
    }

    #[test]
    fn test_fractional_amounts() {
        let token = address!("1111111111111111111111111111111111111111");
        let mut result = TokenPriceResult::new(token);

        // Test with small fractional amounts
        result.add_swap(0.001, 0.002);
        result.add_swap(0.0005, 0.001);

        assert!((result.total_token_amount().as_f64() - 0.0015).abs() < 1e-10);
        assert!((result.total_usdc_amount().as_f64() - 0.003).abs() < 1e-10);
        assert!((result.get_average_price().as_f64() - 2.0).abs() < 1e-6);
    }

    #[test]
    fn test_normalize_amount_standard_decimals() {
        // Test normalize_amount logic directly without needing a provider
        // This tests the business logic of decimal normalization

        // Test USDC (6 decimals): 1,000,000 raw = 1.0 USDC
        let divisor = U256::from(10u64.pow(6));
        let normalized = f64::from(U256::from(1_000_000u64)) / f64::from(divisor);
        assert_eq!(normalized, 1.0);

        // Test WETH (18 decimals): 1e18 raw = 1.0 ETH
        let divisor = U256::from(10u128.pow(18));
        let normalized = f64::from(U256::from(1_000_000_000_000_000_000u64)) / f64::from(divisor);
        assert_eq!(normalized, 1.0);
    }

    #[test]
    fn test_normalize_amount_edge_cases() {
        // Test normalize_amount logic without needing a provider

        // Zero amount
        let divisor = U256::from(10u128.pow(18));
        let normalized = f64::from(U256::ZERO) / f64::from(divisor);
        assert_eq!(normalized, 0.0);

        // Zero decimals (like some weird tokens)
        let divisor = U256::from(10u64.pow(0)); // = 1
        let normalized = f64::from(U256::from(42u64)) / f64::from(divisor);
        assert_eq!(normalized, 42.0);

        // 1 decimal
        let divisor = U256::from(10u64.pow(1));
        let normalized = f64::from(U256::from(100u64)) / f64::from(divisor);
        assert_eq!(normalized, 10.0);
    }

    #[test]
    fn test_average_price_calculation() {
        let token = address!("1111111111111111111111111111111111111111");

        // Manually set values to simulate swap processing
        let result = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(100.0),
            total_usdc_amount: UsdValue::new(200.0),
            transaction_count: TransactionCount::new(5),
        };

        // Average price = 200.0 / 100.0 = 2.0 USDC per token
        assert_eq!(result.get_average_price().as_f64(), 2.0);
    }

    #[test]
    fn test_average_price_fractional() {
        let token = address!("1111111111111111111111111111111111111111");
        let result = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(333.33),
            total_usdc_amount: UsdValue::new(999.99),
            transaction_count: TransactionCount::new(10),
        };

        // Average price ≈ 3.0
        let price = result.get_average_price();
        assert!(
            (price.as_f64() - 3.0).abs() < 0.01,
            "Expected ~3.0, got {}",
            price.as_f64()
        );
    }

    #[test]
    fn test_price_result_multiple_merges() {
        let token = address!("1111111111111111111111111111111111111111");

        let mut total = TokenPriceResult::new(token);

        // Merge three results
        let r1 = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(10.0),
            total_usdc_amount: UsdValue::new(20.0),
            transaction_count: TransactionCount::new(1),
        };

        let r2 = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(20.0),
            total_usdc_amount: UsdValue::new(40.0),
            transaction_count: TransactionCount::new(2),
        };

        let r3 = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(30.0),
            total_usdc_amount: UsdValue::new(60.0),
            transaction_count: TransactionCount::new(3),
        };

        total.merge(&r1);
        total.merge(&r2);
        total.merge(&r3);

        assert_eq!(total.total_token_amount().as_f64(), 60.0);
        assert_eq!(total.total_usdc_amount().as_f64(), 120.0);
        assert_eq!(total.transaction_count().as_usize(), 6);
        assert_eq!(total.get_average_price().as_f64(), 2.0);
    }

    #[test]
    fn test_price_calculation_high_precision() {
        let token = address!("1111111111111111111111111111111111111111");

        let result = TokenPriceResult {
            token_address: token,
            total_token_amount: NormalizedAmount::new(0.000001), // Very small amount
            total_usdc_amount: UsdValue::new(0.00000123),        // Even smaller USDC amount
            transaction_count: TransactionCount::new(1),
        };

        let price = result.get_average_price();
        // Price = 0.00000123 / 0.000001 = 1.23
        assert!(
            (price.as_f64() - 1.23).abs() < 0.001,
            "Expected ~1.23, got {}",
            price.as_f64()
        );
    }
}