Skip to main content

tycho_simulation/evm/protocol/aerodrome_slipstreams/
decoder.rs

1use std::collections::HashMap;
2
3use alloy::primitives::U256;
4use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
5use tycho_common::{
6    models::token::Token,
7    simulation::protocol_sim::{BlockContext, ProtocolSim},
8    Bytes,
9};
10
11use super::state::AerodromeSlipstreamsState;
12use crate::{
13    evm::protocol::utils::{
14        slipstreams::{
15            aero_hook_fee::AeroHookFee,
16            dynamic_fee_module::DynamicFeeConfig,
17            observations::{observation_slot, Observations},
18        },
19        uniswap::{i24_be_bytes_to_i32, tick_list::TickInfo},
20    },
21    protocol::{
22        errors::InvalidSnapshotError,
23        models::{DecoderContext, TryFromWithBlock},
24    },
25};
26
27impl TryFromWithBlock<ComponentWithState, BlockHeader> for AerodromeSlipstreamsState {
28    type Error = InvalidSnapshotError;
29
30    /// Decodes a `ComponentWithState` into a `AerodromeSlipstreamsState`. Errors with a
31    /// `InvalidSnapshotError` if the snapshot is missing any required attributes or if the fee
32    /// amount is not supported.
33    async fn try_from_with_header(
34        snapshot: ComponentWithState,
35        block: BlockHeader,
36        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
37        _all_tokens: &HashMap<Bytes, Token>,
38        decoder_context: &DecoderContext,
39    ) -> Result<Self, Self::Error> {
40        let liq = snapshot
41            .state
42            .attributes
43            .get("liquidity")
44            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("liquidity".to_string()))?
45            .clone();
46
47        // This is a hotfix because if the liquidity has never been updated after creation, it's
48        // currently encoded as H256::zero(), therefore, we can't decode this as u128.
49        // We can remove this once it has been fixed on the tycho side.
50        let liq_16_bytes = if liq.len() == 32 {
51            // Make sure it only happens for 0 values, otherwise error.
52            if liq == Bytes::zero(32) {
53                Bytes::from([0; 16])
54            } else {
55                return Err(InvalidSnapshotError::ValueError(format!(
56                    "Liquidity bytes too long for {liq}, expected 16"
57                )));
58            }
59        } else {
60            liq
61        };
62
63        let liquidity = u128::try_from(liq_16_bytes)?;
64
65        let sqrt_price = U256::from_be_slice(
66            snapshot
67                .state
68                .attributes
69                .get("sqrt_price_x96")
70                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("sqrt_price".to_string()))?,
71        );
72
73        let observation_index = u16::try_from(
74            snapshot
75                .state
76                .attributes
77                .get("observationIndex")
78                .ok_or_else(|| {
79                    InvalidSnapshotError::MissingAttribute("observationIndex".to_string())
80                })?
81                .clone(),
82        )?;
83
84        let observation_cardinality = u16::try_from(
85            snapshot
86                .state
87                .attributes
88                .get("observationCardinality")
89                .ok_or_else(|| {
90                    InvalidSnapshotError::MissingAttribute("observationCardinality".to_string())
91                })?
92                .clone(),
93        )?;
94
95        let dynamic_fee_config = DynamicFeeConfig::from_attributes(&snapshot.state.attributes)
96            .map_err(InvalidSnapshotError::ValueError)?;
97        // `aero_cl` components carry the AERO swap hook's settings instead of a fee module's.
98        let aero_hook = snapshot
99            .state
100            .attributes
101            .contains_key("hook_seconds_ago")
102            .then(|| AeroHookFee::from_attributes(&snapshot.state.attributes))
103            .transpose()
104            .map_err(InvalidSnapshotError::ValueError)?;
105
106        let tick_spacing = snapshot
107            .component
108            .static_attributes
109            .get("tick_spacing")
110            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick_spacing".to_string()))?
111            .clone();
112
113        let tick_spacing_4_bytes = if tick_spacing.len() == 32 {
114            // Make sure it only happens for 0 values, otherwise error.
115            if tick_spacing == Bytes::zero(32) {
116                Bytes::from([0; 4])
117            } else {
118                return Err(InvalidSnapshotError::ValueError(format!(
119                    "Tick Spacing bytes too long for {tick_spacing}, expected 4"
120                )));
121            }
122        } else {
123            tick_spacing
124        };
125
126        let tick_spacing = i24_be_bytes_to_i32(&tick_spacing_4_bytes);
127
128        let default_fee = u32::try_from(
129            snapshot
130                .component
131                .static_attributes
132                .get("default_fee")
133                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("default_fee".to_string()))?
134                .clone(),
135        )?;
136
137        let tick = snapshot
138            .state
139            .attributes
140            .get("tick")
141            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick".to_string()))?
142            .clone();
143
144        // This is a hotfix because if the tick has never been updated after creation, it's
145        // currently encoded as H256::zero(), therefore, we can't decode this as i32. We can
146        // remove this this will be fixed on the tycho side.
147        let ticks_4_bytes = if tick.len() == 32 {
148            // Make sure it only happens for 0 values, otherwise error.
149            if tick == Bytes::zero(32) {
150                Bytes::from([0; 4])
151            } else {
152                return Err(InvalidSnapshotError::ValueError(format!(
153                    "Tick bytes too long for {tick}, expected 4"
154                )));
155            }
156        } else {
157            tick
158        };
159        let tick = i24_be_bytes_to_i32(&ticks_4_bytes);
160
161        let ticks: Result<Vec<_>, _> = snapshot
162            .state
163            .attributes
164            .iter()
165            .filter_map(|(key, value)| {
166                if key.starts_with("ticks/") {
167                    Some(
168                        key.split('/')
169                            .nth(1)?
170                            .parse::<i32>()
171                            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
172                            .and_then(|tick_index| {
173                                TickInfo::new(tick_index, i128::try_from(value.clone())?).map_err(
174                                    |err| InvalidSnapshotError::ValueError(err.to_string()),
175                                )
176                            }),
177                    )
178                } else {
179                    None
180                }
181            })
182            .collect();
183
184        let mut ticks = match ticks {
185            Ok(ticks) if !ticks.is_empty() => ticks
186                .into_iter()
187                .filter(|t| t.net_liquidity != 0)
188                .collect::<Vec<_>>(),
189            _ => return Err(InvalidSnapshotError::MissingAttribute("tick_liquidities".to_string())),
190        };
191
192        ticks.sort_by_key(|tick| tick.index);
193
194        // The oracle is a ring addressed by index, and lookups read slot `i` as position `i`, so
195        // each observation goes to its own index.
196        let mut words = Vec::new();
197        for (key, value) in &snapshot.state.attributes {
198            let Some(slot) = observation_slot(key) else {
199                continue;
200            };
201            let slot = slot.map_err(InvalidSnapshotError::ValueError)?;
202            words.push((slot, value.as_ref()));
203        }
204        let observations = Observations::from_words(words)
205            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))?
206            .into_slots();
207        if observations.is_empty() {
208            return Err(InvalidSnapshotError::MissingAttribute("observations".to_string()));
209        }
210
211        AerodromeSlipstreamsState::new(
212            snapshot.component.id,
213            // Seed value only: the stream decoder points every block-sensitive state at the
214            // execution block before the snapshot reaches a consumer.
215            block.timestamp,
216            liquidity,
217            sqrt_price,
218            observation_index,
219            observation_cardinality,
220            default_fee,
221            tick_spacing,
222            tick,
223            ticks,
224            observations,
225            dynamic_fee_config,
226        )
227        .map(|state| {
228            let mut state = match aero_hook {
229                Some(hook) => state.with_aero_hook(hook),
230                None => state,
231            }
232            .with_position_assumption(decoder_context.block_position);
233            state.apply_block(&BlockContext::new(block.number, block.timestamp));
234            state
235        })
236        .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use alloy::primitives::U256;
243    use rstest::rstest;
244    use tycho_client::feed::synchronizer::ComponentWithState;
245    use tycho_common::{
246        models::protocol::{ProtocolComponent, ProtocolComponentState},
247        Bytes,
248    };
249
250    use super::*;
251    use crate::evm::protocol::{
252        test_utils::try_decode_snapshot_with_defaults,
253        utils::{
254            slipstreams::{dynamic_fee_module::DynamicFeeConfig, observations::Observation},
255            uniswap::{tick_list::TickInfo, tick_math::get_sqrt_ratio_at_tick},
256        },
257    };
258
259    const STALE_DYNAMIC_FEE_MODULE: [u8; 20] =
260        hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D");
261    fn snapshot(dynamic_fee_module: Option<Bytes>) -> ComponentWithState {
262        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("tick zero should have a sqrt price");
263        let initialized_observation = (U256::from(1) << 248_u32).to_be_bytes::<32>();
264        let mut attributes = HashMap::from([
265            ("liquidity".to_string(), Bytes::from(100_u128.to_be_bytes())),
266            ("sqrt_price_x96".to_string(), Bytes::from(sqrt_price.to_be_bytes::<32>())),
267            ("observationIndex".to_string(), Bytes::from(0_u16.to_be_bytes())),
268            ("observationCardinality".to_string(), Bytes::from(1_u16.to_be_bytes())),
269            ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
270            ("dfc_scalingFactor".to_string(), Bytes::from(6_000_000_u64.to_be_bytes())),
271            ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
272            ("dfc_initialFeeEnabled".to_string(), Bytes::from([1_u8])),
273            ("dfc_initialFee".to_string(), Bytes::from(30_u32.to_be_bytes())),
274            ("tick".to_string(), Bytes::from(0_i32.to_be_bytes())),
275            ("ticks/-1".to_string(), Bytes::from(1_i128.to_be_bytes())),
276            ("ticks/1".to_string(), Bytes::from((-1_i128).to_be_bytes())),
277            ("observations/0".to_string(), Bytes::from(initialized_observation)),
278        ]);
279        if let Some(dynamic_fee_module) = dynamic_fee_module {
280            attributes.insert("dynamic_fee_module".to_string(), dynamic_fee_module);
281        }
282
283        ComponentWithState {
284            state: ProtocolComponentState::new("test-pool", attributes, HashMap::new()),
285            component: ProtocolComponent {
286                id: "test-pool".to_string(),
287                static_attributes: HashMap::from([
288                    ("default_fee".to_string(), Bytes::from(100_u32.to_be_bytes())),
289                    ("tick_spacing".to_string(), Bytes::from(1_i32.to_be_bytes())),
290                ]),
291                ..Default::default()
292            },
293            component_tvl: None,
294            entrypoints: Vec::new(),
295        }
296    }
297
298    fn expected_state(dfc: DynamicFeeConfig) -> AerodromeSlipstreamsState {
299        expected_state_with_ring(
300            dfc,
301            0,
302            1,
303            vec![Observation { initialized: true, ..Default::default() }],
304        )
305    }
306
307    fn expected_state_with_ring(
308        dfc: DynamicFeeConfig,
309        observation_index: u16,
310        observation_cardinality: u16,
311        observations: Vec<Observation>,
312    ) -> AerodromeSlipstreamsState {
313        AerodromeSlipstreamsState::new(
314            "test-pool".to_string(),
315            0,
316            100,
317            get_sqrt_ratio_at_tick(0).expect("tick zero should have a sqrt price"),
318            observation_index,
319            observation_cardinality,
320            100,
321            1,
322            0,
323            vec![TickInfo::new(-1, 1).unwrap(), TickInfo::new(1, -1).unwrap()],
324            observations,
325            dfc,
326        )
327        .expect("test state should be valid")
328    }
329
330    #[tokio::test]
331    async fn observations_are_placed_at_their_ring_index() {
332        // Slots 1 and 3 were prefilled by `increaseObservationCardinalityNext` and never written,
333        // so the indexer sends each as the single byte 0x01; slot 2 holds the newest observation.
334        // Each written slot must sit at its own index, as lookups read position `i` as slot `i`;
335        // the prefilled ones read as uninitialized whether stored or not, so they are not.
336        let mut snapshot = snapshot(None);
337        let newest = ((U256::from(1) << 248_u32) | U256::from(5_u32)).to_be_bytes::<32>();
338        let attributes = &mut snapshot.state.attributes;
339        attributes.insert("observations/1".to_string(), Bytes::from([0x01_u8]));
340        attributes.insert("observations/2".to_string(), Bytes::from(newest));
341        attributes.insert("observations/3".to_string(), Bytes::from([0x01_u8]));
342        attributes.insert("observationIndex".to_string(), Bytes::from(2_u16.to_be_bytes()));
343        attributes.insert("observationCardinality".to_string(), Bytes::from(3_u16.to_be_bytes()));
344
345        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot)
346            .await
347            .expect("snapshot should decode");
348
349        assert_eq!(
350            decoded,
351            expected_state_with_ring(
352                DynamicFeeConfig::default(),
353                2,
354                3,
355                vec![
356                    Observation { initialized: true, ..Default::default() },
357                    Observation::default(),
358                    Observation { block_timestamp: 5, initialized: true, ..Default::default() },
359                ],
360            )
361        );
362    }
363
364    #[tokio::test]
365    async fn observation_slot_past_the_ring_fails_to_decode() {
366        // The pool's ring is `Observation[65535]`, so slot 65,535 is malformed rather than a slot
367        // to grow the ring to.
368        let mut snapshot = snapshot(None);
369        snapshot.state.attributes.insert(
370            "observations/65535".to_string(),
371            Bytes::from((U256::from(1) << 248_u32).to_be_bytes::<32>()),
372        );
373
374        let result = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot).await;
375
376        let Err(InvalidSnapshotError::ValueError(message)) = result else {
377            panic!("expected a ValueError, got {result:?}");
378        };
379        assert!(message.starts_with("observations/65535"), "{message}");
380    }
381
382    #[rstest]
383    #[case::missing_module(None)]
384    #[case::stale_module(Some(Bytes::from(STALE_DYNAMIC_FEE_MODULE)))]
385    #[tokio::test]
386    async fn missing_or_unsupported_module_falls_back_to_default_config(
387        #[case] dynamic_fee_module: Option<Bytes>,
388    ) {
389        // Still decodable with a default config, not dropped: these pools quote their default_fee.
390        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot(
391            dynamic_fee_module,
392        ))
393        .await
394        .expect("pools without a supported marker should remain decodable");
395
396        assert_eq!(decoded, expected_state(DynamicFeeConfig::default()));
397    }
398
399    #[rstest]
400    #[case::factory_5e7b(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"), 480)]
401    #[case::factory_ade6(hex_literal::hex!("F4Ecd78EBEB6d36CF7f80B5B6B41453515fe2785"), 480)]
402    #[case::factory_f8f2(hex_literal::hex!("87D8f999BBa9343E8099552426775B51C338E8CB"), 30)]
403    #[tokio::test]
404    async fn supported_module_defaults_missing_initial_fee_attributes(
405        #[case] dynamic_fee_module: [u8; 20],
406        #[case] seconds_ago: u32,
407    ) {
408        let mut snapshot = snapshot(Some(Bytes::from(dynamic_fee_module)));
409        snapshot
410            .state
411            .attributes
412            .remove("dfc_initialFeeEnabled");
413        snapshot
414            .state
415            .attributes
416            .remove("dfc_initialFee");
417
418        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot)
419            .await
420            .expect("new module updates should work with pre-upgrade pool state");
421
422        assert_eq!(
423            decoded,
424            expected_state(
425                DynamicFeeConfig::new(500, 700, 6_000_000, false, 0).with_seconds_ago(seconds_ago)
426            )
427        );
428    }
429}