tycho-simulation 0.525.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::collections::HashMap;

use alloy::primitives::U256;
use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
use tycho_common::{
    models::token::Token,
    simulation::protocol_sim::{BlockContext, ProtocolSim},
    Bytes,
};

use super::state::AerodromeSlipstreamsState;
use crate::{
    evm::protocol::utils::{
        slipstreams::{
            aero_hook_fee::AeroHookFee,
            dynamic_fee_module::DynamicFeeConfig,
            observations::{observation_slot, Observations},
        },
        uniswap::{i24_be_bytes_to_i32, tick_list::TickInfo},
    },
    protocol::{
        errors::InvalidSnapshotError,
        models::{DecoderContext, TryFromWithBlock},
    },
};

impl TryFromWithBlock<ComponentWithState, BlockHeader> for AerodromeSlipstreamsState {
    type Error = InvalidSnapshotError;

    /// Decodes a `ComponentWithState` into a `AerodromeSlipstreamsState`. Errors with a
    /// `InvalidSnapshotError` if the snapshot is missing any required attributes or if the fee
    /// amount is not supported.
    async fn try_from_with_header(
        snapshot: ComponentWithState,
        block: BlockHeader,
        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
        _all_tokens: &HashMap<Bytes, Token>,
        decoder_context: &DecoderContext,
    ) -> Result<Self, Self::Error> {
        let liq = snapshot
            .state
            .attributes
            .get("liquidity")
            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("liquidity".to_string()))?
            .clone();

        // This is a hotfix because if the liquidity has never been updated after creation, it's
        // currently encoded as H256::zero(), therefore, we can't decode this as u128.
        // We can remove this once it has been fixed on the tycho side.
        let liq_16_bytes = if liq.len() == 32 {
            // Make sure it only happens for 0 values, otherwise error.
            if liq == Bytes::zero(32) {
                Bytes::from([0; 16])
            } else {
                return Err(InvalidSnapshotError::ValueError(format!(
                    "Liquidity bytes too long for {liq}, expected 16"
                )));
            }
        } else {
            liq
        };

        let liquidity = u128::try_from(liq_16_bytes)?;

        let sqrt_price = U256::from_be_slice(
            snapshot
                .state
                .attributes
                .get("sqrt_price_x96")
                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("sqrt_price".to_string()))?,
        );

        let observation_index = u16::try_from(
            snapshot
                .state
                .attributes
                .get("observationIndex")
                .ok_or_else(|| {
                    InvalidSnapshotError::MissingAttribute("observationIndex".to_string())
                })?
                .clone(),
        )?;

        let observation_cardinality = u16::try_from(
            snapshot
                .state
                .attributes
                .get("observationCardinality")
                .ok_or_else(|| {
                    InvalidSnapshotError::MissingAttribute("observationCardinality".to_string())
                })?
                .clone(),
        )?;

        let dynamic_fee_config = DynamicFeeConfig::from_attributes(&snapshot.state.attributes)
            .map_err(InvalidSnapshotError::ValueError)?;
        // `aero_cl` components carry the AERO swap hook's settings instead of a fee module's.
        let aero_hook = snapshot
            .state
            .attributes
            .contains_key("hook_seconds_ago")
            .then(|| AeroHookFee::from_attributes(&snapshot.state.attributes))
            .transpose()
            .map_err(InvalidSnapshotError::ValueError)?;

        let tick_spacing = snapshot
            .component
            .static_attributes
            .get("tick_spacing")
            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick_spacing".to_string()))?
            .clone();

        let tick_spacing_4_bytes = if tick_spacing.len() == 32 {
            // Make sure it only happens for 0 values, otherwise error.
            if tick_spacing == Bytes::zero(32) {
                Bytes::from([0; 4])
            } else {
                return Err(InvalidSnapshotError::ValueError(format!(
                    "Tick Spacing bytes too long for {tick_spacing}, expected 4"
                )));
            }
        } else {
            tick_spacing
        };

        let tick_spacing = i24_be_bytes_to_i32(&tick_spacing_4_bytes);

        let default_fee = u32::try_from(
            snapshot
                .component
                .static_attributes
                .get("default_fee")
                .ok_or_else(|| InvalidSnapshotError::MissingAttribute("default_fee".to_string()))?
                .clone(),
        )?;

        let tick = snapshot
            .state
            .attributes
            .get("tick")
            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("tick".to_string()))?
            .clone();

        // This is a hotfix because if the tick has never been updated after creation, it's
        // currently encoded as H256::zero(), therefore, we can't decode this as i32. We can
        // remove this this will be fixed on the tycho side.
        let ticks_4_bytes = if tick.len() == 32 {
            // Make sure it only happens for 0 values, otherwise error.
            if tick == Bytes::zero(32) {
                Bytes::from([0; 4])
            } else {
                return Err(InvalidSnapshotError::ValueError(format!(
                    "Tick bytes too long for {tick}, expected 4"
                )));
            }
        } else {
            tick
        };
        let tick = i24_be_bytes_to_i32(&ticks_4_bytes);

        let ticks: Result<Vec<_>, _> = snapshot
            .state
            .attributes
            .iter()
            .filter_map(|(key, value)| {
                if key.starts_with("ticks/") {
                    Some(
                        key.split('/')
                            .nth(1)?
                            .parse::<i32>()
                            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
                            .and_then(|tick_index| {
                                TickInfo::new(tick_index, i128::try_from(value.clone())?).map_err(
                                    |err| InvalidSnapshotError::ValueError(err.to_string()),
                                )
                            }),
                    )
                } else {
                    None
                }
            })
            .collect();

        let mut ticks = match ticks {
            Ok(ticks) if !ticks.is_empty() => ticks
                .into_iter()
                .filter(|t| t.net_liquidity != 0)
                .collect::<Vec<_>>(),
            _ => return Err(InvalidSnapshotError::MissingAttribute("tick_liquidities".to_string())),
        };

        ticks.sort_by_key(|tick| tick.index);

        // The oracle is a ring addressed by index, and lookups read slot `i` as position `i`, so
        // each observation goes to its own index.
        let mut words = Vec::new();
        for (key, value) in &snapshot.state.attributes {
            let Some(slot) = observation_slot(key) else {
                continue;
            };
            let slot = slot.map_err(InvalidSnapshotError::ValueError)?;
            words.push((slot, value.as_ref()));
        }
        let observations = Observations::from_words(words)
            .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))?
            .into_slots();
        if observations.is_empty() {
            return Err(InvalidSnapshotError::MissingAttribute("observations".to_string()));
        }

        AerodromeSlipstreamsState::new(
            snapshot.component.id,
            // Seed value only: the stream decoder points every block-sensitive state at the
            // execution block before the snapshot reaches a consumer.
            block.timestamp,
            liquidity,
            sqrt_price,
            observation_index,
            observation_cardinality,
            default_fee,
            tick_spacing,
            tick,
            ticks,
            observations,
            dynamic_fee_config,
        )
        .map(|state| {
            let mut state = match aero_hook {
                Some(hook) => state.with_aero_hook(hook),
                None => state,
            }
            .with_position_assumption(decoder_context.block_position);
            state.apply_block(&BlockContext::new(block.number, block.timestamp));
            state
        })
        .map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use alloy::primitives::U256;
    use rstest::rstest;
    use tycho_client::feed::synchronizer::ComponentWithState;
    use tycho_common::{
        models::protocol::{ProtocolComponent, ProtocolComponentState},
        Bytes,
    };

    use super::*;
    use crate::evm::protocol::{
        test_utils::try_decode_snapshot_with_defaults,
        utils::{
            slipstreams::{dynamic_fee_module::DynamicFeeConfig, observations::Observation},
            uniswap::{tick_list::TickInfo, tick_math::get_sqrt_ratio_at_tick},
        },
    };

    const STALE_DYNAMIC_FEE_MODULE: [u8; 20] =
        hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D");
    fn snapshot(dynamic_fee_module: Option<Bytes>) -> ComponentWithState {
        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("tick zero should have a sqrt price");
        let initialized_observation = (U256::from(1) << 248_u32).to_be_bytes::<32>();
        let mut attributes = HashMap::from([
            ("liquidity".to_string(), Bytes::from(100_u128.to_be_bytes())),
            ("sqrt_price_x96".to_string(), Bytes::from(sqrt_price.to_be_bytes::<32>())),
            ("observationIndex".to_string(), Bytes::from(0_u16.to_be_bytes())),
            ("observationCardinality".to_string(), Bytes::from(1_u16.to_be_bytes())),
            ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
            ("dfc_scalingFactor".to_string(), Bytes::from(6_000_000_u64.to_be_bytes())),
            ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
            ("dfc_initialFeeEnabled".to_string(), Bytes::from([1_u8])),
            ("dfc_initialFee".to_string(), Bytes::from(30_u32.to_be_bytes())),
            ("tick".to_string(), Bytes::from(0_i32.to_be_bytes())),
            ("ticks/-1".to_string(), Bytes::from(1_i128.to_be_bytes())),
            ("ticks/1".to_string(), Bytes::from((-1_i128).to_be_bytes())),
            ("observations/0".to_string(), Bytes::from(initialized_observation)),
        ]);
        if let Some(dynamic_fee_module) = dynamic_fee_module {
            attributes.insert("dynamic_fee_module".to_string(), dynamic_fee_module);
        }

        ComponentWithState {
            state: ProtocolComponentState::new("test-pool", attributes, HashMap::new()),
            component: ProtocolComponent {
                id: "test-pool".to_string(),
                static_attributes: HashMap::from([
                    ("default_fee".to_string(), Bytes::from(100_u32.to_be_bytes())),
                    ("tick_spacing".to_string(), Bytes::from(1_i32.to_be_bytes())),
                ]),
                ..Default::default()
            },
            component_tvl: None,
            entrypoints: Vec::new(),
        }
    }

    fn expected_state(dfc: DynamicFeeConfig) -> AerodromeSlipstreamsState {
        expected_state_with_ring(
            dfc,
            0,
            1,
            vec![Observation { initialized: true, ..Default::default() }],
        )
    }

    fn expected_state_with_ring(
        dfc: DynamicFeeConfig,
        observation_index: u16,
        observation_cardinality: u16,
        observations: Vec<Observation>,
    ) -> AerodromeSlipstreamsState {
        AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            0,
            100,
            get_sqrt_ratio_at_tick(0).expect("tick zero should have a sqrt price"),
            observation_index,
            observation_cardinality,
            100,
            1,
            0,
            vec![TickInfo::new(-1, 1).unwrap(), TickInfo::new(1, -1).unwrap()],
            observations,
            dfc,
        )
        .expect("test state should be valid")
    }

    #[tokio::test]
    async fn observations_are_placed_at_their_ring_index() {
        // Slots 1 and 3 were prefilled by `increaseObservationCardinalityNext` and never written,
        // so the indexer sends each as the single byte 0x01; slot 2 holds the newest observation.
        // Each written slot must sit at its own index, as lookups read position `i` as slot `i`;
        // the prefilled ones read as uninitialized whether stored or not, so they are not.
        let mut snapshot = snapshot(None);
        let newest = ((U256::from(1) << 248_u32) | U256::from(5_u32)).to_be_bytes::<32>();
        let attributes = &mut snapshot.state.attributes;
        attributes.insert("observations/1".to_string(), Bytes::from([0x01_u8]));
        attributes.insert("observations/2".to_string(), Bytes::from(newest));
        attributes.insert("observations/3".to_string(), Bytes::from([0x01_u8]));
        attributes.insert("observationIndex".to_string(), Bytes::from(2_u16.to_be_bytes()));
        attributes.insert("observationCardinality".to_string(), Bytes::from(3_u16.to_be_bytes()));

        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot)
            .await
            .expect("snapshot should decode");

        assert_eq!(
            decoded,
            expected_state_with_ring(
                DynamicFeeConfig::default(),
                2,
                3,
                vec![
                    Observation { initialized: true, ..Default::default() },
                    Observation::default(),
                    Observation { block_timestamp: 5, initialized: true, ..Default::default() },
                ],
            )
        );
    }

    #[tokio::test]
    async fn observation_slot_past_the_ring_fails_to_decode() {
        // The pool's ring is `Observation[65535]`, so slot 65,535 is malformed rather than a slot
        // to grow the ring to.
        let mut snapshot = snapshot(None);
        snapshot.state.attributes.insert(
            "observations/65535".to_string(),
            Bytes::from((U256::from(1) << 248_u32).to_be_bytes::<32>()),
        );

        let result = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot).await;

        let Err(InvalidSnapshotError::ValueError(message)) = result else {
            panic!("expected a ValueError, got {result:?}");
        };
        assert!(message.starts_with("observations/65535"), "{message}");
    }

    #[rstest]
    #[case::missing_module(None)]
    #[case::stale_module(Some(Bytes::from(STALE_DYNAMIC_FEE_MODULE)))]
    #[tokio::test]
    async fn missing_or_unsupported_module_falls_back_to_default_config(
        #[case] dynamic_fee_module: Option<Bytes>,
    ) {
        // Still decodable with a default config, not dropped: these pools quote their default_fee.
        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot(
            dynamic_fee_module,
        ))
        .await
        .expect("pools without a supported marker should remain decodable");

        assert_eq!(decoded, expected_state(DynamicFeeConfig::default()));
    }

    #[rstest]
    #[case::factory_5e7b(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"), 480)]
    #[case::factory_ade6(hex_literal::hex!("F4Ecd78EBEB6d36CF7f80B5B6B41453515fe2785"), 480)]
    #[case::factory_f8f2(hex_literal::hex!("87D8f999BBa9343E8099552426775B51C338E8CB"), 30)]
    #[tokio::test]
    async fn supported_module_defaults_missing_initial_fee_attributes(
        #[case] dynamic_fee_module: [u8; 20],
        #[case] seconds_ago: u32,
    ) {
        let mut snapshot = snapshot(Some(Bytes::from(dynamic_fee_module)));
        snapshot
            .state
            .attributes
            .remove("dfc_initialFeeEnabled");
        snapshot
            .state
            .attributes
            .remove("dfc_initialFee");

        let decoded = try_decode_snapshot_with_defaults::<AerodromeSlipstreamsState>(snapshot)
            .await
            .expect("new module updates should work with pre-upgrade pool state");

        assert_eq!(
            decoded,
            expected_state(
                DynamicFeeConfig::new(500, 700, 6_000_000, false, 0).with_seconds_ago(seconds_ago)
            )
        );
    }
}