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
use std::sync::Arc;

use async_trait::async_trait;
use futures::stream::FuturesUnordered;
use serde::{Deserialize, Serialize};
use starknet::{
    core::types::{BlockId, EventFilter, Felt},
    providers::Provider,
};

use super::{jediswap::factory::JediswapFactory, pool::AMM, tenkswap::factory::TenKFactory};
use crate::errors::AMMError;

#[async_trait]
pub trait AutomatedMarketMakerFactory {
    /// Returns the address of the AMM.
    fn address(&self) -> Felt;

    async fn fetch_all_pools<P>(&mut self, provider: Arc<P>) -> Result<Vec<AMM>, AMMError>
    where
        P: Provider + Sync + Send;

    fn amm_created_event_signature(&self) -> Vec<Vec<Felt>>;

    /// Populates all AMMs data via batched static calls.
    async fn populate_amm_data<P>(
        &self,
        amms: &mut [AMM],
        block_number: Option<u64>,
        provider: Arc<P>,
    ) -> Result<(), AMMError>
    where
        P: Provider + Send + Sync;
}

macro_rules! factory {
    ($($factory_type:ident),+ $(,)?) => {
        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub enum Factory {
            $($factory_type($factory_type),)+
        }

        #[async_trait]
        impl AutomatedMarketMakerFactory for Factory {
            fn address(&self) -> Felt{
                match self {
                    $(Factory::$factory_type(pool) => pool.address(),)+
                }
            }


            async fn fetch_all_pools<P>(&mut self, provider: Arc<P>) -> Result<Vec<AMM>, AMMError>
            where
            P: Provider + Sync + Send
            {
                match self {
                        $(Factory::$factory_type(pool) => pool.fetch_all_pools(provider).await,)+
                }
            }

            fn amm_created_event_signature(&self) -> Vec<Vec<Felt>> {
                match self {
                    $(Factory::$factory_type(factory) => factory.amm_created_event_signature(),)+
                }
            }


            async fn populate_amm_data<P>(
                &self,
                amms: &mut [AMM],
                block_number: Option<u64>,
                provider: Arc<P>,
            ) -> Result<(), AMMError>
            where
                P: Provider + Send + Sync
            {
                match self {
                    $(Factory::$factory_type(factory) => {
                        factory.populate_amm_data(amms, block_number, provider).await
                    },)+
                }
            }
        }


        impl PartialEq for Factory {
            fn eq(&self, other: &Self) -> bool {
                self.address() == other.address()
            }
        }

        impl Eq for Factory {}
    };
}

factory!(JediswapFactory, TenKFactory);

impl Factory {
    #[allow(unused)]
    pub async fn get_all_pools_from_logs<P>(
        &self,
        mut from_block: u64,
        to_block: u64,
        step: u64,
        provider: Arc<P>,
    ) -> Result<Vec<AMM>, AMMError>
    where
        P: Provider,
    {
        let factory_address = self.address();
        let amm_created_event_signature = self.amm_created_event_signature();
        let mut futures = FuturesUnordered::new();

        let mut aggregated_amms: Vec<AMM> = vec![];

        while from_block < to_block {
            let provider = provider.clone();
            let mut target_block = from_block + step - 1;
            if target_block > to_block {
                target_block = to_block;
            }

            let filter = EventFilter {
                from_block: Some(BlockId::Number(from_block)),
                to_block: Some(BlockId::Number(to_block)),
                address: Some(factory_address),
                keys: Some(self.amm_created_event_signature()),
            };

            futures.push(async move { provider.get_events(filter, None, 10).await });

            // from_block += step;
        }

        // while let Some(result) = futures.next().await {
        //     let logs = result.map_err(AMMError::TransportError)?;
        //
        //     for log in logs {
        //         aggregated_amms.push(self.new_empty_amm_from_log(log).unwrap());
        //     }
        // }

        Ok(aggregated_amms)
    }
}