Skip to main content

tycho_common/models/
protocol.rs

1use std::{
2    collections::{HashMap, HashSet},
3    sync::Arc,
4};
5
6use chrono::NaiveDateTime;
7use deepsize::{Context, DeepSizeOf};
8use num_bigint::BigUint;
9use serde::{Deserialize, Serialize};
10
11use crate::{
12    dto,
13    models::{
14        token::Token, Address, AttrStoreKey, Balance, Chain, ChangeType, ComponentId, MergeError,
15        StoreVal, TxHash,
16    },
17    Bytes,
18};
19
20/// `ProtocolComponent` provides detailed descriptions of a component of a protocol,
21/// for example, swap pools that enables the exchange of two tokens.
22///
23/// A `ProtocolComponent` can be associated with an `Account`, and it has an identifier (`id`) that
24/// can be either the on-chain address or a custom one. It belongs to a specific `ProtocolSystem`
25/// and has a `ProtocolTypeID` that associates it with a `ProtocolType` that describes its behaviour
26/// e.g., swap, lend, bridge. The component is associated with a specific `Chain` and holds
27/// information about tradable tokens, related contract IDs, and static attributes.
28///
29/// Every values of a `ProtocolComponent` must be static, they can't ever be changed after creation.
30/// The dynamic values associated to a component must be given using `ProtocolComponentState`.
31#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
32pub struct ProtocolComponent<Token: Into<Address> + Clone = Address> {
33    pub id: ComponentId,
34    pub protocol_system: String,
35    pub protocol_type_name: String,
36    pub chain: Chain,
37    pub tokens: Vec<Token>,
38    pub contract_addresses: Vec<Address>,
39    pub static_attributes: HashMap<AttrStoreKey, StoreVal>,
40    pub change: ChangeType,
41    pub creation_tx: TxHash,
42    pub created_at: NaiveDateTime,
43}
44
45impl<T> ProtocolComponent<T>
46where
47    T: Into<Address> + Clone,
48{
49    #[expect(
50        clippy::too_many_arguments,
51        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
52    )]
53    pub fn new(
54        id: &str,
55        protocol_system: &str,
56        protocol_type_name: &str,
57        chain: Chain,
58        tokens: Vec<T>,
59        contract_addresses: Vec<Address>,
60        static_attributes: HashMap<AttrStoreKey, StoreVal>,
61        change: ChangeType,
62        creation_tx: TxHash,
63        created_at: NaiveDateTime,
64    ) -> Self {
65        Self {
66            id: id.to_string(),
67            protocol_system: protocol_system.to_string(),
68            protocol_type_name: protocol_type_name.to_string(),
69            chain,
70            tokens,
71            contract_addresses,
72            static_attributes,
73            change,
74            creation_tx,
75            created_at,
76        }
77    }
78}
79
80impl ProtocolComponent<Arc<Token>> {
81    pub fn get_token(&self, address: &Address) -> Option<Arc<Token>> {
82        self.tokens
83            .iter()
84            .find(|t| &t.address == address)
85            .map(Arc::clone)
86    }
87}
88
89impl DeepSizeOf for ProtocolComponent {
90    fn deep_size_of_children(&self, context: &mut Context) -> usize {
91        self.id.deep_size_of_children(context) +
92            self.protocol_system
93                .deep_size_of_children(context) +
94            self.protocol_type_name
95                .deep_size_of_children(context) +
96            self.chain
97                .deep_size_of_children(context) +
98            self.tokens
99                .deep_size_of_children(context) +
100            self.contract_addresses
101                .deep_size_of_children(context) +
102            self.static_attributes
103                .deep_size_of_children(context) +
104            self.change
105                .deep_size_of_children(context) +
106            self.creation_tx
107                .deep_size_of_children(context)
108    }
109}
110
111#[derive(Debug, Clone, PartialEq)]
112pub struct ProtocolComponentState {
113    pub component_id: ComponentId,
114    pub attributes: HashMap<AttrStoreKey, StoreVal>,
115    // used during snapshots retrieval by the gateway
116    pub balances: HashMap<Address, Balance>,
117}
118
119impl ProtocolComponentState {
120    pub fn new(
121        component_id: &str,
122        attributes: HashMap<AttrStoreKey, StoreVal>,
123        balances: HashMap<Address, Balance>,
124    ) -> Self {
125        Self { component_id: component_id.to_string(), attributes, balances }
126    }
127
128    /// Applies state deltas to this state.
129    ///
130    /// This method assumes that the passed delta is "newer" than the current state.
131    pub fn apply_state_delta(
132        &mut self,
133        delta: &ProtocolComponentStateDelta,
134    ) -> Result<(), MergeError> {
135        if self.component_id != delta.component_id {
136            return Err(MergeError::IdMismatch(
137                "ProtocolComponentStates".to_string(),
138                self.component_id.clone(),
139                delta.component_id.clone(),
140            ));
141        }
142        self.attributes
143            .extend(delta.updated_attributes.clone());
144
145        self.attributes
146            .retain(|attr, _| !delta.deleted_attributes.contains(attr));
147
148        Ok(())
149    }
150
151    /// Applies balance deltas to this state.
152    ///
153    /// This method assumes that the passed delta is "newer" than the current state.
154    #[expect(
155        clippy::unnecessary_wraps,
156        reason = "public API; changing the signature is a breaking change"
157    )]
158    pub fn apply_balance_delta(
159        &mut self,
160        delta: &HashMap<Bytes, ComponentBalance>,
161    ) -> Result<(), MergeError> {
162        self.balances.extend(
163            delta
164                .iter()
165                .map(|(k, v)| (k.clone(), v.balance.clone())),
166        );
167
168        Ok(())
169    }
170}
171
172#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, DeepSizeOf)]
173pub struct ProtocolComponentStateDelta {
174    pub component_id: ComponentId,
175    pub updated_attributes: HashMap<AttrStoreKey, StoreVal>,
176    pub deleted_attributes: HashSet<AttrStoreKey>,
177    /// Attribute names first introduced with `ChangeType::Creation` in this delta.
178    /// Skipped during serialization — this is an indexer-internal hint, not part of the public
179    /// delta format.
180    #[serde(skip)]
181    pub created_attributes: HashSet<AttrStoreKey>,
182}
183
184impl ProtocolComponentStateDelta {
185    pub fn new(
186        component_id: &str,
187        updated_attributes: HashMap<AttrStoreKey, StoreVal>,
188        deleted_attributes: HashSet<AttrStoreKey>,
189    ) -> Self {
190        Self {
191            component_id: component_id.to_string(),
192            updated_attributes,
193            deleted_attributes,
194            created_attributes: HashSet::new(),
195        }
196    }
197
198    /// Merges this update with another one.
199    ///
200    /// The method combines two `ProtocolComponentStateDelta` instances if they are for the same
201    /// protocol component.
202    ///
203    /// NB: It is assumed that `other` is a more recent update than `self` is and the two are
204    /// combined accordingly.
205    ///
206    /// # Errors
207    /// This method will return `CoreError::MergeError` if any of the above
208    /// conditions is violated.
209    pub fn merge(&mut self, other: ProtocolComponentStateDelta) -> Result<(), MergeError> {
210        if self.component_id != other.component_id {
211            return Err(MergeError::IdMismatch(
212                "ProtocolComponentStateDeltas".to_string(),
213                self.component_id.clone(),
214                other.component_id.clone(),
215            ));
216        }
217        for attr in &other.deleted_attributes {
218            self.updated_attributes.remove(attr);
219            self.created_attributes.remove(attr);
220        }
221        for attr in other.updated_attributes.keys() {
222            self.deleted_attributes.remove(attr);
223        }
224        self.updated_attributes
225            .extend(other.updated_attributes);
226        self.deleted_attributes
227            .extend(other.deleted_attributes);
228        self.created_attributes
229            .extend(other.created_attributes);
230        Ok(())
231    }
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, DeepSizeOf)]
235pub struct ComponentBalance {
236    pub token: Address,
237    pub balance: Balance,
238    pub balance_float: f64,
239    pub modify_tx: TxHash,
240    pub component_id: ComponentId,
241}
242
243impl ComponentBalance {
244    pub fn new(
245        token: Address,
246        new_balance: Balance,
247        balance_float: f64,
248        modify_tx: TxHash,
249        component_id: &str,
250    ) -> Self {
251        Self {
252            token,
253            balance: new_balance,
254            balance_float,
255            modify_tx,
256            component_id: component_id.to_string(),
257        }
258    }
259}
260
261/// Token quality range filter
262///
263/// The quality range is considered inclusive and used as a filter, will be applied as such.
264#[derive(Debug, Clone)]
265pub struct QualityRange {
266    pub min: Option<i32>,
267    pub max: Option<i32>,
268}
269
270impl QualityRange {
271    pub fn new(min: i32, max: i32) -> Self {
272        Self { min: Some(min), max: Some(max) }
273    }
274
275    pub fn min_only(min: i32) -> Self {
276        Self { min: Some(min), max: None }
277    }
278
279    #[expect(
280        non_snake_case,
281        reason = "named after the Option::None it stands for; renaming the public constructor is a breaking change"
282    )]
283    pub fn None() -> Self {
284        Self { min: None, max: None }
285    }
286}
287
288pub struct GetAmountOutParams {
289    pub amount_in: BigUint,
290    pub token_in: Bytes,
291    pub token_out: Bytes,
292    pub sender: Bytes,
293    pub receiver: Bytes,
294    /// The end user's EOA (`tx.origin`), for RFQ providers that ask for it. `None` lets the
295    /// provider use its own default.
296    pub origin: Option<Bytes>,
297}
298
299impl From<dto::ProtocolStateDelta> for ProtocolComponentStateDelta {
300    fn from(value: dto::ProtocolStateDelta) -> Self {
301        Self {
302            component_id: value.component_id,
303            updated_attributes: value.updated_attributes,
304            deleted_attributes: value.deleted_attributes,
305            created_attributes: HashSet::new(),
306        }
307    }
308}
309
310impl From<dto::ComponentBalance> for ComponentBalance {
311    fn from(value: dto::ComponentBalance) -> Self {
312        Self {
313            token: value.token,
314            balance: value.balance,
315            balance_float: value.balance_float,
316            modify_tx: value.modify_tx,
317            component_id: value.component_id,
318        }
319    }
320}
321
322impl From<dto::ProtocolComponent> for ProtocolComponent {
323    fn from(value: dto::ProtocolComponent) -> Self {
324        Self {
325            id: value.id,
326            protocol_system: value.protocol_system,
327            protocol_type_name: value.protocol_type_name,
328            chain: value.chain.into(),
329            tokens: value.tokens,
330            contract_addresses: value.contract_ids,
331            static_attributes: value.static_attributes,
332            change: value.change.into(),
333            creation_tx: value.creation_tx,
334            created_at: value.created_at,
335        }
336    }
337}
338
339impl From<dto::ResponseProtocolState> for ProtocolComponentState {
340    fn from(value: dto::ResponseProtocolState) -> Self {
341        Self {
342            component_id: value.component_id,
343            attributes: value.attributes,
344            balances: value.balances,
345        }
346    }
347}
348
349#[cfg(test)]
350mod test {
351    use super::*;
352
353    fn create_state(id: String) -> ProtocolComponentStateDelta {
354        let attributes1: HashMap<String, Bytes> = vec![
355            ("reserve1".to_owned(), Bytes::from(1000u64).lpad(32, 0)),
356            ("reserve2".to_owned(), Bytes::from(500u64).lpad(32, 0)),
357            ("static_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
358        ]
359        .into_iter()
360        .collect();
361        ProtocolComponentStateDelta {
362            component_id: id,
363            updated_attributes: attributes1,
364            deleted_attributes: HashSet::new(),
365            ..Default::default()
366        }
367    }
368
369    #[test]
370    fn test_merge_protocol_state_updates() {
371        let mut state_1 = create_state("State1".to_owned());
372        state_1
373            .updated_attributes
374            .insert("to_be_removed".to_owned(), Bytes::from(1u64).lpad(32, 0));
375        state_1.deleted_attributes = vec!["to_add_back".to_owned()]
376            .into_iter()
377            .collect();
378
379        let attributes2: HashMap<String, Bytes> = vec![
380            ("reserve1".to_owned(), Bytes::from(900u64).lpad(32, 0)),
381            ("reserve2".to_owned(), Bytes::from(550u64).lpad(32, 0)),
382            ("new_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
383            ("to_add_back".to_owned(), Bytes::from(200u64).lpad(32, 0)),
384        ]
385        .into_iter()
386        .collect();
387        let del_attributes2: HashSet<String> = vec!["to_be_removed".to_owned()]
388            .into_iter()
389            .collect();
390        let mut state_2 = create_state("State1".to_owned());
391        state_2.updated_attributes = attributes2;
392        state_2.deleted_attributes = del_attributes2;
393
394        let res = state_1.merge(state_2);
395
396        assert!(res.is_ok());
397        let expected_attributes: HashMap<String, Bytes> = vec![
398            ("reserve1".to_owned(), Bytes::from(900u64).lpad(32, 0)),
399            ("reserve2".to_owned(), Bytes::from(550u64).lpad(32, 0)),
400            ("static_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
401            ("new_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
402            ("to_add_back".to_owned(), Bytes::from(200u64).lpad(32, 0)),
403        ]
404        .into_iter()
405        .collect();
406        assert_eq!(state_1.updated_attributes, expected_attributes);
407        let expected_del_attributes: HashSet<String> = vec!["to_be_removed".to_owned()]
408            .into_iter()
409            .collect();
410        assert_eq!(state_1.deleted_attributes, expected_del_attributes);
411    }
412
413    #[test]
414    fn test_merge_protocol_state_update_wrong_id() {
415        let mut state1 = create_state("State1".to_owned());
416        let state2 = create_state("State2".to_owned());
417
418        let res = state1.merge(state2);
419
420        assert_eq!(
421            res,
422            Err(MergeError::IdMismatch(
423                "ProtocolComponentStateDeltas".to_string(),
424                "State1".to_string(),
425                "State2".to_string(),
426            ))
427        );
428    }
429}