tycho_simulation/evm/protocol/aero_basic/
decoder.rs1use std::collections::HashMap;
2
3use alloy::primitives::U256;
4use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
5use tycho_common::{models::token::Token, Bytes};
6
7use crate::{
8 evm::protocol::aero_basic::state::{AeroBasicFees, AeroBasicState},
9 protocol::{
10 errors::InvalidSnapshotError,
11 models::{DecoderContext, TryFromWithBlock},
12 },
13};
14
15fn attribute<'a>(
16 attributes: &'a HashMap<String, Bytes>,
17 name: &str,
18) -> Result<&'a Bytes, InvalidSnapshotError> {
19 attributes
20 .get(name)
21 .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_string()))
22}
23
24fn decimals(
25 all_tokens: &HashMap<Bytes, Token>,
26 address: &Bytes,
27) -> Result<u8, InvalidSnapshotError> {
28 let token = all_tokens
29 .get(address)
30 .ok_or_else(|| InvalidSnapshotError::ValueError(format!("Token {address} not found")))?;
31 u8::try_from(token.decimals).map_err(|e| {
32 InvalidSnapshotError::ValueError(format!("Token {address} decimals out of range: {e}"))
33 })
34}
35
36impl TryFromWithBlock<ComponentWithState, BlockHeader> for AeroBasicState {
37 type Error = InvalidSnapshotError;
38
39 async fn try_from_with_header(
42 snapshot: ComponentWithState,
43 _block: BlockHeader,
44 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
45 all_tokens: &HashMap<Bytes, Token>,
46 _decoder_context: &DecoderContext,
47 ) -> Result<Self, Self::Error> {
48 let state = &snapshot.state.attributes;
49 let [token0, token1] = snapshot.component.tokens.as_slice() else {
50 return Err(InvalidSnapshotError::ValueError(format!(
51 "Expected 2 tokens, got {}",
52 snapshot.component.tokens.len()
53 )));
54 };
55 let stable = attribute(&snapshot.component.static_attributes, "is_stable")?.as_ref() == [1];
56 let fees = AeroBasicFees {
57 custom_fee: u32::try_from(attribute(state, "custom_fee")?.clone())?,
58 default_fee: u32::try_from(attribute(state, "default_fee")?.clone())?,
59 fee_module: attribute(state, "fee_module")?.clone(),
60 paused: attribute(state, "paused")?
61 .iter()
62 .any(|byte| *byte != 0),
63 };
64 let reserves = (
65 U256::from_be_slice(attribute(state, "reserve0")?),
66 U256::from_be_slice(attribute(state, "reserve1")?),
67 );
68
69 AeroBasicState::new(
70 reserves,
71 stable,
72 fees,
73 (decimals(all_tokens, token0)?, decimals(all_tokens, token1)?),
74 )
75 .map_err(InvalidSnapshotError::ValueError)
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use std::{collections::HashMap, str::FromStr};
82
83 use num_bigint::BigUint;
84 use rstest::rstest;
85 use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
86 use tycho_common::{
87 models::{
88 protocol::{ProtocolComponent, ProtocolComponentState},
89 token::Token,
90 Chain,
91 },
92 simulation::protocol_sim::ProtocolSim,
93 Bytes,
94 };
95
96 use super::*;
97
98 fn tokens() -> HashMap<Bytes, Token> {
99 [
100 ("0x0000000000000000000000000000000000000001", 18),
101 ("0x0000000000000000000000000000000000000002", 6),
102 ]
103 .into_iter()
104 .map(|(address, decimals)| {
105 let address = Bytes::from_str(address).unwrap();
106 let token = Token::new(&address, "T", decimals, 0, &[Some(10_000)], Chain::Base, 100);
107 (address, token)
108 })
109 .collect()
110 }
111
112 fn snapshot(missing: Option<&str>) -> ComponentWithState {
113 let mut attributes = HashMap::from([
114 ("reserve0".to_string(), Bytes::from(vec![0x0f, 0x42, 0x40])),
115 ("reserve1".to_string(), Bytes::from(vec![0x0f, 0x42, 0x40])),
116 ("custom_fee".to_string(), Bytes::from(vec![0])),
117 ("default_fee".to_string(), Bytes::from(vec![30])),
118 (
119 "fee_module".to_string(),
120 Bytes::from_str("0x7949DE8d67E4F6b8509Bdbb43FF0503aF1247a7A").unwrap(),
121 ),
122 ("paused".to_string(), Bytes::from(vec![0])),
123 ]);
124 if let Some(name) = missing {
125 attributes.remove(name);
126 }
127 ComponentWithState {
128 state: ProtocolComponentState {
129 component_id: "0x00".to_string(),
130 attributes,
131 balances: HashMap::new(),
132 },
133 component: ProtocolComponent {
134 tokens: tokens()
135 .into_keys()
136 .collect::<std::collections::BTreeSet<_>>()
137 .into_iter()
138 .collect(),
139 static_attributes: HashMap::from([("is_stable".to_string(), Bytes::from(vec![0]))]),
140 ..Default::default()
141 },
142 component_tvl: None,
143 entrypoints: Vec::new(),
144 }
145 }
146
147 async fn decode(snapshot: ComponentWithState) -> Result<AeroBasicState, InvalidSnapshotError> {
148 AeroBasicState::try_from_with_header(
149 snapshot,
150 BlockHeader::default(),
151 &HashMap::new(),
152 &tokens(),
153 &DecoderContext::new(),
154 )
155 .await
156 }
157
158 #[tokio::test]
159 async fn decodes_a_snapshot_that_quotes() {
160 let state = decode(snapshot(None)).await.unwrap();
161 let tokens = tokens();
162 let token0 =
163 &tokens[&Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap()];
164 let token1 =
165 &tokens[&Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap()];
166
167 let out = state
168 .get_amount_out(BigUint::from(10_000u64), token0, token1)
169 .unwrap();
170
171 assert_eq!(out.amount, BigUint::from(9_871u64));
173 }
174
175 #[rstest]
176 #[case::reserve0("reserve0")]
177 #[case::custom_fee("custom_fee")]
178 #[case::default_fee("default_fee")]
179 #[case::fee_module("fee_module")]
180 #[case::paused("paused")]
181 #[tokio::test]
182 async fn missing_attribute_is_an_error(#[case] name: &str) {
183 let err = decode(snapshot(Some(name)))
184 .await
185 .unwrap_err();
186
187 assert!(matches!(err, InvalidSnapshotError::MissingAttribute(missing) if missing == name));
188 }
189}