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, fee_tier::FeeTier, 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 async fn try_from_with_header(
23 snapshot: ComponentWithState,
24 _block: BlockHeader,
25 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
26 _all_tokens: &HashMap<Bytes, Token>,
27 _decoder_context: &DecoderContext,
28 ) -> Result<Self, Self::Error> {
29 let liq = snapshot
30 .state
31 .attributes
32 .get("liquidity")
33 .ok_or_else(|| InvalidSnapshotError::MissingAttribute("liquidity".to_string()))?
34 .clone();
35
36 let liq_16_bytes = if liq.len() == 32 {
40 if liq == Bytes::zero(32) {
42 Bytes::from([0; 16])
43 } else {
44 return Err(InvalidSnapshotError::ValueError(format!(
45 "Liquidity bytes too long for {liq}, expected 16"
46 )));
47 }
48 } else {
49 liq
50 };
51
52 let liquidity = u128::try_from(liq_16_bytes)?;
53
54 let sqrt_price = U256::from_be_slice(
55 snapshot
56 .state
57 .attributes
58 .get("sqrt_price_x96")
59 .ok_or_else(|| InvalidSnapshotError::MissingAttribute("sqrt_price".to_string()))?,
60 );
61
62 let fee = decode_fee_tier(&snapshot.component.static_attributes)?;
63
64 let tick = snapshot
65 .state
66 .attributes
67 .get("tick")
68 .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick".to_string()))?
69 .clone();
70
71 let ticks_4_bytes = if tick.len() == 32 {
75 if tick == Bytes::zero(32) {
77 Bytes::from([0; 4])
78 } else {
79 return Err(InvalidSnapshotError::ValueError(format!(
80 "Tick bytes too long for {tick}, expected 4"
81 )));
82 }
83 } else {
84 tick
85 };
86 let tick = i24_be_bytes_to_i32(&ticks_4_bytes);
87
88 let ticks: Result<Vec<_>, _> = snapshot
89 .state
90 .attributes
91 .iter()
92 .filter_map(|(key, value)| {
93 if key.starts_with("ticks/") {
94 Some(
95 key.split('/')
96 .nth(1)?
97 .parse::<i32>()
98 .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
99 .and_then(|tick_index| {
100 TickInfo::new(tick_index, i128::try_from(value.clone())?).map_err(
101 |err| InvalidSnapshotError::ValueError(err.to_string()),
102 )
103 }),
104 )
105 } else {
106 None
107 }
108 })
109 .collect();
110
111 let mut ticks = match ticks {
112 Ok(ticks) if !ticks.is_empty() => ticks
113 .into_iter()
114 .filter(|t| t.net_liquidity != 0)
115 .collect::<Vec<_>>(),
116 _ => return Err(InvalidSnapshotError::MissingAttribute("tick_liquidities".to_string())),
117 };
118
119 ticks.sort_by_key(|tick| tick.index);
120
121 UniswapV3State::new(liquidity, sqrt_price, fee, tick, ticks)
122 .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
123 }
124}
125
126fn decode_fee_tier(
132 static_attributes: &HashMap<String, Bytes>,
133) -> Result<FeeTier, InvalidSnapshotError> {
134 let fee = static_attributes
135 .get("fee")
136 .ok_or_else(|| InvalidSnapshotError::MissingAttribute("fee".to_string()))?;
137 let fee = decode_i32("fee", fee)?;
138
139 let Some(tick_spacing) = static_attributes.get("tick_spacing") else {
140 return FeeAmount::try_from(fee)
141 .map(FeeTier::from)
142 .map_err(|()| {
143 InvalidSnapshotError::ValueError(format!("Unsupported fee amount {fee}"))
144 });
145 };
146 let tick_spacing = decode_i32("tick_spacing", tick_spacing)?;
147
148 let fee = u32::try_from(fee)
149 .map_err(|_out_of_range| InvalidSnapshotError::ValueError(format!("Negative fee {fee}")))?;
150 let tick_spacing = u16::try_from(tick_spacing).map_err(|_out_of_range| {
151 InvalidSnapshotError::ValueError(format!("Tick spacing {tick_spacing} out of range"))
152 })?;
153 FeeTier::new(fee, tick_spacing).map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
154}
155
156fn decode_i32(name: &str, value: &Bytes) -> Result<i32, InvalidSnapshotError> {
157 i32::try_from(value.clone())
158 .map_err(|err| InvalidSnapshotError::ValueError(format!("Attribute {name}: {err}")))
159}
160
161#[cfg(test)]
162mod tests {
163 use std::str::FromStr;
164
165 use chrono::DateTime;
166 use rstest::rstest;
167 use tycho_common::models::{
168 protocol::{ProtocolComponent, ProtocolComponentState},
169 Chain, ChangeType,
170 };
171
172 use super::*;
173 use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
174
175 fn usv3_component() -> ProtocolComponent {
176 let creation_time = DateTime::from_timestamp(1622526000, 0)
177 .unwrap()
178 .naive_utc(); let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
182 static_attributes.insert("fee".to_string(), Bytes::from(3000_i32.to_be_bytes().to_vec()));
183
184 ProtocolComponent {
185 id: "State1".to_string(),
186 protocol_system: "system1".to_string(),
187 protocol_type_name: "typename1".to_string(),
188 chain: Chain::Ethereum,
189 tokens: Vec::new(),
190 contract_addresses: Vec::new(),
191 static_attributes,
192 change: ChangeType::Creation,
193 creation_tx: Bytes::from_str("0x0000").unwrap(),
194 created_at: creation_time,
195 }
196 }
197
198 fn usv3_attributes() -> HashMap<String, Bytes> {
199 vec![
200 ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
201 ("sqrt_price_x96".to_string(), Bytes::from(200_u64.to_be_bytes().to_vec())),
202 ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
203 ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
204 ]
205 .into_iter()
206 .collect::<HashMap<String, Bytes>>()
207 }
208
209 #[tokio::test]
210 async fn test_usv3_try_from() {
211 let snapshot = ComponentWithState {
212 state: ProtocolComponentState {
213 component_id: "State1".to_owned(),
214 attributes: usv3_attributes(),
215 balances: HashMap::new(),
216 },
217 component: usv3_component(),
218 component_tvl: None,
219 entrypoints: Vec::new(),
220 };
221
222 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
223
224 assert!(result.is_ok());
225 let expected = UniswapV3State::new(
226 100,
227 U256::from(200),
228 FeeAmount::Medium,
229 300,
230 vec![TickInfo::new(60, 400).unwrap()],
231 )
232 .unwrap();
233 assert_eq!(result.unwrap(), expected);
234 }
235
236 #[tokio::test]
237 #[rstest]
238 #[case::missing_liquidity("liquidity")]
239 #[case::missing_sqrt_price("sqrt_price")]
240 #[case::missing_tick("tick")]
241 #[case::missing_tick_liquidity("tick_liquidities")]
242 #[case::missing_fee("fee")]
243 async fn test_usv3_try_from_invalid(#[case] missing_attribute: String) {
244 let mut attributes = usv3_attributes();
246 attributes.remove(&missing_attribute);
247
248 if missing_attribute == "tick_liquidities" {
249 attributes.remove("ticks/60/net_liquidity");
250 }
251
252 if missing_attribute == "sqrt_price" {
253 attributes.remove("sqrt_price_x96");
254 }
255
256 let mut component = usv3_component();
257 if missing_attribute == "fee" {
258 component
259 .static_attributes
260 .remove("fee");
261 }
262
263 let snapshot = ComponentWithState {
264 state: ProtocolComponentState {
265 component_id: "State1".to_owned(),
266 attributes,
267 balances: HashMap::new(),
268 },
269 component,
270 component_tvl: None,
271 entrypoints: Vec::new(),
272 };
273
274 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
275
276 assert!(result.is_err());
277 assert!(matches!(
278 result.err().unwrap(),
279 InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
280 ));
281 }
282
283 fn usv3_snapshot(static_attributes: &[(&str, Vec<u8>)], tick: i32) -> ComponentWithState {
284 let mut component = usv3_component();
285 for (name, value) in static_attributes {
286 component
287 .static_attributes
288 .insert(name.to_string(), Bytes::from(value.clone()));
289 }
290 let mut attributes = usv3_attributes();
291 attributes.remove("ticks/60/net_liquidity");
292 attributes.insert(
293 format!("ticks/{tick}/net_liquidity"),
294 Bytes::from(400_i128.to_be_bytes().to_vec()),
295 );
296 ComponentWithState {
297 state: ProtocolComponentState {
298 component_id: "State1".to_owned(),
299 attributes,
300 balances: HashMap::new(),
301 },
302 component,
303 component_tvl: None,
304 entrypoints: Vec::new(),
305 }
306 }
307
308 #[tokio::test]
309 #[rstest]
310 #[case::fee_outside_fee_amount(vec![0x32], vec![0x0a], 50, 10, 20)]
312 #[case::spacing_differs_from_fee_amount(vec![0x00, 0xc8], vec![0x04], 200, 4, 8)]
313 #[case::large_fee_small_spacing(vec![0x75, 0x30], vec![0x01], 30_000, 1, 7)]
314 async fn test_usv3_try_from_uses_tick_spacing_attribute(
315 #[case] fee_bytes: Vec<u8>,
316 #[case] tick_spacing_bytes: Vec<u8>,
317 #[case] fee: u32,
318 #[case] tick_spacing: u16,
319 #[case] tick: i32,
320 ) {
321 let snapshot =
322 usv3_snapshot(&[("fee", fee_bytes), ("tick_spacing", tick_spacing_bytes)], tick);
323
324 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
325
326 let expected = UniswapV3State::new(
327 100,
328 U256::from(200),
329 FeeTier::new(fee, tick_spacing).unwrap(),
330 300,
331 vec![TickInfo::new(tick, 400).unwrap()],
332 )
333 .unwrap();
334 assert_eq!(result.unwrap(), expected);
335 }
336
337 #[tokio::test]
338 async fn test_usv3_try_from_rejects_tick_off_attribute_spacing() {
339 let snapshot = usv3_snapshot(&[("fee", vec![0x00, 0xc8]), ("tick_spacing", vec![0x04])], 2);
341
342 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
343
344 assert!(matches!(
345 result,
346 Err(InvalidSnapshotError::ValueError(err)) if err.contains("not aligned")
347 ));
348 }
349
350 #[tokio::test]
351 #[rstest]
352 #[case::negative_fee(vec![0xff], vec![0x01], "Negative fee")]
353 #[case::fee_at_denominator(vec![0x0f, 0x42, 0x40], vec![0x01], "must be below")]
354 #[case::zero_spacing(vec![0x32], vec![0x00], "must be positive")]
355 #[case::negative_spacing(vec![0x32], vec![0xff], "out of range")]
356 #[case::spacing_above_u16(vec![0x32], vec![0x01, 0x00, 0x00], "out of range")]
357 #[case::spacing_wider_than_i32(vec![0x32], vec![0x01, 0x00, 0x00, 0x00, 0x00], "does not fit into i32")]
358 async fn test_usv3_try_from_invalid_tick_spacing_attribute(
359 #[case] fee_bytes: Vec<u8>,
360 #[case] tick_spacing_bytes: Vec<u8>,
361 #[case] expected_error: &str,
362 ) {
363 let snapshot =
364 usv3_snapshot(&[("fee", fee_bytes), ("tick_spacing", tick_spacing_bytes)], 0);
365
366 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
367
368 assert!(matches!(
369 result,
370 Err(InvalidSnapshotError::ValueError(err)) if err.contains(expected_error)
371 ));
372 }
373
374 #[tokio::test]
375 async fn test_usv3_try_from_invalid_fee() {
376 let mut component = usv3_component();
378 component
379 .static_attributes
380 .insert("fee".to_string(), Bytes::from(4000_i32.to_be_bytes().to_vec()));
381
382 let snapshot = ComponentWithState {
383 state: ProtocolComponentState {
384 component_id: "State1".to_owned(),
385 attributes: usv3_attributes(),
386 balances: HashMap::new(),
387 },
388 component,
389 component_tvl: None,
390 entrypoints: Vec::new(),
391 };
392
393 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
394
395 assert!(result.is_err());
396 assert!(matches!(
397 result.err().unwrap(),
398 InvalidSnapshotError::ValueError(err) if err == *"Unsupported fee amount 4000"
399 ));
400 }
401}