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
use std::{
    cmp::{max, min},
    fmt::Display,
    str::FromStr,
};

use alloy_primitives::{wrap_fixed_bytes, Address, FixedBytes};
use clickhouse::Row;
use itertools::Itertools;
use malachite::{
    num::{
        basic::traits::One,
        conversion::{string::options::ToSciOptions, traits::ToSci},
    },
    Natural, Rational,
};
use redefined::Redefined;
use reth_db::DatabaseError;
use rkyv::{Archive, Deserialize as rDeserialize, Serialize as rSerialize};
use serde::{Deserialize, Serialize};
use tracing::debug;

use crate::{
    constants::{ETH_ADDRESS, WETH_ADDRESS},
    db::{clickhouse_serde::dex::dex_quote, redefined_types::malachite::RationalRedefined},
    implement_table_value_codecs_with_zc,
    pair::{Pair, PairRedefined},
    FastHashMap,
};

/// Represents the DEX prices of a token pair before (`pre_state`) and after a
/// transaction (`post_state`)
///
/// The `goes_through` field, indicates the token pair of the pool
/// that generated the action that caused the pricing event.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, Redefined)]
#[redefined_attr(derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Serialize,
    rDeserialize,
    rSerialize,
    Archive
))]
pub struct DexPrices {
    pub pre_state:             Rational,
    pub post_state:            Rational,
    pub pool_liquidity:        Rational,
    /// tells us what variant of pricing for this pool we are looking at
    pub goes_through:          Pair,
    /// lets us know if this price was generated from a transfer. This allows
    /// us to choose a swap that will have a correct goes through for the given
    /// tx over a transfer which will be less accurate on price
    pub is_transfer:           bool,
    /// how many connections (pairs) does the address we are trying to price
    /// have. If it is only 1. then we highly discount the accuracy of the
    /// price.
    pub first_hop_connections: usize,
}

impl Display for DexPrices {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut opt = ToSciOptions::default();
        opt.set_scale(9);
        writeln!(f, "pre state price: {}", self.pre_state.to_sci_with_options(opt))?;
        writeln!(f, "post state price: {}", self.post_state.to_sci_with_options(opt))?;
        writeln!(f, "goes through: {:?}", self.goes_through)?;
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum PriceAt {
    Before,
    After,
    Lowest,
    Highest,
    Average,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum BlockPrice {
    Highest,
    Lowest,
    Average,
}

impl DexPrices {
    pub fn get_price(self, post: PriceAt) -> Rational {
        match post {
            PriceAt::After => self.post_state,
            PriceAt::Before => self.pre_state,
            PriceAt::Lowest => min(self.pre_state, self.post_state),
            PriceAt::Highest => max(self.pre_state, self.post_state),
            PriceAt::Average => (self.pre_state + self.post_state) / Rational::from(2),
        }
    }
}

/// A collection of dex prices for a given block
///
/// Each index in the vec represents a tx index in the block
///
/// For a given transaction, the value is `None` if it doesn't
/// contain any token transfers
#[derive(Debug, Clone, PartialEq, Row, Eq, Deserialize, Serialize)]
pub struct DexQuotes(pub Vec<Option<FastHashMap<Pair, DexPrices>>>);

impl DexQuotes {
    /// This is done as the require tokens for our testing sets
    /// the index to zero
    #[cfg(feature = "test_pricing")]
    pub fn price_at(&self, mut pair: Pair, mut tx: usize) -> Option<DexPrices> {
        if pair.0 == ETH_ADDRESS {
            pair.0 = WETH_ADDRESS;
        }
        if pair.1 == ETH_ADDRESS {
            pair.1 = WETH_ADDRESS;
        }
        let s_idx = tx;

        if pair.0 == pair.1 {
            return Some(DexPrices {
                pre_state:             Rational::ONE,
                post_state:            Rational::ONE,
                pool_liquidity:        Rational::from(1_000_000),
                first_hop_connections: usize::MAX,
                goes_through:          Pair::default(),
                is_transfer:           false,
            })
        }

        loop {
            if let Some(price) = self.get_price(pair, tx) {
                return Some(price.clone())
            }
            if tx == 0 {
                break
            }

            tx -= 1;
        }

        debug!(target: "brontes::missing_pricing",?pair, at_or_before=?s_idx, "no price for pair");

        None
    }

    /// checks for price at the given tx index. if it isn't found, will look for
    /// the price at all previous indexes in the block
    #[cfg(not(feature = "test_pricing"))]
    pub fn price_at(&self, mut pair: Pair, tx: usize) -> Option<DexPrices> {
        if pair.0 == ETH_ADDRESS {
            pair.0 = WETH_ADDRESS;
        }
        if pair.1 == ETH_ADDRESS {
            pair.1 = WETH_ADDRESS;
        }
        let s_idx = tx;

        if pair.0 == pair.1 {
            return Some(DexPrices {
                pre_state:             Rational::ONE,
                post_state:            Rational::ONE,
                first_hop_connections: usize::MAX,
                pool_liquidity:        Rational::from(1_000_000),
                goes_through:          Pair::default(),
                is_transfer:           false,
            })
        }

        if let Some(price) = self.get_price(pair, tx) {
            return Some(price.clone())
        }

        debug!(target: "brontes::missing_pricing",?pair, at=?s_idx, "no price for pair");

        None
    }

    pub fn price_at_or_before(&self, mut pair: Pair, mut tx: usize) -> Option<DexPrices> {
        if pair.0 == ETH_ADDRESS {
            pair.0 = WETH_ADDRESS;
        }
        if pair.1 == ETH_ADDRESS {
            pair.1 = WETH_ADDRESS;
        }
        let s_idx = tx;

        if pair.0 == pair.1 {
            return Some(DexPrices {
                pre_state:             Rational::ONE,
                post_state:            Rational::ONE,
                first_hop_connections: usize::MAX,
                pool_liquidity:        Rational::from(1_000_000),
                goes_through:          Pair::default(),
                is_transfer:           false,
            })
        }

        loop {
            if let Some(price) = self.get_price(pair, tx) {
                return Some(price.clone())
            }
            if tx == 0 {
                break
            }

            tx -= 1;
        }

        debug!(target: "brontes::missing_pricing",?pair, at_or_before=?s_idx, "no price for pair");

        None
    }

    pub fn price_for_block(&self, mut pair: Pair, price_at: BlockPrice) -> Option<Rational> {
        if pair.0 == ETH_ADDRESS {
            pair.0 = WETH_ADDRESS;
        }
        if pair.1 == ETH_ADDRESS {
            pair.1 = WETH_ADDRESS;
        }

        match price_at {
            BlockPrice::Lowest => self
                .0
                .iter()
                .filter_map(|f| f.as_ref())
                .filter_map(|p| {
                    p.get(&pair)
                        .map(|prices| prices.clone().get_price(PriceAt::Lowest))
                })
                .min(),
            BlockPrice::Highest => self
                .0
                .iter()
                .filter_map(|f| f.as_ref())
                .filter_map(|p| {
                    p.get(&pair)
                        .map(|prices| prices.clone().get_price(PriceAt::Highest))
                })
                .max(),
            BlockPrice::Average => {
                let entires = self
                    .0
                    .iter()
                    .filter_map(|f| f.as_ref())
                    .filter_map(|p| {
                        p.get(&pair)
                            .map(|prices| prices.clone().get_price(PriceAt::Average))
                    })
                    .collect_vec();

                if entires.is_empty() {
                    return None
                }

                let len = entires.len();
                Some(entires.into_iter().sum::<Rational>() / Rational::from(len))
            }
        }
    }

    pub fn has_quote(&self, pair: &Pair, tx: usize) -> bool {
        self.0
            .get(tx)
            .and_then(|i| i.as_ref().map(|i| i.get(pair).is_some()))
            .unwrap_or(false)
    }

    fn get_price(&self, mut pair: Pair, tx: usize) -> Option<&DexPrices> {
        if pair.0 == ETH_ADDRESS {
            pair.0 = WETH_ADDRESS;
        }
        if pair.1 == ETH_ADDRESS {
            pair.1 = WETH_ADDRESS;
        }
        self.0.get(tx)?.as_ref()?.get(&pair)
    }
}

impl Display for DexQuotes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, val) in self.0.iter().enumerate() {
            if let Some(val) = val.as_ref() {
                for (pair, am) in val {
                    writeln!(f, "----Price at tx_index: {i}, pair {:?}-----\n {}", pair, am)?;
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DexQuote(pub FastHashMap<Pair, DexPrices>);

impl From<DexQuoteWithIndex> for DexQuote {
    fn from(value: DexQuoteWithIndex) -> Self {
        Self(value.quote.into_iter().collect())
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize, Redefined)]
#[redefined_attr(derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Serialize,
    rDeserialize,
    rSerialize,
    Archive
))]
pub struct DexQuoteWithIndex {
    pub tx_idx: u16,
    pub quote:  Vec<(Pair, DexPrices)>,
}

type DexPriceQuotesVec = (
    u64,
    Vec<(
        (String, String),
        (
            (Vec<u64>, Vec<u64>),
            (Vec<u64>, Vec<u64>),
            (Vec<u64>, Vec<u64>),
            (String, String),
            bool,
            u64,
        ),
    )>,
);

impl<'de> Deserialize<'de> for DexQuoteWithIndex {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let des: DexPriceQuotesVec = Deserialize::deserialize(deserializer)?;

        if des.1.is_empty() {
            return Ok(DexQuoteWithIndex { tx_idx: des.0 as u16, quote: vec![] })
        }

        let val = des
            .1
            .into_iter()
            .map(
                |(
                    (pair0, pair1),
                    ((pre_num, pre_den), (post_num, post_den), (liq_num, liq_den), (g0, g1), t, c),
                )| {
                    (
                        Pair(
                            Address::from_str(&pair0).unwrap(),
                            Address::from_str(&pair1).unwrap(),
                        ),
                        DexPrices {
                            pre_state:             Rational::from_naturals(
                                Natural::from_owned_limbs_asc(pre_num),
                                Natural::from_owned_limbs_asc(pre_den),
                            ),
                            post_state:            Rational::from_naturals(
                                Natural::from_owned_limbs_asc(post_num),
                                Natural::from_owned_limbs_asc(post_den),
                            ),
                            pool_liquidity:        Rational::from_naturals(
                                Natural::from_owned_limbs_asc(liq_num),
                                Natural::from_owned_limbs_asc(liq_den),
                            ),
                            goes_through:          Pair(
                                Address::from_str(&g0).unwrap(),
                                Address::from_str(&g1).unwrap(),
                            ),
                            is_transfer:           t,
                            first_hop_connections: c as usize,
                        },
                    )
                },
            )
            .collect::<Vec<_>>();
        Ok(Self { tx_idx: des.0 as u16, quote: val })
    }
}

impl From<DexQuote> for Vec<(Pair, DexPrices)> {
    fn from(val: DexQuote) -> Self {
        val.0.into_iter().collect()
    }
}

implement_table_value_codecs_with_zc!(DexQuoteWithIndexRedefined);

wrap_fixed_bytes!(
    extra_derives: [],
    pub struct DexKey<10>;
);

impl reth_db::table::Encode for DexKey {
    type Encoded = [u8; 10];

    fn encode(self) -> Self::Encoded {
        self.0 .0
    }
}

impl reth_db::table::Decode for DexKey {
    fn decode<B: AsRef<[u8]>>(value: B) -> Result<Self, DatabaseError> {
        Ok(DexKey::from_slice(value.as_ref()))
    }
}

pub fn decompose_key(key: DexKey) -> (u64, u16) {
    let block = FixedBytes::<8>::from_slice(&key[0..8]);
    let block_number = u64::from_be_bytes(*block);

    let tx_idx = FixedBytes::<2>::from_slice(&key[8..]);
    let tx_idx = u16::from_be_bytes(*tx_idx);

    (block_number, tx_idx)
}

pub fn make_key(block_number: u64, tx_idx: u16) -> DexKey {
    let block_bytes = FixedBytes::new(block_number.to_be_bytes());
    block_bytes.concat_const(tx_idx.to_be_bytes().into()).into()
}

pub fn make_filter_key_range(block_number: u64) -> (DexKey, DexKey) {
    let base = FixedBytes::new(block_number.to_be_bytes());
    let start_key = base.concat_const([0u8; 2].into());
    let end_key = base.concat_const([u8::MAX; 2].into());

    (start_key.into(), end_key.into())
}

#[derive(Debug, Clone, PartialEq, Row, Eq, Deserialize, Serialize)]
pub struct DexQuotesWithBlockNumber {
    pub block_number: u64,
    pub tx_idx:       u64,
    #[serde(with = "dex_quote")]
    pub quote:        Option<FastHashMap<Pair, DexPrices>>,
}

impl DexQuotesWithBlockNumber {
    pub fn new_with_block(block_number: u64, quotes: DexQuotes) -> Vec<Self> {
        quotes
            .0
            .into_iter()
            .enumerate()
            .map(|(i, quote)| DexQuotesWithBlockNumber { block_number, tx_idx: i as u64, quote })
            .collect_vec()
    }
}