tycho_simulation/evm/protocol/uniswap_v3/
decoder.rs1use 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 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 let liq_16_bytes = if liq.len() == 32 {
39 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 let ticks_4_bytes = if tick.len() == 32 {
83 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::dto::{Chain, ChangeType, ProtocolComponent, ResponseProtocolState};
141
142 use super::*;
143 use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
144
145 fn usv3_component() -> ProtocolComponent {
146 let creation_time = DateTime::from_timestamp(1622526000, 0)
147 .unwrap()
148 .naive_utc(); let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
152 static_attributes.insert("fee".to_string(), Bytes::from(3000_i32.to_be_bytes().to_vec()));
153
154 ProtocolComponent {
155 id: "State1".to_string(),
156 protocol_system: "system1".to_string(),
157 protocol_type_name: "typename1".to_string(),
158 chain: Chain::Ethereum,
159 tokens: Vec::new(),
160 contract_ids: Vec::new(),
161 static_attributes,
162 change: ChangeType::Creation,
163 creation_tx: Bytes::from_str("0x0000").unwrap(),
164 created_at: creation_time,
165 }
166 }
167
168 fn usv3_attributes() -> HashMap<String, Bytes> {
169 vec![
170 ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
171 ("sqrt_price_x96".to_string(), Bytes::from(200_u64.to_be_bytes().to_vec())),
172 ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
173 ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
174 ]
175 .into_iter()
176 .collect::<HashMap<String, Bytes>>()
177 }
178
179 #[tokio::test]
180 async fn test_usv3_try_from() {
181 let snapshot = ComponentWithState {
182 state: ResponseProtocolState {
183 component_id: "State1".to_owned(),
184 attributes: usv3_attributes(),
185 balances: HashMap::new(),
186 },
187 component: usv3_component(),
188 component_tvl: None,
189 entrypoints: Vec::new(),
190 };
191
192 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
193
194 assert!(result.is_ok());
195 let expected = UniswapV3State::new(
196 100,
197 U256::from(200),
198 FeeAmount::Medium,
199 300,
200 vec![TickInfo::new(60, 400).unwrap()],
201 )
202 .unwrap();
203 assert_eq!(result.unwrap(), expected);
204 }
205
206 #[tokio::test]
207 #[rstest]
208 #[case::missing_liquidity("liquidity")]
209 #[case::missing_sqrt_price("sqrt_price")]
210 #[case::missing_tick("tick")]
211 #[case::missing_tick_liquidity("tick_liquidities")]
212 #[case::missing_fee("fee")]
213 async fn test_usv3_try_from_invalid(#[case] missing_attribute: String) {
214 let mut attributes = usv3_attributes();
216 attributes.remove(&missing_attribute);
217
218 if missing_attribute == "tick_liquidities" {
219 attributes.remove("ticks/60/net_liquidity");
220 }
221
222 if missing_attribute == "sqrt_price" {
223 attributes.remove("sqrt_price_x96");
224 }
225
226 let mut component = usv3_component();
227 if missing_attribute == "fee" {
228 component
229 .static_attributes
230 .remove("fee");
231 }
232
233 let snapshot = ComponentWithState {
234 state: ResponseProtocolState {
235 component_id: "State1".to_owned(),
236 attributes,
237 balances: HashMap::new(),
238 },
239 component,
240 component_tvl: None,
241 entrypoints: Vec::new(),
242 };
243
244 let result = try_decode_snapshot_with_defaults::<UniswapV3State>(snapshot).await;
245
246 assert!(result.is_err());
247 assert!(matches!(
248 result.err().unwrap(),
249 InvalidSnapshotError::MissingAttribute(attr) if attr == missing_attribute
250 ));
251 }
252
253 #[tokio::test]
254 async fn test_usv3_try_from_invalid_fee() {
255 let mut component = usv3_component();
257 component
258 .static_attributes
259 .insert("fee".to_string(), Bytes::from(4000_i32.to_be_bytes().to_vec()));
260
261 let snapshot = ComponentWithState {
262 state: ResponseProtocolState {
263 component_id: "State1".to_owned(),
264 attributes: usv3_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::ValueError(err) if err == *"Unsupported fee amount"
278 ));
279 }
280}