Skip to main content

tycho_simulation/protocol/
models.rs

1//! Pair Properties and ProtocolState
2//!
3//! This module contains the `ProtocolComponent` struct, which represents the
4//! properties of a trading pair. It also contains the `Pair` struct, which
5//! represents a trading pair with its properties and corresponding state.
6//!
7//! Additionally, it contains the `GetAmountOutResult` struct, which
8//! represents the result of getting the amount out of a trading pair.
9//!
10//! The `ProtocolComponent` struct has two fields: `address` and `tokens`.
11//! `address` is the address of the trading pair and `tokens` is a vector
12//! of `ERC20Token` representing the tokens of the trading pair.
13//!
14//! Generally this struct contains immutable properties of the pair. These
15//! are attributes that will never change - not even through governance.
16//!
17//! This is in contrast to `ProtocolState`, which includes ideally only
18//! attributes that can change.
19//!
20//! The `Pair` struct combines the former two: `ProtocolComponent` and
21//! `ProtocolState` into a single struct.
22//!
23//! # Note:
24//! It's worth emphasizing that although the term "pair" used in this
25//! module refers to a trading pair, it does not necessarily imply two
26//! tokens only. Some pairs might have more than two tokens.
27use std::{collections::HashMap, default::Default, future::Future};
28
29use chrono::NaiveDateTime;
30use serde::{Deserialize, Serialize};
31use tokio::sync::watch;
32use tycho_client::feed::{HeaderLike, SynchronizerState};
33use tycho_common::{
34    models::{token::Token, Chain},
35    simulation::protocol_sim::ProtocolSim,
36    Bytes,
37};
38
39use crate::evm::override_stream::OverrideSnapshot;
40
41/// What a quote may assume about the swap's position within its execution block, for protocols
42/// whose pricing depends on that position.
43#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
44pub enum BlockPositionAssumption {
45    /// No assumption: price the swap for the least favourable position it could take, so the
46    /// output is never over-quoted. Loses fills where a better position would in fact have held.
47    #[default]
48    WorstCase,
49    /// Bet the swap lands before any other on the same pool. Better quotes wherever the protocol
50    /// favours that position; a lost bet surfaces as reverts or negative slippage at execution
51    /// time. Enable only if the submission path can realistically win that race.
52    First,
53}
54
55/// Context struct containing attributes for decoders
56///
57/// This struct can be extended to include additional attributes for other decoders in the future
58#[derive(Debug, Clone)]
59#[expect(
60    clippy::partial_pub_fields,
61    reason = "public API; making every field public or private is a breaking change"
62)]
63pub struct DecoderContext {
64    pub adapter_path: Option<String>,
65    pub vm_traces: Option<bool>,
66    /// What quotes may assume about the swap's position within its execution block.
67    ///
68    /// Only consumed by protocols that price the first swap of a block differently (currently
69    /// `aerodrome_slipstreams`). Once the pool has been touched in the execution block, position
70    /// is a known fact and the assumption has no effect.
71    pub block_position: BlockPositionAssumption,
72    /// Live per-block VM state override channel, wired into the pool at construction time.
73    ///
74    /// Set internally by the decoder from its registered override providers; not part of the
75    /// public API. External consumers never set this — overrides are fully handled by the library.
76    pub(crate) live_override: Option<watch::Receiver<OverrideSnapshot>>,
77    /// Chain the decoded components live on.
78    ///
79    /// Stamped by [`TychoStreamDecoder`](crate::evm::decoder::TychoStreamDecoder) at registration,
80    /// so it is `None` only for a context that never went through a decoder. Decoders whose
81    /// behaviour depends on the chain (currently the Uniswap V4 hook handler registry) reject the
82    /// snapshot when it is `None` rather than assume one.
83    pub chain: Option<Chain>,
84}
85
86impl DecoderContext {
87    pub fn new() -> Self {
88        Self {
89            adapter_path: None,
90            vm_traces: None,
91            block_position: BlockPositionAssumption::default(),
92            live_override: None,
93            chain: None,
94        }
95    }
96
97    /// Declares the chain the decoded components live on.
98    ///
99    /// Registering the context with a
100    /// [`TychoStreamDecoder`](crate::evm::decoder::TychoStreamDecoder) overrides whatever is
101    /// set here with the decoder's own chain.
102    pub fn chain(mut self, chain: Chain) -> Self {
103        self.chain = Some(chain);
104        self
105    }
106
107    pub fn block_position_assumption(mut self, assumption: BlockPositionAssumption) -> Self {
108        self.block_position = assumption;
109        self
110    }
111
112    pub fn vm_adapter_path<S: Into<String>>(mut self, path: S) -> Self {
113        self.adapter_path = Some(path.into());
114        self
115    }
116
117    pub fn vm_traces(mut self, trace: bool) -> Self {
118        self.vm_traces = Some(trace);
119        self
120    }
121}
122
123impl Default for DecoderContext {
124    fn default() -> Self {
125        Self::new()
126    }
127}
128
129/// ProtocolComponent struct represents the properties of a trading pair
130///
131/// # Fields
132///
133/// * `address`: String, the address of the trading pair
134/// * `tokens`: `Vec<ERC20Token>`, the tokens of the trading pair
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136pub struct ProtocolComponent {
137    #[deprecated(since = "0.73.0", note = "Use `id` instead")]
138    pub address: Bytes,
139    pub id: Bytes,
140    pub tokens: Vec<Token>,
141    pub protocol_system: String,
142    pub protocol_type_name: String,
143    pub chain: Chain,
144    pub contract_ids: Vec<Bytes>,
145    pub static_attributes: HashMap<String, Bytes>,
146    pub creation_tx: Bytes,
147    pub created_at: NaiveDateTime,
148}
149
150impl ProtocolComponent {
151    #[expect(
152        deprecated,
153        reason = "fills the deprecated address field so consumers still reading it get a value"
154    )]
155    #[expect(
156        clippy::too_many_arguments,
157        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
158    )]
159    pub fn new(
160        id: Bytes,
161        protocol_system: String,
162        protocol_type_name: String,
163        chain: Chain,
164        tokens: Vec<Token>,
165        contract_ids: Vec<Bytes>,
166        static_attributes: HashMap<String, Bytes>,
167        creation_tx: Bytes,
168        created_at: NaiveDateTime,
169    ) -> Self {
170        ProtocolComponent {
171            address: Default::default(),
172            id,
173            tokens,
174            protocol_system,
175            protocol_type_name,
176            chain,
177            contract_ids,
178            static_attributes,
179            creation_tx,
180            created_at,
181        }
182    }
183
184    pub fn from_with_tokens(
185        core_model: tycho_common::models::protocol::ProtocolComponent,
186        tokens: Vec<Token>,
187    ) -> Self {
188        let id = Bytes::from(core_model.id.as_str());
189        ProtocolComponent::new(
190            id,
191            core_model.protocol_system,
192            core_model.protocol_type_name,
193            core_model.chain,
194            tokens,
195            core_model.contract_addresses,
196            core_model.static_attributes,
197            core_model.creation_tx,
198            core_model.created_at,
199        )
200    }
201}
202
203impl From<ProtocolComponent> for tycho_common::models::protocol::ProtocolComponent {
204    fn from(component: ProtocolComponent) -> Self {
205        tycho_common::models::protocol::ProtocolComponent {
206            id: hex::encode(component.id),
207            protocol_system: component.protocol_system,
208            protocol_type_name: component.protocol_type_name,
209            chain: component.chain,
210            tokens: component
211                .tokens
212                .into_iter()
213                .map(|t| t.address)
214                .collect(),
215            static_attributes: component.static_attributes,
216            change: Default::default(),
217            creation_tx: component.creation_tx,
218            created_at: component.created_at,
219            contract_addresses: component.contract_ids,
220        }
221    }
222}
223
224pub trait TryFromWithBlock<T, H>
225where
226    H: HeaderLike,
227{
228    type Error;
229
230    fn try_from_with_header(
231        snapshot: T,
232        block: H,
233        account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
234        all_tokens: &HashMap<Bytes, Token>,
235        decoder_context: &DecoderContext,
236    ) -> impl Future<Output = Result<Self, Self::Error>> + Send + Sync
237    where
238        Self: Sized;
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct Update {
243    pub block_number: u64,
244    /// True when this update is for a partial (pre-confirmation) block, false for full blocks.
245    #[serde(default)]
246    pub is_partial: bool,
247    /// Synchronization state per protocol
248    pub sync_states: HashMap<String, SynchronizerState>,
249    /// The new and updated states of this block.
250    /// VM-backed states that can't be serialized are silently skipped during
251    /// serialization and will be absent after a roundtrip.
252    #[serde(with = "crate::serde_helpers::protocol_states")]
253    pub states: HashMap<String, Box<dyn ProtocolSim>>,
254    /// The new pairs that were added in this block
255    pub new_pairs: HashMap<String, ProtocolComponent>,
256    /// The pairs that were removed in this block
257    pub removed_pairs: HashMap<String, ProtocolComponent>,
258}
259
260impl Update {
261    pub fn new(
262        block_number: u64,
263        states: HashMap<String, Box<dyn ProtocolSim>>,
264        new_pairs: HashMap<String, ProtocolComponent>,
265    ) -> Self {
266        Update {
267            block_number,
268            is_partial: false,
269            sync_states: HashMap::new(),
270            states,
271            new_pairs,
272            removed_pairs: HashMap::new(),
273        }
274    }
275
276    pub fn set_is_partial(mut self, is_partial: bool) -> Self {
277        self.is_partial = is_partial;
278        self
279    }
280
281    pub fn set_removed_pairs(mut self, pairs: HashMap<String, ProtocolComponent>) -> Self {
282        self.removed_pairs = pairs;
283        self
284    }
285
286    pub fn set_sync_states(mut self, sync_states: HashMap<String, SynchronizerState>) -> Self {
287        self.sync_states = sync_states;
288        self
289    }
290
291    pub fn merge(mut self, other: Update) -> Self {
292        self.states.extend(other.states);
293        self.new_pairs.extend(other.new_pairs);
294        self.removed_pairs
295            .extend(other.removed_pairs);
296        self
297    }
298}