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::uniswap_v2::state::{decode_reserve, 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 reserve = |name: &str| {
27 let value = snapshot
28 .state
29 .attributes
30 .get(name)
31 .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_string()))?;
32 decode_reserve(name, value).map_err(InvalidSnapshotError::ValueError)
33 };
34 Ok(Self::new(reserve("reserve0")?, reserve("reserve1")?))
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use std::{collections::HashMap, str::FromStr};
41
42 use alloy::primitives::aliases::U112;
43 use rstest::rstest;
44 use tycho_client::feed::synchronizer::ComponentWithState;
45 use tycho_common::{models::protocol::ProtocolComponentState, Bytes};
46
47 use super::super::state::UniswapV2State;
48 use crate::{
49 evm::protocol::test_utils::try_decode_snapshot_with_defaults,
50 protocol::errors::InvalidSnapshotError,
51 };
52
53 #[tokio::test]
54 #[rstest]
55 #[case::missing_reserve0("reserve0")]
56 #[case::missing_reserve1("reserve1")]
57 async fn test_usv2_try_from_missing_attribute(#[case] missing_attribute: &str) {
58 let mut attributes = HashMap::from([
59 ("reserve0".to_string(), Bytes::from(vec![0; 32])),
60 ("reserve1".to_string(), Bytes::from(vec![0; 32])),
61 ]);
62 attributes.remove(missing_attribute);
63
64 let snapshot = ComponentWithState {
65 state: ProtocolComponentState {
66 component_id: "State1".to_owned(),
67 attributes,
68 balances: HashMap::new(),
69 },
70 component: Default::default(),
71 component_tvl: None,
72 entrypoints: Vec::new(),
73 };
74
75 let result = try_decode_snapshot_with_defaults::<UniswapV2State>(snapshot).await;
76
77 assert!(result.is_err());
78 assert!(matches!(
79 result.unwrap_err(),
80 InvalidSnapshotError::MissingAttribute(ref x) if x == missing_attribute
81 ));
82 }
83
84 fn snapshot_with_reserve0(reserve0: Vec<u8>) -> ComponentWithState {
85 ComponentWithState {
86 state: ProtocolComponentState {
87 component_id: "State1".to_owned(),
88 attributes: HashMap::from([
89 ("reserve0".to_string(), Bytes::from(reserve0)),
90 ("reserve1".to_string(), Bytes::from(vec![0])),
91 ]),
92 balances: HashMap::new(),
93 },
94 component: Default::default(),
95 component_tvl: None,
96 entrypoints: Vec::new(),
97 }
98 }
99
100 #[rstest]
101 #[case::zero(vec![0x00], "0")]
102 #[case::zero_word(vec![0x00; 32], "0")]
103 #[case::uint112_max_with_sign_byte(
105 [vec![0x00], vec![0xff; 14]].concat(),
106 "5192296858534827628530496329220095"
107 )]
108 #[case::zero_padded_word([vec![0x00; 29], vec![0x01, 0x00, 0x00]].concat(), "65536")]
109 #[tokio::test]
110 async fn test_usv2_try_from_reads_reserve(#[case] reserve0: Vec<u8>, #[case] expected: &str) {
111 let state =
112 try_decode_snapshot_with_defaults::<UniswapV2State>(snapshot_with_reserve0(reserve0))
113 .await
114 .unwrap();
115
116 assert_eq!(state.reserve0, U112::from_str(expected).unwrap());
117 }
118
119 #[rstest]
120 #[case::past_uint112([vec![0x01], vec![0x00; 14]].concat())]
122 #[case::past_uint256([vec![0x01], vec![0x00; 32]].concat())]
124 #[tokio::test]
125 async fn test_usv2_try_from_refuses_reserve_the_pair_cannot_store(#[case] reserve0: Vec<u8>) {
126 let snapshot = snapshot_with_reserve0(reserve0);
127
128 let result = try_decode_snapshot_with_defaults::<UniswapV2State>(snapshot).await;
129
130 assert!(matches!(result, Err(InvalidSnapshotError::ValueError(_))));
131 }
132}