Skip to main content

tycho_simulation/evm/protocol/ramses_v3/
decoder.rs

1use std::collections::HashMap;
2
3use alloy::primitives::U256;
4use itertools::Itertools;
5use num_traits::Zero;
6use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
7use tycho_common::{models::token::Token, Bytes};
8
9use super::state::RamsesV3State;
10use crate::{
11    evm::protocol::utils::uniswap::tick_list::TickInfo,
12    protocol::{
13        errors::InvalidSnapshotError,
14        models::{DecoderContext, TryFromWithBlock},
15    },
16};
17
18impl TryFromWithBlock<ComponentWithState, BlockHeader> for RamsesV3State {
19    type Error = InvalidSnapshotError;
20
21    /// Decodes a `ComponentWithState` into a `RamsesV3State`. Errors with an `InvalidSnapshotError`
22    /// if the snapshot is missing any required attributes.
23    ///
24    /// Unlike Uniswap V3, `fee` is read from the (mutable) state attributes rather than the static
25    /// attributes, and `tick_spacing` is read directly from the static attributes instead of being
26    /// derived from the fee tier.
27    async fn try_from_with_header(
28        snapshot: ComponentWithState,
29        _block: BlockHeader,
30        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
31        _all_tokens: &HashMap<Bytes, Token>,
32        _decoder_context: &DecoderContext,
33    ) -> Result<Self, Self::Error> {
34        let static_attrs = snapshot.component.static_attributes;
35        let state_attrs = snapshot.state.attributes;
36
37        // The fee is governance-mutable, so it lives in the (dynamic) state attributes.
38        let fee = u32::try_from(attribute(&state_attrs, "fee")?.clone())?;
39        let liquidity = u128::try_from(attribute(&state_attrs, "liquidity")?.clone())?;
40        let sqrt_price = U256::from_be_slice(attribute(&state_attrs, "sqrt_price_x96")?);
41        let tick_spacing = u16::try_from(attribute(&static_attrs, "tick_spacing")?.clone())?;
42        let tick = i32::try_from(attribute(&state_attrs, "tick")?.clone())?;
43
44        // An empty tick list is valid: a pool that is not yet initialized (or has no liquidity)
45        // simply decodes to a zero-liquidity state that gracefully returns "No liquidity" on quote.
46        let ticks = state_attrs
47            .iter()
48            .filter_map(|(key, value)| {
49                let tick_index = match key
50                    .strip_prefix("ticks/")?
51                    .parse::<i32>()
52                {
53                    Ok(tick_index) => tick_index,
54                    Err(err) => return Some(Err(InvalidSnapshotError::ValueError(err.to_string()))),
55                };
56
57                let net_liquidity = match i128::try_from(value.clone()) {
58                    Ok(net_liquidity) => net_liquidity,
59                    Err(err) => return Some(Err(err.into())),
60                };
61                if net_liquidity.is_zero() {
62                    return None;
63                }
64
65                Some(
66                    TickInfo::new(tick_index, net_liquidity)
67                        .map_err(|err| InvalidSnapshotError::ValueError(err.to_string())),
68                )
69            })
70            .collect::<Result<Vec<_>, _>>()?
71            .into_iter()
72            .sorted_unstable_by_key(|tick| tick.index)
73            .collect();
74
75        RamsesV3State::new(liquidity, sqrt_price, fee, tick_spacing, tick, ticks)
76            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
77    }
78}
79
80fn attribute<'a>(
81    map: &'a HashMap<String, Bytes>,
82    key: &str,
83) -> Result<&'a Bytes, InvalidSnapshotError> {
84    map.get(key)
85        .ok_or_else(|| InvalidSnapshotError::MissingAttribute(key.to_string()))
86}
87
88#[cfg(test)]
89mod tests {
90    use std::str::FromStr;
91
92    use chrono::DateTime;
93    use rstest::rstest;
94    use tycho_common::models::{
95        protocol::{ProtocolComponent, ProtocolComponentState},
96        Chain, ChangeType,
97    };
98
99    use super::*;
100    use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
101
102    fn ramses_component() -> ProtocolComponent {
103        let creation_time = DateTime::from_timestamp(1622526000, 0)
104            .unwrap()
105            .naive_utc();
106
107        // tick_spacing is the only V3-style static attribute; fee is dynamic.
108        let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
109        static_attributes
110            .insert("tick_spacing".to_string(), Bytes::from(60_u16.to_be_bytes().to_vec()));
111
112        ProtocolComponent {
113            id: "State1".to_string(),
114            protocol_system: "ramses_v3".to_string(),
115            protocol_type_name: "ramses_v3_pool".to_string(),
116            chain: Chain::Polygon,
117            tokens: Vec::new(),
118            contract_addresses: Vec::new(),
119            static_attributes,
120            change: ChangeType::Creation,
121            creation_tx: Bytes::from_str("0x0000").unwrap(),
122            created_at: creation_time,
123        }
124    }
125
126    fn ramses_attributes() -> HashMap<String, Bytes> {
127        vec![
128            ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
129            ("sqrt_price_x96".to_string(), Bytes::from(200_u64.to_be_bytes().to_vec())),
130            ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
131            ("fee".to_string(), Bytes::from(3000_u32.to_be_bytes().to_vec())),
132            ("ticks/60".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
133        ]
134        .into_iter()
135        .collect::<HashMap<String, Bytes>>()
136    }
137
138    #[tokio::test]
139    async fn test_ramses_try_from() {
140        let snapshot = ComponentWithState {
141            state: ProtocolComponentState {
142                component_id: "State1".to_owned(),
143                attributes: ramses_attributes(),
144                balances: HashMap::new(),
145            },
146            component: ramses_component(),
147            component_tvl: None,
148            entrypoints: Vec::new(),
149        };
150
151        assert_eq!(
152            RamsesV3State::new(
153                100,
154                U256::from(200),
155                3000,
156                60,
157                300,
158                vec![TickInfo::new(60, 400).unwrap()],
159            )
160            .unwrap(),
161            try_decode_snapshot_with_defaults(snapshot)
162                .await
163                .unwrap(),
164        );
165    }
166
167    #[tokio::test]
168    #[rstest]
169    #[case::missing_liquidity("liquidity")]
170    #[case::missing_sqrt_price("sqrt_price_x96")]
171    #[case::missing_tick("tick")]
172    #[case::missing_fee("fee")]
173    #[case::missing_tick_spacing("tick_spacing")]
174    async fn test_ramses_try_from_invalid(#[case] missing_attribute: String) {
175        let mut attributes = ramses_attributes();
176        attributes.remove(&missing_attribute);
177
178        let mut component = ramses_component();
179        component
180            .static_attributes
181            .remove(&missing_attribute);
182
183        let snapshot = ComponentWithState {
184            state: ProtocolComponentState {
185                component_id: "State1".to_owned(),
186                attributes,
187                balances: HashMap::new(),
188            },
189            component,
190            component_tvl: None,
191            entrypoints: Vec::new(),
192        };
193
194        let result = try_decode_snapshot_with_defaults::<RamsesV3State>(snapshot).await;
195
196        assert!(matches!(
197            result.unwrap_err(),
198            InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
199        ));
200    }
201
202    #[tokio::test]
203    async fn test_ramses_try_from_uninitialized() {
204        // A created-but-not-initialized pool has no ticks and zero price/liquidity. It must still
205        // decode (into a zero-liquidity state) rather than error.
206        let mut attributes = ramses_attributes();
207        attributes.remove("ticks/60");
208        attributes.insert("liquidity".to_string(), Bytes::from(vec![0u8]));
209        attributes.insert("sqrt_price_x96".to_string(), Bytes::from(vec![0u8]));
210
211        let snapshot = ComponentWithState {
212            state: ProtocolComponentState {
213                component_id: "State1".to_owned(),
214                attributes,
215                balances: HashMap::new(),
216            },
217            component: ramses_component(),
218            component_tvl: None,
219            entrypoints: Vec::new(),
220        };
221
222        let result = try_decode_snapshot_with_defaults::<RamsesV3State>(snapshot).await;
223
224        assert!(result.is_ok());
225    }
226}