Skip to main content

tycho_simulation/evm/protocol/vm/
decoder.rs

1use std::{
2    collections::{HashMap, HashSet},
3    str::FromStr,
4};
5
6use alloy::primitives::{Address, U256};
7use revm::state::Bytecode;
8use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
9use tycho_common::{models::token::Token, simulation::errors::SimulationError, Bytes};
10
11use super::{state::EVMPoolState, state_builder::EVMPoolStateBuilder};
12use crate::{
13    evm::{
14        engine_db::{tycho_db::PreCachedDB, SHARED_TYCHO_DB},
15        protocol::vm::{constants::get_adapter_file, utils::json_deserialize_address_list},
16        simulation::BlockEnvOverrides,
17    },
18    protocol::{
19        errors::InvalidSnapshotError,
20        models::{DecoderContext, TryFromWithBlock},
21    },
22};
23
24impl TryFromWithBlock<ComponentWithState, BlockHeader> for EVMPoolState<PreCachedDB> {
25    type Error = InvalidSnapshotError;
26
27    /// Decodes a `ComponentWithState`, block `BlockHeader` and HashMap of all available tokens into
28    /// an `EVMPoolState`.
29    ///
30    /// Errors with a `InvalidSnapshotError`.
31    #[allow(deprecated)]
32    async fn try_from_with_header(
33        snapshot: ComponentWithState,
34        _block: BlockHeader,
35        account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
36        all_tokens: &HashMap<Bytes, Token>,
37        decoder_context: &DecoderContext,
38    ) -> Result<Self, Self::Error> {
39        let id = snapshot.component.id.clone();
40        let tokens = snapshot.component.tokens.clone();
41
42        // Decode involved contracts
43        let mut stateless_contracts = HashMap::new();
44        let mut index = 0;
45
46        loop {
47            let address_key = format!("stateless_contract_addr_{index}");
48            if let Some(encoded_address_bytes) = snapshot
49                .state
50                .attributes
51                .get(&address_key)
52            {
53                let encoded_address = hex::encode(encoded_address_bytes);
54                // Stateless contracts address are UTF-8 encoded
55                let address_hex = encoded_address
56                    .strip_prefix("0x")
57                    .unwrap_or(&encoded_address);
58
59                let decoded = match hex::decode(address_hex) {
60                    Ok(decoded_bytes) => match String::from_utf8(decoded_bytes) {
61                        Ok(decoded_string) => decoded_string,
62                        Err(_) => continue,
63                    },
64                    Err(_) => continue,
65                };
66
67                let code_key = format!("stateless_contract_code_{index}");
68                let code = snapshot
69                    .state
70                    .attributes
71                    .get(&code_key)
72                    .map(|value| value.to_vec());
73
74                stateless_contracts.insert(decoded, code);
75                index += 1;
76            } else {
77                break;
78            }
79        }
80        let involved_contracts = snapshot
81            .component
82            .contract_addresses
83            .iter()
84            .map(|bytes: &Bytes| Address::from_slice(bytes.as_ref()))
85            .collect::<HashSet<Address>>();
86
87        let potential_rebase_tokens: HashSet<Address> = if let Some(bytes) = snapshot
88            .component
89            .static_attributes
90            .get("rebase_tokens")
91        {
92            if let Ok(vecs) = json_deserialize_address_list(bytes) {
93                vecs.into_iter()
94                    .map(|addr| Address::from_slice(&addr))
95                    .collect()
96            } else {
97                HashSet::new()
98            }
99        } else {
100            HashSet::new()
101        };
102
103        // Tokens whose protocol does not emit token contract storage. Simulation handles their
104        // transfers entirely in the proxy's local bookkeeping (custom approval + recipient balance)
105        // so they never delegate to an implementation another protocol may have left in the shared
106        // DB.
107        let self_contained_tokens: HashSet<Address> = if let Some(bytes) = snapshot
108            .component
109            .static_attributes
110            .get("self_contained_tokens")
111        {
112            if let Ok(vecs) = json_deserialize_address_list(bytes) {
113                vecs.into_iter()
114                    .map(|addr| Address::from_slice(&addr))
115                    .collect()
116            } else {
117                HashSet::new()
118            }
119        } else {
120            HashSet::new()
121        };
122
123        // Decode balances
124        let balance_owner = snapshot
125            .state
126            .attributes
127            .get("balance_owner")
128            .map(|owner| Address::from_slice(owner.as_ref()));
129        let component_balances = snapshot
130            .state
131            .balances
132            .iter()
133            .map(|(k, v)| (Address::from_slice(k), U256::from_be_slice(v)))
134            .collect::<HashMap<_, _>>();
135        let account_balances = account_balances
136            .iter()
137            .filter(|(k, _)| involved_contracts.contains(&Address::from_slice(k)))
138            .map(|(k, v)| {
139                let addr = Address::from_slice(k);
140                let balances = v
141                    .iter()
142                    .map(|(k, v)| (Address::from_slice(k), U256::from_be_slice(v)))
143                    .collect();
144                (addr, balances)
145            })
146            .collect::<HashMap<_, _>>();
147
148        let manual_updates = snapshot
149            .component
150            .static_attributes
151            .contains_key("manual_updates");
152
153        let protocol_name = snapshot
154            .component
155            .protocol_system
156            .strip_prefix("vm:")
157            .unwrap_or({
158                snapshot
159                    .component
160                    .protocol_system
161                    .as_str()
162            });
163        let adapter_bytecode;
164        if let Some(adapter_bytecode_path) = &decoder_context.adapter_path {
165            let bytecode_bytes = std::fs::read(adapter_bytecode_path).map_err(|e| {
166                SimulationError::FatalError(format!(
167                    "Failed to read adapter bytecode from {adapter_bytecode_path}: {e}"
168                ))
169            })?;
170            adapter_bytecode = Bytecode::new_raw(bytecode_bytes.into());
171        } else {
172            adapter_bytecode = Bytecode::new_raw(get_adapter_file(protocol_name)?.into());
173        }
174        let adapter_contract_address = Address::from_str(&format!(
175            "{hex_protocol_name:0>40}",
176            hex_protocol_name = hex::encode(protocol_name)
177        ))
178        .map_err(|_| {
179            InvalidSnapshotError::ValueError(
180                "Error converting protocol name to address".to_string(),
181            )
182        })?;
183        let mut vm_traces = false;
184        if let Some(trace) = &decoder_context.vm_traces {
185            vm_traces = *trace;
186        }
187        // A protocol may override only one block env field. In that case the VM call will use the
188        // overridden field together with the current block's other field, so block.number and
189        // block.timestamp may not correspond to the same real chain block.
190        let block_number = snapshot
191            .state
192            .attributes
193            .get("override_block_number")
194            .map(|block_number| {
195                <[u8; 8]>::try_from(block_number.as_ref())
196                    .map(u64::from_be_bytes)
197                    .map_err(|_| {
198                        InvalidSnapshotError::ValueError(
199                            "override_block_number attribute must be an 8-byte big-endian u64"
200                                .to_string(),
201                        )
202                    })
203            })
204            .transpose()?;
205        let block_timestamp = snapshot
206            .state
207            .attributes
208            .get("override_block_timestamp")
209            .map(|block_timestamp| {
210                <[u8; 8]>::try_from(block_timestamp.as_ref())
211                    .map(u64::from_be_bytes)
212                    .map_err(|_| {
213                        InvalidSnapshotError::ValueError(
214                            "override_block_timestamp attribute must be an 8-byte big-endian u64"
215                                .to_string(),
216                        )
217                    })
218            })
219            .transpose()?;
220        let block_overrides = if block_number.is_some() || block_timestamp.is_some() {
221            Some(BlockEnvOverrides { number: block_number, timestamp: block_timestamp })
222        } else {
223            None
224        };
225        let mut pool_state_builder =
226            EVMPoolStateBuilder::new(id.clone(), tokens.clone(), adapter_contract_address)
227                .balances(component_balances)
228                .disable_overwrite_tokens(potential_rebase_tokens)
229                .self_contained_tokens(self_contained_tokens)
230                .account_balances(account_balances)
231                .adapter_contract_bytecode(adapter_bytecode)
232                .involved_contracts(involved_contracts)
233                .stateless_contracts(stateless_contracts)
234                .manual_updates(manual_updates)
235                .trace(vm_traces)
236                .block_overrides(block_overrides);
237
238        if let Some(balance_owner) = balance_owner {
239            pool_state_builder = pool_state_builder.balance_owner(balance_owner)
240        };
241
242        let mut pool_state = pool_state_builder
243            .build(SHARED_TYCHO_DB.clone())
244            .await
245            .map_err(InvalidSnapshotError::VMError)?;
246
247        pool_state.set_spot_prices(all_tokens)?;
248
249        Ok(pool_state)
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use std::{collections::HashSet, fs, path::Path};
256
257    use chrono::DateTime;
258    use revm::{primitives::KECCAK_EMPTY, state::AccountInfo};
259    use serde_json::Value;
260    use tycho_common::models::{
261        protocol::{ProtocolComponent, ProtocolComponentState},
262        Chain, ChangeType,
263    };
264
265    use super::*;
266    use crate::evm::{
267        engine_db::{create_engine, engine_db_interface::EngineDatabaseInterface},
268        protocol::vm::constants::{BALANCER_V2, CURVE},
269        tycho_models::AccountUpdate,
270    };
271
272    #[test]
273    fn test_to_adapter_file_name() {
274        assert_eq!(get_adapter_file("balancer_v2").unwrap(), BALANCER_V2);
275        assert_eq!(get_adapter_file("curve").unwrap(), CURVE);
276    }
277
278    fn vm_component() -> ProtocolComponent {
279        let creation_time = DateTime::from_timestamp(1622526000, 0)
280            .unwrap()
281            .naive_utc(); //Sample timestamp
282
283        let mut static_attributes: HashMap<String, Bytes> = HashMap::new();
284        static_attributes.insert("manual_updates".to_string(), Bytes::from_str("0x01").unwrap());
285
286        let dai_addr = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
287        let bal_addr = Bytes::from_str("0xba100000625a3754423978a60c9317c58a424e3d").unwrap();
288        let tokens = vec![dai_addr, bal_addr];
289
290        ProtocolComponent {
291            id: "0x4626d81b3a1711beb79f4cecff2413886d461677000200000000000000000011".to_string(),
292            protocol_system: "vm:balancer_v2".to_string(),
293            protocol_type_name: "balancer_v2_pool".to_string(),
294            chain: Chain::Ethereum,
295            tokens,
296            contract_addresses: vec![
297                Bytes::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap()
298            ],
299            static_attributes,
300            change: ChangeType::Creation,
301            creation_tx: Bytes::from_str("0x0000").unwrap(),
302            created_at: creation_time,
303        }
304    }
305
306    fn load_balancer_account_data() -> Vec<AccountUpdate> {
307        let project_root = env!("CARGO_MANIFEST_DIR");
308        let asset_path =
309            Path::new(project_root).join("tests/assets/decoder/balancer_v2_snapshot.json");
310        let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
311        let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
312
313        let accounts: Vec<AccountUpdate> = serde_json::from_value(data["accounts"].clone())
314            .expect("Expected accounts to match AccountUpdate structure");
315        accounts
316    }
317
318    #[tokio::test]
319    async fn test_try_from_with_header() {
320        let attributes: HashMap<String, Bytes> = vec![
321            (
322                "balance_owner".to_string(),
323                Bytes::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap(),
324            ),
325            ("override_block_number".to_string(), Bytes::from(123_u64.to_be_bytes().to_vec())),
326            ("override_block_timestamp".to_string(), Bytes::from(456_u64.to_be_bytes().to_vec())),
327            ("reserve1".to_string(), Bytes::from(200_u64.to_le_bytes().to_vec())),
328        ]
329        .into_iter()
330        .collect();
331        let tokens = [
332            Token::new(
333                &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
334                "DAI",
335                18,
336                0,
337                &[Some(10_000)],
338                tycho_common::models::Chain::Ethereum,
339                100,
340            ),
341            Token::new(
342                &Bytes::from_str("0xba100000625a3754423978a60c9317c58a424e3d").unwrap(),
343                "BAL",
344                18,
345                0,
346                &[Some(10_000)],
347                tycho_common::models::Chain::Ethereum,
348                100,
349            ),
350        ]
351        .into_iter()
352        .map(|t| (t.address.clone(), t))
353        .collect::<HashMap<_, _>>();
354        let snapshot = ComponentWithState {
355            state: ProtocolComponentState {
356                component_id: "0x4626d81b3a1711beb79f4cecff2413886d461677000200000000000000000011"
357                    .to_owned(),
358                attributes,
359                balances: HashMap::new(),
360            },
361            component: vm_component(),
362            component_tvl: None,
363            entrypoints: Vec::new(),
364        };
365        // Initialize engine with balancer storage
366        let block = BlockHeader::default();
367        let accounts = load_balancer_account_data();
368        let db = SHARED_TYCHO_DB.clone();
369        let engine = create_engine(db.clone(), false).unwrap();
370        for account in accounts.clone() {
371            engine
372                .state
373                .init_account(
374                    account.address,
375                    AccountInfo {
376                        balance: account.balance.unwrap_or_default(),
377                        nonce: 0u64,
378                        code_hash: KECCAK_EMPTY,
379                        code: account
380                            .code
381                            .clone()
382                            .map(|arg0: Vec<u8>| Bytecode::new_raw(arg0.into())),
383                    },
384                    None,
385                    false,
386                )
387                .expect("Failed to init account");
388        }
389        db.update(accounts, Some(block.clone()))
390            .unwrap();
391        let account_balances = HashMap::from([(
392            Bytes::from("0xBA12222222228d8Ba445958a75a0704d566BF2C8"),
393            HashMap::from([
394                (
395                    Bytes::from("0x6b175474e89094c44da98b954eedeac495271d0f"),
396                    Bytes::from(100_u64.to_le_bytes().to_vec()),
397                ),
398                (
399                    Bytes::from("0xba100000625a3754423978a60c9317c58a424e3d"),
400                    Bytes::from(100_u64.to_le_bytes().to_vec()),
401                ),
402            ]),
403        )]);
404
405        let decoder_context = DecoderContext::new();
406        let res = EVMPoolState::try_from_with_header(
407            snapshot,
408            block,
409            &account_balances,
410            &tokens,
411            &decoder_context,
412        )
413        .await
414        .unwrap();
415
416        let res_pool = res;
417
418        assert_eq!(
419            res_pool.get_balance_owner(),
420            Some(Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap())
421        );
422        let mut exp_involved_contracts = HashSet::new();
423        exp_involved_contracts
424            .insert(Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap());
425        assert_eq!(res_pool.get_involved_contracts(), exp_involved_contracts);
426        assert!(res_pool.get_manual_updates());
427        assert_eq!(
428            res_pool.get_block_overrides(),
429            Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) })
430        );
431    }
432}