1use std::collections::{BTreeMap, HashMap};
2
3use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
4use tycho_common::{models::token::Token, Bytes};
5
6use super::{
7 attributes::{
8 apply_reserve, decode_bin_id_attribute, decode_bool_attribute, decode_u16_attribute,
9 decode_u32_attribute,
10 },
11 state::PancakeswapInfinityBinState,
12};
13use crate::{
14 evm::protocol::utils::uniswap::lp_fee::DYNAMIC_FEE_FLAG,
15 protocol::{
16 errors::InvalidSnapshotError,
17 models::{DecoderContext, TryFromWithBlock},
18 },
19};
20
21impl TryFromWithBlock<ComponentWithState, BlockHeader> for PancakeswapInfinityBinState {
22 type Error = InvalidSnapshotError;
23
24 async fn try_from_with_header(
35 snapshot: ComponentWithState,
36 _block: BlockHeader,
37 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
38 _all_tokens: &HashMap<Bytes, Token>,
39 _decoder_context: &DecoderContext,
40 ) -> Result<Self, Self::Error> {
41 let static_attrs = snapshot.component.static_attributes;
42 let state_attrs = snapshot.state.attributes;
43
44 let parameters = attribute(&static_attrs, "parameters")?;
47 if has_swap_hooks(parameters)? {
48 return Err(InvalidSnapshotError::ValueError(format!(
49 "pool registers a swap hook (parameters {parameters}); its quotes depend on the hook"
50 )));
51 }
52 let lp_fee = decode_u32_attribute("key_lp_fee", attribute(&static_attrs, "key_lp_fee")?)?;
55 if lp_fee == DYNAMIC_FEE_FLAG {
56 return Err(InvalidSnapshotError::ValueError(
57 "pool has a dynamic LP fee (key_lp_fee), set by its hook per swap".to_string(),
58 ));
59 }
60
61 let bin_step = decode_u16_attribute("bin_step", attribute(&static_attrs, "bin_step")?)?;
62 let active_id =
63 decode_bin_id_attribute("active_id", attribute(&state_attrs, "active_id")?)?;
64 let active_in_tree = match state_attrs.get("active_in_tree") {
67 Some(flag) => decode_bool_attribute("active_in_tree", flag)?,
68 None => true,
69 };
70 let protocol_fee = |key: &str| {
74 decode_u16_attribute(key, attribute(&state_attrs, key)?)
75 .map_err(InvalidSnapshotError::from)
76 };
77 let protocol_fee_zero_for_one = protocol_fee("protocol_fees/zero2one")?;
78 let protocol_fee_one_for_zero = protocol_fee("protocol_fees/one2zero")?;
79 let mut bins = BTreeMap::new();
80 for (key, value) in state_attrs
81 .iter()
82 .filter(|(key, _)| key.starts_with("bins/"))
83 {
84 apply_reserve(&mut bins, key, value)?;
85 }
86 bins.retain(|_, reserves| *reserves != (0, 0));
88
89 Self::new(
90 active_id,
91 active_in_tree,
92 bin_step,
93 lp_fee,
94 protocol_fee_zero_for_one,
95 protocol_fee_one_for_zero,
96 bins,
97 )
98 .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
99 }
100}
101
102const SWAP_HOOK_BITS: u16 = (1 << 6) | (1 << 7) | (1 << 10) | (1 << 11);
105
106fn has_swap_hooks(parameters: &Bytes) -> Result<bool, InvalidSnapshotError> {
108 let word: &[u8; 32] = parameters
109 .as_ref()
110 .try_into()
111 .map_err(|_not_32_bytes| {
112 InvalidSnapshotError::ValueError(format!(
113 "parameters is {} bytes, expected 32",
114 parameters.len()
115 ))
116 })?;
117 Ok(u16::from_be_bytes([word[30], word[31]]) & SWAP_HOOK_BITS != 0)
118}
119
120fn attribute<'a>(
122 attrs: &'a HashMap<String, Bytes>,
123 key: &str,
124) -> Result<&'a Bytes, InvalidSnapshotError> {
125 attrs
126 .get(key)
127 .ok_or_else(|| InvalidSnapshotError::MissingAttribute(key.to_string()))
128}
129
130#[cfg(test)]
131mod tests {
132 use chrono::DateTime;
133 use rstest::rstest;
134 use tycho_common::models::{
135 protocol::{ProtocolComponent, ProtocolComponentState},
136 Chain, ChangeType,
137 };
138
139 use super::{super::attributes::reserve_attributes, *};
140 use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
141
142 const ACTIVE_ID: u32 = 8_388_608;
143
144 fn component(static_attrs: &[(&str, Bytes)]) -> ProtocolComponent {
145 ProtocolComponent {
146 id: "0xbin".to_string(),
147 protocol_system: "pancakeswap_infinity_bin".to_string(),
148 protocol_type_name: "pancakeswap_infinity_bin_pool".to_string(),
149 chain: Chain::Base,
150 tokens: Vec::new(),
151 contract_addresses: Vec::new(),
152 static_attributes: static_attrs
153 .iter()
154 .map(|(key, value)| (key.to_string(), value.clone()))
155 .collect(),
156 change: ChangeType::Creation,
157 creation_tx: Bytes::from(vec![0u8; 32]),
158 created_at: DateTime::from_timestamp(1622526000, 0)
159 .unwrap()
160 .naive_utc(),
161 }
162 }
163
164 fn parameters(hooks_bitmap: u16) -> Bytes {
166 let mut word = vec![0u8; 32];
167 word[28..30].copy_from_slice(&10u16.to_be_bytes());
168 word[30..].copy_from_slice(&hooks_bitmap.to_be_bytes());
169 Bytes::from(word)
170 }
171
172 fn statics() -> Vec<(&'static str, Bytes)> {
174 vec![
175 ("bin_step", Bytes::from(10u16.to_be_bytes().to_vec())),
176 ("key_lp_fee", Bytes::from(vec![0x64])),
177 ("parameters", parameters(0)),
178 ]
179 }
180
181 fn snapshot(
183 static_attrs: &[(&str, Bytes)],
184 state_attrs: &[(&str, Bytes)],
185 ) -> ComponentWithState {
186 ComponentWithState {
187 state: ProtocolComponentState::new(
188 "0xbin",
189 state_attrs
190 .iter()
191 .map(|(key, value)| (key.to_string(), value.clone()))
192 .collect(),
193 HashMap::new(),
194 ),
195 component: component(static_attrs),
196 component_tvl: None,
197 entrypoints: Vec::new(),
198 }
199 }
200
201 fn with_bins<'a>(
203 attrs: &[(&'a str, Bytes)],
204 bins: &'a [(String, Bytes)],
205 ) -> Vec<(&'a str, Bytes)> {
206 attrs
207 .iter()
208 .cloned()
209 .chain(
210 bins.iter()
211 .map(|(key, value)| (key.as_str(), value.clone())),
212 )
213 .collect()
214 }
215
216 #[tokio::test]
218 async fn test_decodes_full_snapshot() {
219 let bins = reserve_attributes(ACTIVE_ID, 7, 11);
220 let snapshot = snapshot(
221 &statics(),
222 &with_bins(
223 &[
224 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
225 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
226 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
227 ],
228 &bins,
229 ),
230 );
231
232 let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
233 .await
234 .unwrap();
235
236 assert_eq!(state.bin_step, 10);
237 assert_eq!(state.active_id, ACTIVE_ID);
238 assert!(state.active_in_tree, "absent flag reads as in the tree");
239 assert_eq!(state.lp_fee, 100);
240 assert_eq!(state.protocol_fee_zero_for_one, 3);
241 assert_eq!(state.protocol_fee_one_for_zero, 5);
242 assert_eq!(state.bins[&ACTIVE_ID], (7, 11));
243 }
244
245 #[tokio::test]
246 async fn test_decodes_active_bin_outside_the_tree() {
247 let snapshot = snapshot(
248 &statics(),
249 &[
250 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
251 ("active_in_tree", Bytes::from(vec![0x00])),
252 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
253 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
254 ],
255 );
256
257 let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
258 .await
259 .unwrap();
260
261 assert!(!state.active_in_tree);
262 }
263
264 #[tokio::test]
267 async fn test_state_fee_attribute_is_ignored() {
268 let snapshot = snapshot(
269 &statics(),
270 &[
271 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
272 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
273 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
274 ("fee", Bytes::from(vec![0x01, 0xf4])),
275 ],
276 );
277
278 let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
279 .await
280 .unwrap();
281
282 assert_eq!(state.lp_fee, 100);
283 }
284
285 #[tokio::test]
287 #[rstest]
288 #[case::missing_bin_step("bin_step", "bin_step")]
289 #[case::missing_active_id("active_id", "active_id")]
290 #[case::missing_lp_fee("key_lp_fee", "key_lp_fee")]
291 #[case::missing_parameters("parameters", "parameters")]
292 #[case::missing_protocol_fee_zero2one("protocol_fees/zero2one", "protocol_fees/zero2one")]
293 #[case::missing_protocol_fee_one2zero("protocol_fees/one2zero", "protocol_fees/one2zero")]
294 async fn test_missing_required_attribute_errors(#[case] removed: &str, #[case] reported: &str) {
295 let statics: Vec<_> = statics()
296 .into_iter()
297 .filter(|(key, _)| *key != removed)
298 .collect();
299 let states: Vec<_> = [
300 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
301 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
302 ("protocol_fees/one2zero", Bytes::from(vec![0x03])),
303 ]
304 .into_iter()
305 .filter(|(key, _)| *key != removed)
306 .collect();
307
308 let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
309 &statics, &states,
310 ))
311 .await;
312
313 assert!(
314 matches!(
315 result,
316 Err(InvalidSnapshotError::MissingAttribute(ref attr)) if attr == reported
317 ),
318 "expected MissingAttribute({reported}), got {result:?}"
319 );
320 }
321
322 #[tokio::test]
325 #[rstest]
326 #[case::before_swap("parameters", parameters(1 << 6))]
327 #[case::after_swap("parameters", parameters(1 << 7))]
328 #[case::before_swap_returns_delta("parameters", parameters(1 << 10))]
329 #[case::after_swap_returns_delta("parameters", parameters(1 << 11))]
330 #[case::dynamic_lp_fee("key_lp_fee", Bytes::from(vec![0x00, 0x80, 0x00, 0x00]))]
332 #[case::short_parameters("parameters", Bytes::from(vec![0u8; 31]))]
333 async fn test_rejects_pools_it_cannot_quote(#[case] key: &str, #[case] value: Bytes) {
334 let mut statics = statics();
335 for (name, existing) in &mut statics {
336 if *name == key {
337 *existing = value.clone();
338 }
339 }
340
341 let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
342 &statics,
343 &[
344 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
345 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
346 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
347 ],
348 ))
349 .await;
350
351 assert!(
352 matches!(result, Err(InvalidSnapshotError::ValueError(_))),
353 "{key} = {value} decoded: {result:?}"
354 );
355 }
356
357 #[tokio::test]
360 async fn test_accepts_non_swap_hooks() {
361 let mut statics = statics();
362 statics[2].1 = parameters(0b11_0011_0011_1111);
363
364 let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
365 &statics,
366 &[
367 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
368 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
369 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
370 ],
371 ))
372 .await;
373
374 assert!(result.is_ok(), "non-swap hooks rejected: {result:?}");
375 }
376
377 #[tokio::test]
379 async fn test_skips_empty_bins() {
380 let bins: Vec<_> =
381 [reserve_attributes(ACTIVE_ID, 0, 1_000), reserve_attributes(ACTIVE_ID + 1, 0, 0)]
382 .concat();
383 let snapshot = snapshot(
384 &statics(),
385 &with_bins(
386 &[
387 ("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
388 ("protocol_fees/zero2one", Bytes::from(vec![0x03])),
389 ("protocol_fees/one2zero", Bytes::from(vec![0x05])),
390 ],
391 &bins,
392 ),
393 );
394
395 let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
396 .await
397 .unwrap();
398
399 assert_eq!(state.bins.len(), 1);
400 assert_eq!(state.bins[&ACTIVE_ID], (0, 1_000));
401 }
402}