Skip to main content

tycho_simulation/evm/protocol/aero_basic/
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::aero_basic::state::{AeroBasicFees, AeroBasicState},
9    protocol::{
10        errors::InvalidSnapshotError,
11        models::{DecoderContext, TryFromWithBlock},
12    },
13};
14
15fn attribute<'a>(
16    attributes: &'a HashMap<String, Bytes>,
17    name: &str,
18) -> Result<&'a Bytes, InvalidSnapshotError> {
19    attributes
20        .get(name)
21        .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_string()))
22}
23
24fn decimals(
25    all_tokens: &HashMap<Bytes, Token>,
26    address: &Bytes,
27) -> Result<u8, InvalidSnapshotError> {
28    all_tokens
29        .get(address)
30        .map(|token| token.decimals as u8)
31        .ok_or_else(|| InvalidSnapshotError::ValueError(format!("Token {address} not found")))
32}
33
34impl TryFromWithBlock<ComponentWithState, BlockHeader> for AeroBasicState {
35    type Error = InvalidSnapshotError;
36
37    /// Decodes an `aero_basic` component. Errors if an attribute the `evm-aero-basic` Substreams
38    /// package always emits is missing, or a token is unknown.
39    async fn try_from_with_header(
40        snapshot: ComponentWithState,
41        _block: BlockHeader,
42        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
43        all_tokens: &HashMap<Bytes, Token>,
44        _decoder_context: &DecoderContext,
45    ) -> Result<Self, Self::Error> {
46        let state = &snapshot.state.attributes;
47        let [token0, token1] = snapshot.component.tokens.as_slice() else {
48            return Err(InvalidSnapshotError::ValueError(format!(
49                "Expected 2 tokens, got {}",
50                snapshot.component.tokens.len()
51            )));
52        };
53        let stable = attribute(&snapshot.component.static_attributes, "is_stable")?.as_ref() == [1];
54        let fees = AeroBasicFees {
55            custom_fee: u32::try_from(attribute(state, "custom_fee")?.clone())?,
56            default_fee: u32::try_from(attribute(state, "default_fee")?.clone())?,
57            fee_module: attribute(state, "fee_module")?.clone(),
58            paused: attribute(state, "paused")?
59                .iter()
60                .any(|byte| *byte != 0),
61        };
62        let reserves = (
63            U256::from_be_slice(attribute(state, "reserve0")?),
64            U256::from_be_slice(attribute(state, "reserve1")?),
65        );
66
67        AeroBasicState::new(
68            reserves,
69            stable,
70            fees,
71            (decimals(all_tokens, token0)?, decimals(all_tokens, token1)?),
72        )
73        .map_err(InvalidSnapshotError::ValueError)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use std::{collections::HashMap, str::FromStr};
80
81    use num_bigint::BigUint;
82    use rstest::rstest;
83    use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
84    use tycho_common::{
85        models::{
86            protocol::{ProtocolComponent, ProtocolComponentState},
87            token::Token,
88            Chain,
89        },
90        simulation::protocol_sim::ProtocolSim,
91        Bytes,
92    };
93
94    use super::*;
95
96    fn tokens() -> HashMap<Bytes, Token> {
97        [
98            ("0x0000000000000000000000000000000000000001", 18),
99            ("0x0000000000000000000000000000000000000002", 6),
100        ]
101        .into_iter()
102        .map(|(address, decimals)| {
103            let address = Bytes::from_str(address).unwrap();
104            let token = Token::new(&address, "T", decimals, 0, &[Some(10_000)], Chain::Base, 100);
105            (address, token)
106        })
107        .collect()
108    }
109
110    fn snapshot(missing: Option<&str>) -> ComponentWithState {
111        let mut attributes = HashMap::from([
112            ("reserve0".to_string(), Bytes::from(vec![0x0f, 0x42, 0x40])),
113            ("reserve1".to_string(), Bytes::from(vec![0x0f, 0x42, 0x40])),
114            ("custom_fee".to_string(), Bytes::from(vec![0])),
115            ("default_fee".to_string(), Bytes::from(vec![30])),
116            (
117                "fee_module".to_string(),
118                Bytes::from_str("0x7949DE8d67E4F6b8509Bdbb43FF0503aF1247a7A").unwrap(),
119            ),
120            ("paused".to_string(), Bytes::from(vec![0])),
121        ]);
122        if let Some(name) = missing {
123            attributes.remove(name);
124        }
125        ComponentWithState {
126            state: ProtocolComponentState {
127                component_id: "0x00".to_string(),
128                attributes,
129                balances: HashMap::new(),
130            },
131            component: ProtocolComponent {
132                tokens: tokens()
133                    .into_keys()
134                    .collect::<std::collections::BTreeSet<_>>()
135                    .into_iter()
136                    .collect(),
137                static_attributes: HashMap::from([("is_stable".to_string(), Bytes::from(vec![0]))]),
138                ..Default::default()
139            },
140            component_tvl: None,
141            entrypoints: Vec::new(),
142        }
143    }
144
145    async fn decode(snapshot: ComponentWithState) -> Result<AeroBasicState, InvalidSnapshotError> {
146        AeroBasicState::try_from_with_header(
147            snapshot,
148            BlockHeader::default(),
149            &HashMap::new(),
150            &tokens(),
151            &DecoderContext::new(),
152        )
153        .await
154    }
155
156    #[tokio::test]
157    async fn decodes_a_snapshot_that_quotes() {
158        let state = decode(snapshot(None)).await.unwrap();
159        let tokens = tokens();
160        let token0 =
161            &tokens[&Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap()];
162        let token1 =
163            &tokens[&Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap()];
164
165        let out = state
166            .get_amount_out(BigUint::from(10_000u64), token0, token1)
167            .unwrap();
168
169        // 30 bps default fee on a 1e6/1e6 volatile pool.
170        assert_eq!(out.amount, BigUint::from(9_871u64));
171    }
172
173    #[rstest]
174    #[case::reserve0("reserve0")]
175    #[case::custom_fee("custom_fee")]
176    #[case::default_fee("default_fee")]
177    #[case::fee_module("fee_module")]
178    #[case::paused("paused")]
179    #[tokio::test]
180    async fn missing_attribute_is_an_error(#[case] name: &str) {
181        let err = decode(snapshot(Some(name)))
182            .await
183            .unwrap_err();
184
185        assert!(matches!(err, InvalidSnapshotError::MissingAttribute(missing) if missing == name));
186    }
187}