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
//! Provides a set of utilities and helpers for testing inspectors within the
//! `brontes-inspect` crate. This includes functions for creating transaction
//! trees, applying pricing information, and running inspectors with various
//! configurations to assert expected MEV (Miner Extractable Value) outcomes.
//!
//! ## Key Components
//!
//! - `InspectorTestUtils`: A struct providing methods to facilitate the testing
//!   of inspectors.
//! - `InspectorTxRunConfig`: Configuration struct for running single
//!   opportunity tests with inspectors.
//! - `ComposerRunConfig`: Configuration struct for running composition tests
//!   across multiple inspectors.
//! - `InspectorTestUtilsError`: Enum defining possible error types that can
//!   occur during test execution.
//!
//! ## Usage
//!
//! Test utilities are primarily used in the context of unit and integration
//! tests to verify the correctness of inspector implementations. They allow for
//! detailed configuration of test scenarios, including specifying transaction
//! hashes, blocks, expected profits, and gas usage, among other parameters.

use alloy_primitives::{Address, TxHash};
use brontes_classifier::test_utils::{ClassifierTestUtils, ClassifierTestUtilsError};
use brontes_core::{LibmdbxReadWriter, TraceLoaderError};
pub use brontes_types::constants::*;
use brontes_types::{
    db::{
        cex::{trades::CexDexTradeConfig, CexExchange},
        dex::DexQuotes,
        metadata::Metadata,
    },
    mev::{Bundle, MevType},
    normalized_actions::Action,
    tree::BlockTree,
    BlockData, MultiBlockData,
};
use thiserror::Error;

use crate::{composer::run_block_inspection, shared_utils::SharedInspectorUtils, Inspectors};

type StateTests = Option<Box<dyn for<'a> Fn(&'a Bundle)>>;

/// Inspector Specific testing functionality
pub struct InspectorTestUtils {
    pub classifier_inspector: ClassifierTestUtils,
    quote_address:            Address,
    max_result_difference:    f64,
}

impl InspectorTestUtils {
    pub async fn new(quote_address: Address, max_result_difference: f64) -> Self {
        let classifier_inspector = ClassifierTestUtils::new().await;
        Self { classifier_inspector, quote_address, max_result_difference }
    }

    async fn get_tree_txes(
        &self,
        tx_hashes: Vec<TxHash>,
    ) -> Result<BlockTree<Action>, InspectorTestUtilsError> {
        let mut trees = self.classifier_inspector.build_tree_txes(tx_hashes).await?;

        if trees.len() != 1 {
            return Err(InspectorTestUtilsError::MultipleBlockError(
                trees.into_iter().map(|t| t.header.number).collect(),
            ))
        }
        Ok(trees.remove(0))
    }

    async fn get_tree_txes_with_pricing(
        &self,
        tx_hashes: Vec<TxHash>,
        needs_tokens: Vec<Address>,
    ) -> Result<(BlockTree<Action>, DexQuotes), InspectorTestUtilsError> {
        let mut trees = self
            .classifier_inspector
            .build_tree_txes_with_pricing(tx_hashes, self.quote_address, needs_tokens)
            .await?;

        if trees.len() != 1 {
            return Err(InspectorTestUtilsError::MultipleBlockError(
                trees.into_iter().map(|(t, _)| t.header.number).collect(),
            ))
        }
        Ok(trees.remove(0))
    }

    async fn get_block_tree(
        &self,
        block: u64,
    ) -> Result<BlockTree<Action>, InspectorTestUtilsError> {
        self.classifier_inspector
            .build_block_tree(block)
            .await
            .map_err(Into::into)
    }

    async fn get_block_tree_with_pricing(
        &self,
        block: u64,
        needs_tokens: Vec<Address>,
    ) -> Result<(BlockTree<Action>, Option<DexQuotes>), InspectorTestUtilsError> {
        self.classifier_inspector
            .build_block_tree_with_pricing(block, self.quote_address, needs_tokens)
            .await
            .map_err(Into::into)
    }

    pub async fn assert_no_mev(
        &self,
        config: InspectorTxRunConfig,
    ) -> Result<(), InspectorTestUtilsError> {
        let copied = config.clone();
        let err = || InspectorTestUtilsError::InspectorConfig(Box::new(copied.clone()));

        let mut quotes = None;
        let tree = if let Some(tx_hashes) = config.mev_tx_hashes {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_tree_txes_with_pricing(tx_hashes, config.needs_tokens)
                    .await?;
                quotes = Some(prices);
                tree
            } else {
                self.get_tree_txes(tx_hashes).await?
            }
        } else if let Some(block) = config.block {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_block_tree_with_pricing(block, config.needs_tokens)
                    .await?;
                quotes = prices;
                tree
            } else {
                self.get_block_tree(block).await?
            }
        } else {
            return Err(err())
        };

        let block = tree.header.number;

        let mut metadata = if let Some(meta) = config.metadata_override {
            meta
        } else {
            self.classifier_inspector
                .get_metadata(block, false)
                .await
                .unwrap_or_default()
        };

        metadata.dex_quotes = quotes;

        if metadata.dex_quotes.is_none() && config.needs_dex_prices {
            panic!("no dex quotes found in metadata. test suite will fail");
        }

        let inspector = config.expected_mev_type.init_mev_inspector(
            self.quote_address,
            self.classifier_inspector.libmdbx,
            &[
                CexExchange::Binance,
                CexExchange::Coinbase,
                CexExchange::Okex,
                CexExchange::BybitSpot,
                CexExchange::Kucoin,
            ],
            CexDexTradeConfig::default(),
            None,
        );
        let data = BlockData { metadata: metadata.into(), tree: tree.into() };
        let multi = MultiBlockData { per_block_data: vec![data], blocks: 1 };
        let results = inspector.inspect_block(multi);

        assert_eq!(results.len(), 0, "found mev when we shouldn't of {:#?}", results);

        Ok(())
    }

    pub async fn run_inspector(
        &self,
        config: InspectorTxRunConfig,
        specific_state_tests: StateTests,
    ) -> Result<(), InspectorTestUtilsError> {
        let copied = config.clone();
        let err = || InspectorTestUtilsError::InspectorConfig(Box::new(copied.clone()));

        let profit_usd = config.expected_profit_usd.ok_or_else(err)?;
        let gas_used_usd = config.expected_gas_usd.ok_or_else(err)?;

        let mut quotes = None;
        let tree = if let Some(tx_hashes) = config.mev_tx_hashes {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_tree_txes_with_pricing(tx_hashes, config.needs_tokens)
                    .await?;
                quotes = Some(prices);
                tree
            } else {
                self.get_tree_txes(tx_hashes).await?
            }
        } else if let Some(block) = config.block {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_block_tree_with_pricing(block, config.needs_tokens)
                    .await?;
                quotes = prices;
                tree
            } else {
                self.get_block_tree(block).await?
            }
        } else {
            return Err(err())
        };

        let mut metadata = if let Some(meta) = config.metadata_override {
            meta
        } else {
            let res = self
                .classifier_inspector
                .get_metadata(tree.header.number, false)
                .await;

            if config.expected_mev_type == Inspectors::CexDexMarkout
                || config.expected_mev_type == Inspectors::CexDex
            {
                res?
            } else {
                res.unwrap_or_else(|_| Metadata::default())
            }
        };

        if metadata.dex_quotes.is_none() {
            metadata.dex_quotes = quotes;
        }

        if metadata.dex_quotes.is_none() && config.needs_dex_prices {
            panic!("no dex quotes found in metadata. test suite will fail");
        }

        let mut cex_trade_config = CexDexTradeConfig::default();

        if config.use_block_time_weights_for_cex_pricing {
            cex_trade_config.with_block_time_weights();
        }

        let inspector = config.expected_mev_type.init_mev_inspector(
            self.quote_address,
            self.classifier_inspector.libmdbx,
            &[
                CexExchange::Binance,
                CexExchange::Coinbase,
                CexExchange::Okex,
                CexExchange::BybitSpot,
                CexExchange::Kucoin,
                CexExchange::Upbit,
            ],
            cex_trade_config,
            None,
        );

        let data = BlockData { metadata: metadata.into(), tree: tree.into() };
        let multi = MultiBlockData { per_block_data: vec![data], blocks: 1 };
        let results = inspector.inspect_block(multi);
        let mut results = SharedInspectorUtils::<LibmdbxReadWriter>::dedup_bundles(results);

        assert_eq!(
            results.len(),
            1,
            "Identified an incorrect number of MEV bundles. Expected 1, found: {:#?}",
            results
        );

        let bundle = results.remove(0);

        if let Some(specific_state_tests) = specific_state_tests {
            specific_state_tests(&bundle);
        }

        // check gas
        assert!(
            (bundle.header.bribe_usd - gas_used_usd).abs() < self.max_result_difference,
            "Finalized Bribe != Expected Bribe, {} != {}",
            bundle.header.bribe_usd,
            gas_used_usd
        );

        // check profit
        assert!(
            (bundle.header.profit_usd - profit_usd).abs() < self.max_result_difference,
            "Finalized Profit != Expected Profit, {} != {}",
            bundle.header.profit_usd,
            profit_usd
        );

        Ok(())
    }

    pub async fn run_composer(
        &self,
        config: ComposerRunConfig,
        specific_state_tests: StateTests,
    ) -> Result<(), InspectorTestUtilsError> {
        let copied = config.clone();
        let err = || InspectorTestUtilsError::ComposerConfig(Box::new(copied.clone()));

        let profit_usd = config.expected_profit_usd.ok_or_else(err)?;
        let gas_used_usd = config.expected_gas_usd.ok_or_else(err)?;

        let mut quotes = None;
        let tree = if let Some(tx_hashes) = config.mev_tx_hashes {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_tree_txes_with_pricing(tx_hashes, config.needs_tokens)
                    .await?;
                quotes = Some(prices);
                tree
            } else {
                self.get_tree_txes(tx_hashes).await?
            }
        } else if let Some(block) = config.block {
            if config.needs_dex_prices {
                let (tree, prices) = self
                    .get_block_tree_with_pricing(block, config.needs_tokens)
                    .await?;
                quotes = prices;
                tree
            } else {
                self.get_block_tree(block).await?
            }
        } else {
            return Err(err())
        };

        let block = tree.header.number;

        let mut metadata = if let Some(meta) = config.metadata_override {
            meta
        } else {
            let res = self.classifier_inspector.get_metadata(block, false).await;

            if config.inspectors.contains(&Inspectors::CexDex)
                || config.inspectors.contains(&Inspectors::CexDexMarkout)
            {
                res?
            } else {
                res.unwrap_or_else(|_| Metadata::default())
            }
        };

        if let Some(quotes) = quotes {
            metadata.dex_quotes = Some(quotes);
        }

        if metadata.dex_quotes.is_none() && config.needs_dex_prices {
            panic!("no dex quotes found in metadata. test suite will fail");
        }

        let inspector = config
            .inspectors
            .into_iter()
            .map(|i| {
                i.init_mev_inspector(
                    self.quote_address,
                    self.classifier_inspector.libmdbx,
                    &[CexExchange::Binance],
                    CexDexTradeConfig::default(),
                    None,
                )
            })
            .collect::<Vec<_>>();
        let db = self.classifier_inspector.trace_loader.libmdbx;
        let data = BlockData { metadata: metadata.into(), tree: tree.into() };
        let multi = MultiBlockData { blocks: 1, per_block_data: vec![data] };

        let results = run_block_inspection(inspector.as_slice(), multi, db);

        let mut results = results
            .mev_details
            .into_iter()
            .filter(|mev| {
                config
                    .prune_opportunities
                    .as_ref()
                    .map(|opp| !opp.contains(&mev.header.tx_hash))
                    .unwrap_or(true)
            })
            .collect::<Vec<_>>();

        assert_eq!(
            results.len(),
            1,
            "Got wrong number of mev bundles. Expected 1, got {}\n {:#?}",
            results.len(),
            results
        );

        let bundle = results.remove(0);
        assert!(
            bundle.header.mev_type == config.expected_mev_type,
            "got wrong composed type {} != {}\n\n\n {:#?}",
            bundle.header.mev_type,
            config.expected_mev_type,
            bundle
        );

        if let Some(specific_state_tests) = specific_state_tests {
            specific_state_tests(&bundle);
        }

        // check gas
        assert!(
            (bundle.header.bribe_usd - gas_used_usd).abs() < self.max_result_difference,
            "Finalized Bribe != Expected Bribe, {} != {}",
            bundle.header.bribe_usd,
            gas_used_usd
        );
        // check profit
        assert!(
            (bundle.header.profit_usd - profit_usd).abs() < self.max_result_difference,
            "Finalized Profit != Expected Profit, {} != {}",
            bundle.header.profit_usd,
            profit_usd
        );

        Ok(())
    }
}

/// This inspector test config is to configure an inspector test for a single
/// bundle. MevTxHashes is a list of tx hashes that are expected be in the
/// bundle.
#[derive(Debug, Clone)]
pub struct InspectorTxRunConfig {
    pub metadata_override: Option<Metadata>,
    pub mev_tx_hashes: Option<Vec<TxHash>>,
    pub block: Option<u64>,
    pub expected_profit_usd: Option<f64>,
    pub expected_gas_usd: Option<f64>,
    pub expected_mev_type: Inspectors,
    pub needs_dex_prices: bool,
    pub needs_tokens: Vec<Address>,
    pub use_block_time_weights_for_cex_pricing: bool,
}

impl InspectorTxRunConfig {
    pub fn new(mev: Inspectors) -> Self {
        Self {
            expected_mev_type: mev,
            block: None,
            mev_tx_hashes: None,
            expected_profit_usd: None,
            expected_gas_usd: None,
            metadata_override: None,
            needs_tokens: Vec::new(),
            needs_dex_prices: false,
            use_block_time_weights_for_cex_pricing: false,
        }
    }

    pub fn needs_tokens(mut self, tokens: Vec<Address>) -> Self {
        self.needs_tokens.extend(tokens);
        self
    }

    pub fn needs_token(mut self, token: Address) -> Self {
        self.needs_tokens.push(token);
        self
    }

    pub fn with_dex_prices(mut self) -> Self {
        self.needs_dex_prices = true;
        self
    }

    pub fn with_block(mut self, block: u64) -> Self {
        self.block = Some(block);
        self
    }

    pub fn with_metadata_override(mut self, metadata: Metadata) -> Self {
        self.metadata_override = Some(metadata);
        self
    }

    pub fn with_mev_tx_hashes(mut self, txes: Vec<TxHash>) -> Self {
        self.mev_tx_hashes = Some(txes);
        self
    }

    pub fn with_expected_profit_usd(mut self, profit: f64) -> Self {
        self.expected_profit_usd = Some(profit);
        self
    }

    /// Total cost of transaction in USD. This includes base fee, priority fee &
    /// bribe
    pub fn with_gas_paid_usd(mut self, gas: f64) -> Self {
        self.expected_gas_usd = Some(gas);
        self
    }

    pub fn with_block_time_weights_for_cex_pricing(mut self) -> Self {
        self.use_block_time_weights_for_cex_pricing = true;
        self
    }
}

#[derive(Debug, Clone)]
pub struct ComposerRunConfig {
    pub inspectors:          Vec<Inspectors>,
    pub expected_mev_type:   MevType,
    pub metadata_override:   Option<Metadata>,
    pub mev_tx_hashes:       Option<Vec<TxHash>>,
    pub block:               Option<u64>,
    pub expected_profit_usd: Option<f64>,
    pub expected_gas_usd:    Option<f64>,
    pub prune_opportunities: Option<Vec<TxHash>>,
    pub needs_dex_prices:    bool,
    pub needs_tokens:        Vec<Address>,
}

impl ComposerRunConfig {
    pub fn new(inspectors: Vec<Inspectors>, expected_mev_type: MevType) -> Self {
        Self {
            inspectors,
            metadata_override: None,
            mev_tx_hashes: None,
            expected_mev_type,
            block: None,
            expected_profit_usd: None,
            expected_gas_usd: None,
            prune_opportunities: None,
            needs_dex_prices: false,
            needs_tokens: Vec::new(),
        }
    }

    pub fn needs_tokens(mut self, tokens: Vec<Address>) -> Self {
        self.needs_tokens.extend(tokens);
        self
    }

    pub fn needs_token(mut self, token: Address) -> Self {
        self.needs_tokens.push(token);
        self
    }

    pub fn with_metadata_override(mut self, metadata: Metadata) -> Self {
        self.metadata_override = Some(metadata);
        self
    }

    pub fn with_mev_tx_hashes(mut self, txes: Vec<TxHash>) -> Self {
        self.mev_tx_hashes = Some(txes);
        self
    }

    pub fn with_block(mut self, block: u64) -> Self {
        self.block = Some(block);
        self
    }

    pub fn with_expected_profit_usd(mut self, profit: f64) -> Self {
        self.expected_profit_usd = Some(profit);
        self
    }

    pub fn with_gas_paid_usd(mut self, gas: f64) -> Self {
        self.expected_gas_usd = Some(gas);
        self
    }

    pub fn with_prune_opportunities(mut self, prune_txes: Vec<TxHash>) -> Self {
        self.prune_opportunities = Some(prune_txes);
        self
    }

    pub fn with_dex_prices(mut self) -> Self {
        self.needs_dex_prices = true;
        self
    }
}

#[derive(Debug, Error)]
pub enum InspectorTestUtilsError {
    #[error(transparent)]
    Classification(#[from] ClassifierTestUtilsError),
    #[error(transparent)]
    Tracing(#[from] TraceLoaderError),
    #[error("invalid inspector tx run config: {0:?}")]
    InspectorConfig(Box<InspectorTxRunConfig>),
    #[error("invalid composer run config: {0:?}")]
    ComposerConfig(Box<ComposerRunConfig>),
    #[error("no inspector for type: {0}")]
    MissingInspector(MevType),
    #[error("more than one block found in inspector config. blocks: {0:?}")]
    MultipleBlockError(Vec<u64>),
}