tycho_simulation/evm/protocol/uniswap_v2/
decoder.rs1use std::collections::HashMap;
2
3use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
4use tycho_common::{models::token::Token, Bytes};
5
6use crate::{
7 evm::protocol::{cpmm::protocol::cpmm_try_from_with_header, uniswap_v2::state::UniswapV2State},
8 protocol::{
9 errors::InvalidSnapshotError,
10 models::{DecoderContext, TryFromWithBlock},
11 },
12};
13
14impl TryFromWithBlock<ComponentWithState, BlockHeader> for UniswapV2State {
15 type Error = InvalidSnapshotError;
16
17 async fn try_from_with_header(
20 snapshot: ComponentWithState,
21 _block: BlockHeader,
22 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
23 _all_tokens: &HashMap<Bytes, Token>,
24 _decoder_context: &DecoderContext,
25 ) -> Result<Self, Self::Error> {
26 let (reserve0, reserve1) = cpmm_try_from_with_header(snapshot)?;
27 Ok(Self::new(reserve0, reserve1))
28 }
29}
30
31#[cfg(test)]
32mod tests {
33 use std::collections::HashMap;
34
35 use alloy::primitives::U256;
36 use rstest::rstest;
37 use tycho_client::feed::synchronizer::ComponentWithState;
38 use tycho_common::{dto::ResponseProtocolState, Bytes};
39
40 use super::super::state::UniswapV2State;
41 use crate::{
42 evm::protocol::test_utils::try_decode_snapshot_with_defaults,
43 protocol::errors::InvalidSnapshotError,
44 };
45
46 #[tokio::test]
47 async fn test_usv2_try_from() {
48 let snapshot = ComponentWithState {
49 state: ResponseProtocolState {
50 component_id: "State1".to_owned(),
51 attributes: HashMap::from([
52 ("reserve0".to_string(), Bytes::from(vec![0; 32])),
53 ("reserve1".to_string(), Bytes::from(vec![0; 32])),
54 ]),
55 balances: HashMap::new(),
56 },
57 component: Default::default(),
58 component_tvl: None,
59 entrypoints: Vec::new(),
60 };
61
62 let result = try_decode_snapshot_with_defaults::<UniswapV2State>(snapshot).await;
63
64 assert!(result.is_ok());
65 assert_eq!(result.unwrap(), UniswapV2State::new(U256::from(0u64), U256::from(0u64)));
66 }
67
68 #[tokio::test]
69 #[rstest]
70 #[case::missing_reserve0("reserve0")]
71 #[case::missing_reserve1("reserve1")]
72 async fn test_usv2_try_from_missing_attribute(#[case] missing_attribute: &str) {
73 let mut attributes = HashMap::from([
74 ("reserve0".to_string(), Bytes::from(vec![0; 32])),
75 ("reserve1".to_string(), Bytes::from(vec![0; 32])),
76 ]);
77 attributes.remove(missing_attribute);
78
79 let snapshot = ComponentWithState {
80 state: ResponseProtocolState {
81 component_id: "State1".to_owned(),
82 attributes,
83 balances: HashMap::new(),
84 },
85 component: Default::default(),
86 component_tvl: None,
87 entrypoints: Vec::new(),
88 };
89
90 let result = try_decode_snapshot_with_defaults::<UniswapV2State>(snapshot).await;
91
92 assert!(result.is_err());
93 assert!(matches!(
94 result.unwrap_err(),
95 InvalidSnapshotError::MissingAttribute(ref x) if x == missing_attribute
96 ));
97 }
98}