Skip to main content

tycho_simulation/evm/protocol/uniswap_v3/
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 super::{enums::FeeAmount, state::UniswapV3State};
8use crate::{
9    evm::protocol::utils::uniswap::{i24_be_bytes_to_i32, tick_list::TickInfo},
10    protocol::{
11        errors::InvalidSnapshotError,
12        models::{DecoderContext, TryFromWithBlock},
13    },
14};
15
16impl TryFromWithBlock<ComponentWithState, BlockHeader> for UniswapV3State {
17    type Error = InvalidSnapshotError;
18
19    /// Decodes a `ComponentWithState` into a `UniswapV3State`. Errors with a `InvalidSnapshotError`
20    /// if the snapshot is missing any required attributes or if the fee amount is not supported.
21    async fn try_from_with_header(
22        snapshot: ComponentWithState,
23        _block: BlockHeader,
24        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
25        _all_tokens: &HashMap<Bytes, Token>,
26        _decoder_context: &DecoderContext,
27    ) -> Result<Self, Self::Error> {
28        let liq = snapshot
29            .state
30            .attributes
31            .get("liquidity")
32            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("liquidity".to_string()))?
33            .clone();
34
35        // This is a hotfix because if the liquidity has never been updated after creation, it's
36        // currently encoded as H256::zero(), therefore, we can't decode this as u128.
37        // We can remove this once it has been fixed on the tycho side.
38        let liq_16_bytes = if liq.len() == 32 {
39            // Make sure it only happens for 0 values, otherwise error.
40            if liq == Bytes::zero(32) {
41                Bytes::from([0; 16])
42            } else {
43                return Err(InvalidSnapshotError::ValueError(format!(
44                    "Liquidity bytes too long for {liq}, expected 16"
45                )));
46            }
47        } else {
48            liq
49        };
50
51        let liquidity = u128::from(liq_16_bytes);
52
53        let sqrt_price = U256::from_be_slice(
54            snapshot
55                .state
56                .attributes
57                .get("sqrt_price_x96")
58                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("sqrt_price".to_string()))?,
59        );
60
61        let fee_value = i32::from(
62            snapshot
63                .component
64                .static_attributes
65                .get("fee")
66                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("fee".to_string()))?
67                .clone(),
68        );
69        let fee = FeeAmount::try_from(fee_value)
70            .map_err(|_| InvalidSnapshotError::ValueError("Unsupported fee amount".to_string()))?;
71
72        let tick = snapshot
73            .state
74            .attributes
75            .get("tick")
76            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick".to_string()))?
77            .clone();
78
79        // This is a hotfix because if the tick has never been updated after creation, it's
80        // currently encoded as H256::zero(), therefore, we can't decode this as i32. We can
81        // remove this this will be fixed on the tycho side.
82        let ticks_4_bytes = if tick.len() == 32 {
83            // Make sure it only happens for 0 values, otherwise error.
84            if tick == Bytes::zero(32) {
85                Bytes::from([0; 4])
86            } else {
87                return Err(InvalidSnapshotError::ValueError(format!(
88                    "Tick bytes too long for {tick}, expected 4"
89                )));
90            }
91        } else {
92            tick
93        };
94        let tick = i24_be_bytes_to_i32(&ticks_4_bytes);
95
96        let ticks: Result<Vec<_>, _> = snapshot
97            .state
98            .attributes
99            .iter()
100            .filter_map(|(key, value)| {
101                if key.starts_with("ticks/") {
102                    Some(
103                        key.split('/')
104                            .nth(1)?
105                            .parse::<i32>()
106                            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
107                            .and_then(|tick_index| {
108                                TickInfo::new(tick_index, i128::from(value.clone())).map_err(
109                                    |err| InvalidSnapshotError::ValueError(err.to_string()),
110                                )
111                            }),
112                    )
113                } else {
114                    None
115                }
116            })
117            .collect();
118
119        let mut ticks = match ticks {
120            Ok(ticks) if !ticks.is_empty() => ticks
121                .into_iter()
122                .filter(|t| t.net_liquidity != 0)
123                .collect::<Vec<_>>(),
124            _ => return Err(InvalidSnapshotError::MissingAttribute("tick_liquidities".to_string())),
125        };
126
127        ticks.sort_by_key(|tick| tick.index);
128
129        UniswapV3State::new(liquidity, sqrt_price, fee, tick, ticks)
130            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use std::str::FromStr;
137
138    use chrono::DateTime;
139    use rstest::rstest;
140    use tycho_common::models::{
141        protocol::{ProtocolComponent, ProtocolComponentState},
142        Chain, ChangeType,
143    };
144
145    use super::*;
146    use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
147
148    fn usv3_component() -> ProtocolComponent {
149        let creation_time = DateTime::from_timestamp(1622526000, 0)
150            .unwrap()
151            .naive_utc(); //Sample timestamp
152
153        // Add a static attribute "fee"
154        let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
155        static_attributes.insert("fee".to_string(), Bytes::from(3000_i32.to_be_bytes().to_vec()));
156
157        ProtocolComponent {
158            id: "State1".to_string(),
159            protocol_system: "system1".to_string(),
160            protocol_type_name: "typename1".to_string(),
161            chain: Chain::Ethereum,
162            tokens: Vec::new(),
163            contract_addresses: Vec::new(),
164            static_attributes,
165            change: ChangeType::Creation,
166            creation_tx: Bytes::from_str("0x0000").unwrap(),
167            created_at: creation_time,
168        }
169    }
170
171    fn usv3_attributes() -> HashMap<String, Bytes> {
172        vec![
173            ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
174            ("sqrt_price_x96".to_string(), Bytes::from(200_u64.to_be_bytes().to_vec())),
175            ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
176            ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
177        ]
178        .into_iter()
179        .collect::<HashMap<String, Bytes>>()
180    }
181
182    #[tokio::test]
183    async fn test_usv3_try_from() {
184        let snapshot = ComponentWithState {
185            state: ProtocolComponentState {
186                component_id: "State1".to_owned(),
187                attributes: usv3_attributes(),
188                balances: HashMap::new(),
189            },
190            component: usv3_component(),
191            component_tvl: None,
192            entrypoints: Vec::new(),
193        };
194
195        let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
196
197        assert!(result.is_ok());
198        let expected = UniswapV3State::new(
199            100,
200            U256::from(200),
201            FeeAmount::Medium,
202            300,
203            vec![TickInfo::new(60, 400).unwrap()],
204        )
205        .unwrap();
206        assert_eq!(result.unwrap(), expected);
207    }
208
209    #[tokio::test]
210    #[rstest]
211    #[case::missing_liquidity("liquidity")]
212    #[case::missing_sqrt_price("sqrt_price")]
213    #[case::missing_tick("tick")]
214    #[case::missing_tick_liquidity("tick_liquidities")]
215    #[case::missing_fee("fee")]
216    async fn test_usv3_try_from_invalid(#[case] missing_attribute: String) {
217        // remove missing attribute
218        let mut attributes = usv3_attributes();
219        attributes.remove(&missing_attribute);
220
221        if missing_attribute == "tick_liquidities" {
222            attributes.remove("ticks/60/net_liquidity");
223        }
224
225        if missing_attribute == "sqrt_price" {
226            attributes.remove("sqrt_price_x96");
227        }
228
229        let mut component = usv3_component();
230        if missing_attribute == "fee" {
231            component
232                .static_attributes
233                .remove("fee");
234        }
235
236        let snapshot = ComponentWithState {
237            state: ProtocolComponentState {
238                component_id: "State1".to_owned(),
239                attributes,
240                balances: HashMap::new(),
241            },
242            component,
243            component_tvl: None,
244            entrypoints: Vec::new(),
245        };
246
247        let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
248
249        assert!(result.is_err());
250        assert!(matches!(
251            result.err().unwrap(),
252            InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
253        ));
254    }
255
256    #[tokio::test]
257    async fn test_usv3_try_from_invalid_fee() {
258        // set an invalid fee amount (100, 500, 3_000 and 10_000 are the only valid fee amounts)
259        let mut component = usv3_component();
260        component
261            .static_attributes
262            .insert("fee".to_string(), Bytes::from(4000_i32.to_be_bytes().to_vec()));
263
264        let snapshot = ComponentWithState {
265            state: ProtocolComponentState {
266                component_id: "State1".to_owned(),
267                attributes: usv3_attributes(),
268                balances: HashMap::new(),
269            },
270            component,
271            component_tvl: None,
272            entrypoints: Vec::new(),
273        };
274
275        let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
276
277        assert!(result.is_err());
278        assert!(matches!(
279            result.err().unwrap(),
280            InvalidSnapshotError::ValueError(err) if err == *"Unsupported fee amount"
281        ));
282    }
283}