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
pub mod errors;
pub mod lazy;
pub mod uniswap_v2;
pub mod uniswap_v3;

use std::{future::Future, sync::Arc};

use alloy_primitives::{Address, Log};
use async_trait::async_trait;
use brontes_types::{normalized_actions::Action, pair::Pair, traits::TracingProvider};
pub use brontes_types::{queries::make_call_request, Protocol};
use malachite::Rational;
use tracing::{debug, warn};

use crate::{
    lazy::{PoolFetchError, PoolFetchSuccess},
    protocols::errors::{AmmError, ArithmeticError},
    types::PairWithFirstPoolHop,
    uniswap_v2::UniswapV2Pool,
    uniswap_v3::UniswapV3Pool,
    LoadResult, PoolState,
};

#[async_trait]
pub trait UpdatableProtocol {
    fn address(&self) -> Address;
    fn tokens(&self) -> Vec<Address>;
    fn calculate_price(&self, base_token: Address) -> Result<Rational, ArithmeticError>;
    fn sync_from_action(&mut self, action: Action) -> Result<(), AmmError>;
    fn sync_from_log(&mut self, log: Log) -> Result<(), AmmError>;
}

pub trait LoadState {
    fn has_state_updater(&self) -> bool;
    fn try_load_state<T: TracingProvider>(
        self,
        address: Address,
        provider: Arc<T>,
        block_number: u64,
        pool_pair: Pair,
        full_pair: PairWithFirstPoolHop,
    ) -> impl Future<Output = Result<PoolFetchSuccess, PoolFetchError>> + Send;
}

impl LoadState for Protocol {
    fn has_state_updater(&self) -> bool {
        matches!(
            self,
            Self::UniswapV2
                | Self::UniswapV3
                | Self::SushiSwapV2
                | Self::SushiSwapV3
                | Self::PancakeSwapV2
                | Self::PancakeSwapV3
        )
    }

    async fn try_load_state<T: TracingProvider>(
        self,
        address: Address,
        provider: Arc<T>,
        block_number: u64,
        pool_pair: Pair,
        fp: PairWithFirstPoolHop,
    ) -> Result<PoolFetchSuccess, PoolFetchError> {
        match self {
            Self::UniswapV2 | Self::SushiSwapV2 | Self::PancakeSwapV2 => {
                let (pool, res) = if let Ok(pool) =
                    UniswapV2Pool::new_load_on_block(address, provider.clone(), block_number - 1)
                        .await
                {
                    (pool, LoadResult::Ok)
                } else {
                    (
                        UniswapV2Pool::new_load_on_block(address, provider, block_number)
                            .await
                            .map_err(|e| {
                                debug!(?pool_pair,protocol=%self, %block_number, pool_address=?address, err=%e, "lazy load failed");
                                (address, Protocol::UniswapV2, block_number, pool_pair, fp, e)
                            })?,
                        LoadResult::PoolInitOnBlock,
                    )
                };

                Ok((
                    block_number,
                    address,
                    PoolState::new(
                        crate::types::PoolVariants::UniswapV2(Box::new(pool)),
                        block_number,
                    ),
                    res,
                ))
            }
            Self::UniswapV3 | Self::SushiSwapV3 | Self::PancakeSwapV3 => {
                let (pool, res) = if let Ok(pool) =
                    UniswapV3Pool::new_from_address(address, block_number - 1, provider.clone())
                        .await
                {
                    (pool, LoadResult::Ok)
                } else {
                    (
                        UniswapV3Pool::new_from_address(address, block_number, provider)
                            .await
                            .map_err(|e| {
                                debug!(?pool_pair, protocol=%self, %block_number, pool_address=?address, err=%e, "lazy load failed");
                                (address, Protocol::UniswapV3, block_number, pool_pair, fp, e)
                            })?,
                        LoadResult::PoolInitOnBlock,
                    )
                };

                Ok((
                    block_number,
                    address,
                    PoolState::new(
                        crate::types::PoolVariants::UniswapV3(Box::new(pool)),
                        block_number,
                    ),
                    res,
                ))
            }
            rest => {
                warn!(protocol=?rest, "no state updater is build for");
                Err((address, self, block_number, pool_pair, fp, AmmError::UnsupportedProtocol))
            }
        }
    }
}