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(|_| InvalidSnapshotError::ValueError("Unsupported fee amount".to_string()));
143 };
144 let tick_spacing = decode_i32("tick_spacing", tick_spacing)?;
145
146 let fee = u32::try_from(fee)
147 .map_err(|_| InvalidSnapshotError::ValueError(format!("Negative fee {fee}")))?;
148 let tick_spacing = u16::try_from(tick_spacing).map_err(|_| {
149 InvalidSnapshotError::ValueError(format!("Tick spacing {tick_spacing} out of range"))
150 })?;
151 FeeTier::new(fee, tick_spacing).map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
152}
153
154fn decode_i32(name: &str, value: &Bytes) -> Result<i32, InvalidSnapshotError> {
155 i32::try_from(value.clone())
156 .map_err(|err| InvalidSnapshotError::ValueError(format!("Attribute {name}: {err}")))
157}
158
159#[cfg(test)]
160mod tests {
161 use std::str::FromStr;
162
163 use chrono::DateTime;
164 use rstest::rstest;
165 use tycho_common::models::{
166 protocol::{ProtocolComponent, ProtocolComponentState},
167 Chain, ChangeType,
168 };
169
170 use super::*;
171 use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
172
173 fn usv3_component() -> ProtocolComponent {
174 let creation_time = DateTime::from_timestamp(1622526000, 0)
175 .unwrap()
176 .naive_utc(); let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
180 static_attributes.insert("fee".to_string(), Bytes::from(3000_i32.to_be_bytes().to_vec()));
181
182 ProtocolComponent {
183 id: "State1".to_string(),
184 protocol_system: "system1".to_string(),
185 protocol_type_name: "typename1".to_string(),
186 chain: Chain::Ethereum,
187 tokens: Vec::new(),
188 contract_addresses: Vec::new(),
189 static_attributes,
190 change: ChangeType::Creation,
191 creation_tx: Bytes::from_str("0x0000").unwrap(),
192 created_at: creation_time,
193 }
194 }
195
196 fn usv3_attributes() -> HashMap<String, Bytes> {
197 vec![
198 ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
199 ("sqrt_price_x96".to_string(), Bytes::from(200_u64.to_be_bytes().to_vec())),
200 ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
201 ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
202 ]
203 .into_iter()
204 .collect::<HashMap<String, Bytes>>()
205 }
206
207 #[tokio::test]
208 async fn test_usv3_try_from() {
209 let snapshot = ComponentWithState {
210 state: ProtocolComponentState {
211 component_id: "State1".to_owned(),
212 attributes: usv3_attributes(),
213 balances: HashMap::new(),
214 },
215 component: usv3_component(),
216 component_tvl: None,
217 entrypoints: Vec::new(),
218 };
219
220 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
221
222 assert!(result.is_ok());
223 let expected = UniswapV3State::new(
224 100,
225 U256::from(200),
226 FeeAmount::Medium,
227 300,
228 vec![TickInfo::new(60, 400).unwrap()],
229 )
230 .unwrap();
231 assert_eq!(result.unwrap(), expected);
232 }
233
234 #[tokio::test]
235 #[rstest]
236 #[case::missing_liquidity("liquidity")]
237 #[case::missing_sqrt_price("sqrt_price")]
238 #[case::missing_tick("tick")]
239 #[case::missing_tick_liquidity("tick_liquidities")]
240 #[case::missing_fee("fee")]
241 async fn test_usv3_try_from_invalid(#[case] missing_attribute: String) {
242 let mut attributes = usv3_attributes();
244 attributes.remove(&missing_attribute);
245
246 if missing_attribute == "tick_liquidities" {
247 attributes.remove("ticks/60/net_liquidity");
248 }
249
250 if missing_attribute == "sqrt_price" {
251 attributes.remove("sqrt_price_x96");
252 }
253
254 let mut component = usv3_component();
255 if missing_attribute == "fee" {
256 component
257 .static_attributes
258 .remove("fee");
259 }
260
261 let snapshot = ComponentWithState {
262 state: ProtocolComponentState {
263 component_id: "State1".to_owned(),
264 attributes,
265 balances: HashMap::new(),
266 },
267 component,
268 component_tvl: None,
269 entrypoints: Vec::new(),
270 };
271
272 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
273
274 assert!(result.is_err());
275 assert!(matches!(
276 result.err().unwrap(),
277 InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
278 ));
279 }
280
281 fn usv3_snapshot(static_attributes: &[(&str, Vec<u8>)], tick: i32) -> ComponentWithState {
282 let mut component = usv3_component();
283 for (name, value) in static_attributes {
284 component
285 .static_attributes
286 .insert(name.to_string(), Bytes::from(value.clone()));
287 }
288 let mut attributes = usv3_attributes();
289 attributes.remove("ticks/60/net_liquidity");
290 attributes.insert(
291 format!("ticks/{tick}/net_liquidity"),
292 Bytes::from(400_i128.to_be_bytes().to_vec()),
293 );
294 ComponentWithState {
295 state: ProtocolComponentState {
296 component_id: "State1".to_owned(),
297 attributes,
298 balances: HashMap::new(),
299 },
300 component,
301 component_tvl: None,
302 entrypoints: Vec::new(),
303 }
304 }
305
306 #[tokio::test]
307 #[rstest]
308 #[case::fee_outside_fee_amount(vec![0x32], vec![0x0a], 50, 10, 20)]
310 #[case::spacing_differs_from_fee_amount(vec![0x00, 0xc8], vec![0x04], 200, 4, 8)]
311 #[case::large_fee_small_spacing(vec![0x75, 0x30], vec![0x01], 30_000, 1, 7)]
312 async fn test_usv3_try_from_uses_tick_spacing_attribute(
313 #[case] fee_bytes: Vec<u8>,
314 #[case] tick_spacing_bytes: Vec<u8>,
315 #[case] fee: u32,
316 #[case] tick_spacing: u16,
317 #[case] tick: i32,
318 ) {
319 let snapshot =
320 usv3_snapshot(&[("fee", fee_bytes), ("tick_spacing", tick_spacing_bytes)], tick);
321
322 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
323
324 let expected = UniswapV3State::new(
325 100,
326 U256::from(200),
327 FeeTier::new(fee, tick_spacing).unwrap(),
328 300,
329 vec![TickInfo::new(tick, 400).unwrap()],
330 )
331 .unwrap();
332 assert_eq!(result.unwrap(), expected);
333 }
334
335 #[tokio::test]
336 async fn test_usv3_try_from_rejects_tick_off_attribute_spacing() {
337 let snapshot = usv3_snapshot(&[("fee", vec![0x00, 0xc8]), ("tick_spacing", vec![0x04])], 2);
339
340 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
341
342 assert!(matches!(
343 result,
344 Err(InvalidSnapshotError::ValueError(err)) if err.contains("not aligned")
345 ));
346 }
347
348 #[tokio::test]
349 #[rstest]
350 #[case::negative_fee(vec![0xff], vec![0x01], "Negative fee")]
351 #[case::fee_at_denominator(vec![0x0f, 0x42, 0x40], vec![0x01], "must be below")]
352 #[case::zero_spacing(vec![0x32], vec![0x00], "must be positive")]
353 #[case::negative_spacing(vec![0x32], vec![0xff], "out of range")]
354 #[case::spacing_above_u16(vec![0x32], vec![0x01, 0x00, 0x00], "out of range")]
355 #[case::spacing_wider_than_i32(vec![0x32], vec![0x01, 0x00, 0x00, 0x00, 0x00], "does not fit into i32")]
356 async fn test_usv3_try_from_invalid_tick_spacing_attribute(
357 #[case] fee_bytes: Vec<u8>,
358 #[case] tick_spacing_bytes: Vec<u8>,
359 #[case] expected_error: &str,
360 ) {
361 let snapshot =
362 usv3_snapshot(&[("fee", fee_bytes), ("tick_spacing", tick_spacing_bytes)], 0);
363
364 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
365
366 assert!(matches!(
367 result,
368 Err(InvalidSnapshotError::ValueError(err)) if err.contains(expected_error)
369 ));
370 }
371
372 #[tokio::test]
373 async fn test_usv3_try_from_invalid_fee() {
374 let mut component = usv3_component();
376 component
377 .static_attributes
378 .insert("fee".to_string(), Bytes::from(4000_i32.to_be_bytes().to_vec()));
379
380 let snapshot = ComponentWithState {
381 state: ProtocolComponentState {
382 component_id: "State1".to_owned(),
383 attributes: usv3_attributes(),
384 balances: HashMap::new(),
385 },
386 component,
387 component_tvl: None,
388 entrypoints: Vec::new(),
389 };
390
391 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
392
393 assert!(result.is_err());
394 assert!(matches!(
395 result.err().unwrap(),
396 InvalidSnapshotError::ValueError(err) if err == *"Unsupported fee amount"
397 ));
398 }
399}