tycho_simulation/evm/protocol/fluid/
decoder.rs1use std::{collections::HashMap, str::FromStr};
2
3use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
4use tycho_common::{models::token::Token, Bytes};
5
6use crate::{
7 evm::{
8 engine_db::{create_engine, SHARED_TYCHO_DB},
9 protocol::fluid::{
10 v1::FluidV1,
11 vm::{self, decode_paused, PAUSED_ATTRIBUTE},
12 },
13 },
14 protocol::{
15 errors::InvalidSnapshotError,
16 models::{DecoderContext, TryFromWithBlock},
17 },
18};
19
20impl TryFromWithBlock<ComponentWithState, BlockHeader> for FluidV1 {
21 type Error = InvalidSnapshotError;
22
23 async fn try_from_with_header(
24 snapshot: ComponentWithState,
25 _block: BlockHeader,
26 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
27 all_tokens: &HashMap<Bytes, Token>,
28 decoder_context: &DecoderContext,
29 ) -> Result<Self, Self::Error> {
30 let pool_address = Bytes::from_str(snapshot.component.id.as_str()).map_err(|e| {
31 InvalidSnapshotError::ValueError(format!(
32 "Expected component id to be pool contract address: {e}"
33 ))
34 })?;
35 let token0_address = snapshot
36 .component
37 .tokens
38 .first()
39 .ok_or_else(|| {
40 InvalidSnapshotError::ValueError("Missing token0 in component".to_string())
41 })?;
42 let token0 = all_tokens
43 .get(token0_address)
44 .ok_or_else(|| {
45 InvalidSnapshotError::ValueError(format!(
46 "Missing token0 in state: {token0_address}"
47 ))
48 })?;
49 let token1_address = snapshot
50 .component
51 .tokens
52 .get(1)
53 .ok_or_else(|| {
54 InvalidSnapshotError::ValueError("Missing token1 in component".to_string())
55 })?;
56 let token1 = all_tokens
57 .get(token1_address)
58 .ok_or_else(|| {
59 InvalidSnapshotError::ValueError(format!(
60 "Missing token1 in state: {token1_address}"
61 ))
62 })?;
63 let resolver_address = snapshot
64 .component
65 .static_attributes
66 .get("reserves_resolver_address")
67 .ok_or_else(|| {
68 InvalidSnapshotError::ValueError(
69 "Missing reserves resolver address in component".to_string(),
70 )
71 })?;
72 let engine = create_engine(
73 SHARED_TYCHO_DB.clone(),
74 decoder_context
75 .vm_traces
76 .unwrap_or_default(),
77 )
78 .expect("Infallible");
79 let paused = snapshot
80 .state
81 .attributes
82 .get(PAUSED_ATTRIBUTE)
83 .is_some_and(decode_paused);
84 let state = vm::decode_from_vm(&pool_address, token0, token1, resolver_address, &engine)?;
85
86 Ok(state.with_paused(paused))
87 }
88}