Skip to main content

tycho_simulation/evm/protocol/sky/
decoder.rs

1use 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::state::{JoinEscrows, SkyComponentKind, SkyState};
8use crate::protocol::{
9    errors::InvalidSnapshotError,
10    models::{DecoderContext, TryFromWithBlock},
11};
12
13impl TryFromWithBlock<ComponentWithState, BlockHeader> for SkyState {
14    type Error = InvalidSnapshotError;
15
16    /// Decodes a `ComponentWithState` into a `SkyState`, dispatching on the
17    /// `component_type` static attribute (`psm`, `psm_wrapper` or `converter`).
18    async fn try_from_with_header(
19        snapshot: ComponentWithState,
20        _block: BlockHeader,
21        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
22        all_tokens: &HashMap<Bytes, Token>,
23        _decoder_context: &DecoderContext,
24    ) -> Result<Self, Self::Error> {
25        let kind = match snapshot
26            .component
27            .static_attributes
28            .get("component_type")
29            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("component_type".to_string()))?
30            .as_ref()
31        {
32            b"psm" => SkyComponentKind::Psm,
33            b"psm_wrapper" => SkyComponentKind::PsmWrapper,
34            b"converter" => SkyComponentKind::Converter,
35            other => {
36                return Err(InvalidSnapshotError::ValueError(format!(
37                    "unknown sky component_type: {}",
38                    String::from_utf8_lossy(other)
39                )))
40            }
41        };
42
43        let tokens = snapshot
44            .component
45            .tokens
46            .iter()
47            .map(|address| {
48                all_tokens
49                    .get(address)
50                    .cloned()
51                    .ok_or_else(|| {
52                        InvalidSnapshotError::ValueError(format!("unknown token {address}"))
53                    })
54            })
55            .collect::<Result<Vec<_>, _>>()?;
56        let [a, b] = tokens
57            .try_into()
58            .map_err(|tokens: Vec<_>| {
59                InvalidSnapshotError::ValueError(format!(
60                    "sky components have exactly two tokens, got {}",
61                    tokens.len()
62                ))
63            })?;
64
65        // Token roles come from the `gem` static attribute (also the swap encoder's
66        // direction source), so the token list order does not matter.
67        let gem_address = snapshot
68            .component
69            .static_attributes
70            .get("gem")
71            .ok_or_else(|| InvalidSnapshotError::MissingAttribute("gem".to_string()))?;
72        let (stable, gem) = if b.address == *gem_address {
73            (a, b)
74        } else if a.address == *gem_address {
75            (b, a)
76        } else {
77            return Err(InvalidSnapshotError::ValueError(format!(
78                "gem attribute {gem_address} is not among the component tokens"
79            )));
80        };
81        // The state's conversion factor is 10^(stable.decimals - gem.decimals);
82        // reject the inverted case up front so that unsigned subtraction cannot
83        // underflow (and, wrapping, turn the factor into a zero divisor).
84        if gem.decimals > stable.decimals {
85            return Err(InvalidSnapshotError::ValueError(format!(
86                "gem decimals ({}) exceed stable decimals ({})",
87                gem.decimals, stable.decimals
88            )));
89        }
90
91        let get_fee = |name: &str| -> Result<U256, InvalidSnapshotError> {
92            match kind {
93                // The converter is immutable and feeless; no attributes are indexed.
94                SkyComponentKind::Converter => Ok(U256::ZERO),
95                SkyComponentKind::Psm | SkyComponentKind::PsmWrapper => snapshot
96                    .state
97                    .attributes
98                    .get(name)
99                    .map(|value| U256::from_be_slice(value))
100                    .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_string())),
101            }
102        };
103        let get_balance = |token: &Token| -> Result<U256, InvalidSnapshotError> {
104            snapshot
105                .state
106                .balances
107                .get(&token.address)
108                .map(|balance| U256::from_be_slice(balance))
109                .ok_or_else(|| {
110                    // Every sky component carries both balances from creation (the
111                    // substreams package seeds them explicitly), so absence means a
112                    // corrupt or stale snapshot, not a zero balance.
113                    InvalidSnapshotError::ValueError(format!(
114                        "missing balance for token {} on component {}",
115                        token.address, snapshot.component.id
116                    ))
117                })
118        };
119
120        let (stable_balance, gem_balance) = (get_balance(&stable)?, get_balance(&gem)?);
121
122        let get_escrow = |name: &str| -> Result<U256, InvalidSnapshotError> {
123            snapshot
124                .state
125                .attributes
126                .get(name)
127                .map(|value| U256::from_be_slice(value))
128                .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_string()))
129        };
130        // The wrapper's in-flight DAI <-> USDS conversion is bounded by the join
131        // escrows, seeded at creation like the fees.
132        let escrows = match kind {
133            SkyComponentKind::PsmWrapper => Some(JoinEscrows {
134                dai: get_escrow("dai_escrow")?,
135                usds: get_escrow("usds_escrow")?,
136            }),
137            SkyComponentKind::Psm | SkyComponentKind::Converter => None,
138        };
139
140        Ok(SkyState::new(
141            snapshot.component.id.to_string(),
142            kind,
143            stable,
144            gem,
145            get_fee("tin")?,
146            get_fee("tout")?,
147            stable_balance,
148            gem_balance,
149            escrows,
150        ))
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use std::str::FromStr;
157
158    use rstest::rstest;
159    use tycho_common::{
160        models::{
161            protocol::{ProtocolComponent, ProtocolComponentState},
162            Chain,
163        },
164        Bytes,
165    };
166
167    use super::*;
168
169    async fn decode(
170        snapshot: ComponentWithState,
171        all_tokens: &HashMap<Bytes, Token>,
172    ) -> Result<SkyState, InvalidSnapshotError> {
173        SkyState::try_from_with_header(
174            snapshot,
175            Default::default(),
176            &HashMap::default(),
177            all_tokens,
178            &Default::default(),
179        )
180        .await
181    }
182
183    const PSM_ID: &str = "0xf6e72db5454dd049d0788e411b06cfaf16853042";
184    const DAI: &str = "0x6b175474e89094c44da98b954eedeac495271d0f";
185    const USDC: &str = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
186    const USDS: &str = "0xdc035d45d973e3ec169d2276ddab16f1e407384f";
187
188    fn token(address: &str, symbol: &str, decimals: u32) -> Token {
189        Token::new(
190            &Bytes::from_str(address).unwrap(),
191            symbol,
192            decimals,
193            0,
194            &[Some(50_000)],
195            Chain::Ethereum,
196            100,
197        )
198    }
199
200    fn all_tokens() -> HashMap<Bytes, Token> {
201        [token(DAI, "DAI", 18), token(USDC, "USDC", 6), token(USDS, "USDS", 18)]
202            .into_iter()
203            .map(|t| (t.address.clone(), t))
204            .collect()
205    }
206
207    fn snapshot(
208        id: &str,
209        component_type: &str,
210        gem: &str,
211        tokens: &[&str],
212        with_fees: bool,
213    ) -> ComponentWithState {
214        let attributes = if with_fees {
215            HashMap::from([
216                ("tin".to_string(), Bytes::from(U256::ZERO.to_be_bytes_vec())),
217                ("tout".to_string(), Bytes::from(U256::from(2u8).to_be_bytes_vec())),
218            ])
219        } else {
220            HashMap::new()
221        };
222        ComponentWithState {
223            state: ProtocolComponentState {
224                component_id: id.to_string(),
225                attributes,
226                balances: HashMap::from([
227                    (
228                        Bytes::from_str(tokens[0]).unwrap(),
229                        Bytes::from(U256::from(1000u64).to_be_bytes_vec()),
230                    ),
231                    (
232                        Bytes::from_str(tokens[1]).unwrap(),
233                        Bytes::from(U256::from(2000u64).to_be_bytes_vec()),
234                    ),
235                ]),
236            },
237            component: ProtocolComponent {
238                id: id.to_string(),
239                tokens: tokens
240                    .iter()
241                    .map(|t| Bytes::from_str(t).unwrap())
242                    .collect(),
243                static_attributes: HashMap::from([
244                    ("component_type".to_string(), Bytes::from(component_type.as_bytes().to_vec())),
245                    ("gem".to_string(), Bytes::from_str(gem).unwrap()),
246                ]),
247                ..Default::default()
248            },
249            component_tvl: None,
250            entrypoints: Vec::new(),
251        }
252    }
253
254    #[rstest]
255    #[case::stable_first(vec![DAI, USDC])]
256    #[case::gem_first(vec![USDC, DAI])]
257    #[tokio::test]
258    async fn decodes_psm_regardless_of_token_order(#[case] tokens: Vec<&str>) {
259        let snap = snapshot(PSM_ID, "psm", USDC, &tokens, true);
260        let state = decode(snap, &all_tokens())
261            .await
262            .unwrap();
263        assert_eq!(state.kind, SkyComponentKind::Psm);
264    }
265
266    #[tokio::test]
267    async fn decodes_converter_without_fee_attributes() {
268        let snap = snapshot(
269            "0x3225737a9bbb6473cb4a45b7244aca2befdb276a",
270            "converter",
271            USDS,
272            &[DAI, USDS],
273            false,
274        );
275        let state = decode(snap, &all_tokens())
276            .await
277            .unwrap();
278        assert_eq!(state.kind, SkyComponentKind::Converter);
279    }
280
281    fn wrapper_snapshot() -> ComponentWithState {
282        let mut snap = snapshot(
283            "0xa188eec8f81263234da3622a406892f3d630f98c",
284            "psm_wrapper",
285            USDC,
286            &[USDS, USDC],
287            true,
288        );
289        snap.state.attributes.extend([
290            ("dai_escrow".to_string(), Bytes::from(U256::from(7u8).to_be_bytes_vec())),
291            ("usds_escrow".to_string(), Bytes::from(U256::from(9u8).to_be_bytes_vec())),
292        ]);
293        snap
294    }
295
296    #[tokio::test]
297    async fn decodes_wrapper_with_join_escrows() {
298        let state = decode(wrapper_snapshot(), &all_tokens())
299            .await
300            .unwrap();
301        assert_eq!(state.kind, SkyComponentKind::PsmWrapper);
302    }
303
304    #[rstest]
305    #[case::dai_escrow("dai_escrow")]
306    #[case::usds_escrow("usds_escrow")]
307    #[tokio::test]
308    async fn missing_escrow_attribute_errors_for_wrapper(#[case] name: &str) {
309        let mut snap = wrapper_snapshot();
310        snap.state.attributes.remove(name);
311        let result = decode(snap, &all_tokens()).await;
312        assert!(matches!(result, Err(InvalidSnapshotError::MissingAttribute(_))));
313    }
314
315    #[tokio::test]
316    async fn missing_fee_attribute_errors_for_psm() {
317        let snap = snapshot(PSM_ID, "psm", USDC, &[DAI, USDC], false);
318        let result = decode(snap, &all_tokens()).await;
319        assert!(matches!(result, Err(InvalidSnapshotError::MissingAttribute(_))));
320    }
321
322    #[tokio::test]
323    async fn unknown_component_type_errors() {
324        let snap = snapshot(PSM_ID, "mystery", USDC, &[DAI, USDC], true);
325        let result = decode(snap, &all_tokens()).await;
326        assert!(matches!(result, Err(InvalidSnapshotError::ValueError(_))));
327    }
328
329    #[tokio::test]
330    async fn gem_decimals_above_stable_decimals_errors() {
331        // Same PSM snapshot, but with the tokens' decimals inverted (6-dec
332        // stable, 18-dec gem): the conversion factor would underflow.
333        let tokens = [token(DAI, "DAI", 6), token(USDC, "USDC", 18)]
334            .into_iter()
335            .map(|t| (t.address.clone(), t))
336            .collect();
337        let snap = snapshot(PSM_ID, "psm", USDC, &[DAI, USDC], true);
338        let result = decode(snap, &tokens).await;
339        assert!(matches!(result, Err(InvalidSnapshotError::ValueError(_))));
340    }
341
342    #[tokio::test]
343    async fn missing_gem_attribute_errors() {
344        let mut snap = snapshot(PSM_ID, "psm", USDC, &[DAI, USDC], true);
345        snap.component
346            .static_attributes
347            .remove("gem");
348        let result = decode(snap, &all_tokens()).await;
349        assert!(matches!(result, Err(InvalidSnapshotError::MissingAttribute(_))));
350    }
351
352    #[tokio::test]
353    async fn missing_balance_errors() {
354        let mut snap = snapshot(PSM_ID, "psm", USDC, &[DAI, USDC], true);
355        snap.state
356            .balances
357            .remove(&Bytes::from_str(DAI).unwrap());
358        let result = decode(snap, &all_tokens()).await;
359        assert!(matches!(result, Err(InvalidSnapshotError::ValueError(_))));
360    }
361}