Skip to main content

tycho_simulation/evm/protocol/aerodrome_v1/
decoder.rs

1use std::collections::HashMap;
2
3use alloy::primitives::U256;
4use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
5use tycho_common::{models::token::Token, Bytes};
6
7use crate::{
8    evm::protocol::aerodrome_v1::state::AerodromeV1State,
9    protocol::{
10        errors::InvalidSnapshotError,
11        models::{DecoderContext, TryFromWithBlock},
12    },
13};
14
15impl TryFromWithBlock<ComponentWithState, BlockHeader> for AerodromeV1State {
16    type Error = InvalidSnapshotError;
17
18    /// Decodes a `ComponentWithState` into an `AerodromeV1State`. Errors with an
19    /// `InvalidSnapshotError` if any required attribute is missing.
20    async fn try_from_with_header(
21        snapshot: ComponentWithState,
22        _block: BlockHeader,
23        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
24        all_tokens: &HashMap<Bytes, Token>,
25        _decoder_context: &DecoderContext,
26    ) -> Result<Self, Self::Error> {
27        let reserve0 = U256::from_be_slice(
28            snapshot
29                .state
30                .attributes
31                .get("reserve0")
32                .ok_or(InvalidSnapshotError::MissingAttribute("reserve0".to_string()))?,
33        );
34        let reserve1 = U256::from_be_slice(
35            snapshot
36                .state
37                .attributes
38                .get("reserve1")
39                .ok_or(InvalidSnapshotError::MissingAttribute("reserve1".to_string()))?,
40        );
41        let stable = snapshot
42            .component
43            .static_attributes
44            .get("is_stable")
45            .ok_or(InvalidSnapshotError::MissingAttribute("is_stable".to_string()))?
46            .first() ==
47            Some(&1);
48
49        let fee = snapshot
50            .state
51            .attributes
52            .get("fee")
53            .map(|fee| u32::try_from(fee.clone()))
54            .transpose()?
55            .unwrap_or(0);
56
57        if fee > 10_000 {
58            return Err(InvalidSnapshotError::ValueError(format!(
59                "Invalid fee value {fee}, expected <= 10000 bps"
60            )));
61        }
62
63        let token0 = all_tokens
64            .get(&snapshot.component.tokens[0])
65            .ok_or_else(|| InvalidSnapshotError::ValueError("Token0 not found".to_string()))?;
66        let token1 = all_tokens
67            .get(&snapshot.component.tokens[1])
68            .ok_or_else(|| InvalidSnapshotError::ValueError("Token1 not found".to_string()))?;
69
70        let decimals0 = u8::try_from(token0.decimals).map_err(|e| {
71            InvalidSnapshotError::ValueError(format!("Token0 decimals out of range: {e}"))
72        })?;
73        let decimals1 = u8::try_from(token1.decimals).map_err(|e| {
74            InvalidSnapshotError::ValueError(format!("Token1 decimals out of range: {e}"))
75        })?;
76
77        Ok(Self::new(reserve0, reserve1, stable, fee, decimals0, decimals1))
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use std::collections::HashMap;
84
85    use alloy::primitives::U256;
86    use rstest::rstest;
87    use tycho_client::feed::synchronizer::ComponentWithState;
88    use tycho_common::{
89        models::{protocol::ProtocolComponentState, token::Token, Chain},
90        simulation::protocol_sim::ProtocolSim,
91        Bytes,
92    };
93
94    use super::super::state::AerodromeV1State;
95    use crate::protocol::{errors::InvalidSnapshotError, models::TryFromWithBlock};
96
97    fn token_keys() -> (Bytes, Bytes) {
98        let token0 = Bytes::from([0_u8; 20]);
99        let mut addr = [0_u8; 20];
100        addr[19] = 1;
101        let token1 = Bytes::from(addr);
102        (token0, token1)
103    }
104
105    fn tokens() -> HashMap<Bytes, Token> {
106        let (token0_addr, token1_addr) = token_keys();
107        let token0 = Token::new(&token0_addr, "T0", 18, 0, &[Some(10_000)], Chain::Ethereum, 100);
108        let token1 = Token::new(&token1_addr, "T1", 6, 0, &[Some(10_000)], Chain::Ethereum, 100);
109        HashMap::from([(token0.address.clone(), token0), (token1.address.clone(), token1)])
110    }
111
112    #[tokio::test]
113    async fn test_aerodrome_v1_try_from() {
114        let (token0, token1) = token_keys();
115        let snapshot = ComponentWithState {
116            state: ProtocolComponentState {
117                component_id: "State1".to_owned(),
118                attributes: HashMap::from([
119                    ("reserve0".to_string(), Bytes::from(vec![0; 32])),
120                    ("reserve1".to_string(), Bytes::from(vec![0; 32])),
121                ]),
122                balances: HashMap::new(),
123            },
124            component: tycho_common::models::protocol::ProtocolComponent {
125                tokens: vec![token0, token1],
126                static_attributes: HashMap::from([("is_stable".to_string(), Bytes::from(vec![0]))]),
127                ..Default::default()
128            },
129            component_tvl: None,
130            entrypoints: Vec::new(),
131        };
132
133        let result = AerodromeV1State::try_from_with_header(
134            snapshot,
135            Default::default(),
136            &HashMap::default(),
137            &tokens(),
138            &Default::default(),
139        )
140        .await;
141
142        assert!(result.is_ok());
143        assert_eq!(
144            result.unwrap(),
145            AerodromeV1State::new(U256::from(0u64), U256::from(0u64), false, 0, 18, 6)
146        );
147    }
148
149    #[tokio::test]
150    #[rstest]
151    #[case::missing_reserve0("reserve0")]
152    #[case::missing_reserve1("reserve1")]
153    #[case::missing_is_stable("is_stable")]
154    async fn test_aerodrome_v1_try_from_missing_attribute(#[case] missing_attribute: &str) {
155        let (token0, token1) = token_keys();
156        let mut attributes = HashMap::from([
157            ("reserve0".to_string(), Bytes::from(vec![0; 32])),
158            ("reserve1".to_string(), Bytes::from(vec![0; 32])),
159        ]);
160        let mut static_attributes =
161            HashMap::from([("is_stable".to_string(), Bytes::from(vec![0]))]);
162        match missing_attribute {
163            "reserve0" | "reserve1" => {
164                attributes.remove(missing_attribute);
165            }
166            "is_stable" => {
167                static_attributes.remove(missing_attribute);
168            }
169            #[expect(clippy::unreachable, reason = "the test cases only name the attributes above")]
170            _ => unreachable!("unexpected attribute under test: {missing_attribute}"),
171        }
172
173        let snapshot = ComponentWithState {
174            state: ProtocolComponentState {
175                component_id: "State1".to_owned(),
176                attributes,
177                balances: HashMap::new(),
178            },
179            component: tycho_common::models::protocol::ProtocolComponent {
180                tokens: vec![token0, token1],
181                static_attributes,
182                ..Default::default()
183            },
184            component_tvl: None,
185            entrypoints: Vec::new(),
186        };
187
188        let result = AerodromeV1State::try_from_with_header(
189            snapshot,
190            Default::default(),
191            &HashMap::default(),
192            &tokens(),
193            &Default::default(),
194        )
195        .await;
196
197        assert!(result.is_err());
198        assert!(matches!(
199            result.unwrap_err(),
200            InvalidSnapshotError::MissingAttribute(ref x) if x == missing_attribute
201        ));
202    }
203
204    #[tokio::test]
205    async fn test_aerodrome_v1_try_from_invalid_fee() {
206        let (token0, token1) = token_keys();
207        let snapshot = ComponentWithState {
208            state: ProtocolComponentState {
209                component_id: "State1".to_owned(),
210                attributes: HashMap::from([
211                    ("reserve0".to_string(), Bytes::from(vec![0; 32])),
212                    ("reserve1".to_string(), Bytes::from(vec![0; 32])),
213                    ("fee".to_string(), Bytes::from(10_001_u32.to_be_bytes().to_vec())),
214                ]),
215                balances: HashMap::new(),
216            },
217            component: tycho_common::models::protocol::ProtocolComponent {
218                tokens: vec![token0, token1],
219                static_attributes: HashMap::from([("is_stable".to_string(), Bytes::from(vec![0]))]),
220                ..Default::default()
221            },
222            component_tvl: None,
223            entrypoints: Vec::new(),
224        };
225
226        let result = AerodromeV1State::try_from_with_header(
227            snapshot,
228            Default::default(),
229            &HashMap::default(),
230            &tokens(),
231            &Default::default(),
232        )
233        .await;
234        assert!(matches!(result, Err(InvalidSnapshotError::ValueError(_))));
235    }
236
237    #[tokio::test]
238    async fn test_aerodrome_v1_try_from_zero_fee_indicator() {
239        let (token0, token1) = token_keys();
240        let snapshot = ComponentWithState {
241            state: ProtocolComponentState {
242                component_id: "State1".to_owned(),
243                attributes: HashMap::from([
244                    ("reserve0".to_string(), Bytes::from(vec![0; 32])),
245                    ("reserve1".to_string(), Bytes::from(vec![0; 32])),
246                    ("fee".to_string(), Bytes::from(420_u32.to_be_bytes().to_vec())),
247                ]),
248                balances: HashMap::new(),
249            },
250            component: tycho_common::models::protocol::ProtocolComponent {
251                tokens: vec![token0, token1],
252                static_attributes: HashMap::from([("is_stable".to_string(), Bytes::from(vec![1]))]),
253                ..Default::default()
254            },
255            component_tvl: None,
256            entrypoints: Vec::new(),
257        };
258
259        let result = AerodromeV1State::try_from_with_header(
260            snapshot,
261            Default::default(),
262            &HashMap::default(),
263            &tokens(),
264            &Default::default(),
265        )
266        .await;
267
268        assert!(result.is_ok());
269        let state = result.unwrap();
270        assert_eq!(state.fee, 420);
271        assert!(state.stable);
272        assert_eq!(state.fee(), 0.0);
273        assert_eq!(state.decimals0, 18);
274        assert_eq!(state.decimals1, 6);
275    }
276}