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