tycho_simulation/evm/protocol/curve/
decoder.rs1use std::{collections::HashMap, str::FromStr};
2
3use alloy::primitives::Address as AlloyAddress;
4use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
5use tycho_common::{models::token::Token, Bytes};
6
7use crate::{
8 evm::{
9 engine_db::{create_engine, SHARED_TYCHO_DB},
10 protocol::{
11 curve::{adapter::build_pool, policy::CurvePolicy, state::CurveState, variant, vm},
12 vm::utils::load_stateless_contracts,
13 },
14 },
15 protocol::{
16 errors::InvalidSnapshotError,
17 models::{DecoderContext, TryFromWithBlock},
18 },
19};
20
21const ETH_SENTINEL: [u8; 20] = [0xEE; 20];
25
26impl TryFromWithBlock<ComponentWithState, BlockHeader> for CurveState {
27 type Error = InvalidSnapshotError;
28
29 async fn try_from_with_header(
36 snapshot: ComponentWithState,
37 _block: BlockHeader,
38 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
39 all_tokens: &HashMap<Bytes, Token>,
40 decoder_context: &DecoderContext,
41 ) -> Result<Self, Self::Error> {
42 let pool_address = Bytes::from_str(snapshot.component.id.as_str()).map_err(|e| {
43 InvalidSnapshotError::ValueError(format!(
44 "Expected curve component id to be the pool address: {e}"
45 ))
46 })?;
47
48 let coins = parse_coins(&snapshot.component.static_attributes)?;
49 if coins.len() < 2 {
50 return Err(InvalidSnapshotError::ValueError(format!(
51 "Curve pool {pool_address} has fewer than 2 coins"
52 )));
53 }
54 let decimals = coins
55 .iter()
56 .map(|coin| coin_decimals(coin, all_tokens, &pool_address))
57 .collect::<Result<Vec<u8>, _>>()?;
58
59 let engine = create_engine(
60 SHARED_TYCHO_DB.clone(),
61 decoder_context
62 .vm_traces
63 .unwrap_or_default(),
64 )
65 .expect("Infallible");
66
67 load_stateless_contracts(&engine, &snapshot.state.attributes).await?;
70
71 let pool_alloy = AlloyAddress::from_slice(pool_address.as_ref());
72 vm::load_math_contract(&engine, &pool_alloy).await?;
76
77 let resolved = variant::resolve_variant(
78 &snapshot.component.static_attributes,
79 &pool_alloy,
80 coins.len(),
81 &engine,
82 )?;
83 let raw = vm::read_raw_pool_state(
84 &engine,
85 &pool_alloy,
86 resolved,
87 &decimals,
88 &Default::default(),
89 )?;
90 let pool = build_pool(&raw).map_err(|e| {
91 InvalidSnapshotError::ValueError(format!("curve build_pool failed: {e}"))
92 })?;
93 let policy = CurvePolicy::from_attributes(&snapshot.state.attributes)
94 .map_err(|e| InvalidSnapshotError::ValueError(e.to_string()))?;
95 Ok(CurveState::new(pool_address, coins, decimals, resolved, pool, raw.admin_fee)
96 .with_policy(policy))
97 }
98}
99
100fn parse_coins(
103 static_attributes: &HashMap<String, Bytes>,
104) -> Result<Vec<Bytes>, InvalidSnapshotError> {
105 let raw = static_attributes
106 .get("coins")
107 .ok_or_else(|| {
108 InvalidSnapshotError::ValueError("Missing `coins` static attribute".to_string())
109 })?;
110 let text = std::str::from_utf8(raw.as_ref()).map_err(|e| {
111 InvalidSnapshotError::ValueError(format!("`coins` attribute is not valid UTF-8: {e}"))
112 })?;
113 let addresses: Vec<String> = serde_json::from_str(text).map_err(|e| {
114 InvalidSnapshotError::ValueError(format!("Failed to parse `coins` attribute: {e}"))
115 })?;
116 addresses
117 .iter()
118 .map(|address| {
119 Bytes::from_str(address)
120 .map(normalize_eth)
121 .map_err(|e| {
122 InvalidSnapshotError::ValueError(format!("Invalid coin address {address}: {e}"))
123 })
124 })
125 .collect()
126}
127
128fn normalize_eth(address: Bytes) -> Bytes {
130 if address.as_ref() == ETH_SENTINEL {
131 Bytes::from(vec![0u8; 20])
132 } else {
133 address
134 }
135}
136
137fn coin_decimals(
140 coin: &Bytes,
141 all_tokens: &HashMap<Bytes, Token>,
142 pool_address: &Bytes,
143) -> Result<u8, InvalidSnapshotError> {
144 if let Some(token) = all_tokens.get(coin) {
145 return u8::try_from(token.decimals).map_err(|e| {
146 InvalidSnapshotError::ValueError(format!("Token {coin} decimals out of range: {e}"))
147 });
148 }
149 if coin.iter().all(|b| *b == 0) {
150 return Ok(18);
151 }
152 Err(InvalidSnapshotError::ValueError(format!(
153 "Missing token {coin} in state for curve pool {pool_address}"
154 )))
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 fn attrs_with_coins(json: &str) -> HashMap<String, Bytes> {
162 let mut m = HashMap::new();
163 m.insert("coins".to_string(), Bytes::from(json.as_bytes().to_vec()));
164 m
165 }
166
167 #[test]
168 fn parse_coins_preserves_on_chain_order_and_normalizes_eth() {
169 let json = r#"["0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]"#;
171 let coins = parse_coins(&attrs_with_coins(json)).unwrap();
172 assert_eq!(coins.len(), 3);
173 assert_eq!(
174 coins[0],
175 Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap()
176 );
177 assert_eq!(
178 coins[1],
179 Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap()
180 );
181 assert_eq!(coins[2], Bytes::from(vec![0u8; 20]), "ETH sentinel -> zero address");
182 }
183
184 #[test]
185 fn parse_coins_missing_attribute_errors() {
186 let err = parse_coins(&HashMap::new()).unwrap_err();
187 assert!(matches!(err, InvalidSnapshotError::ValueError(_)));
188 }
189}