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        ProtocolSystem, 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/// An admin pause of one component, with optional audit details for operators.
262///
263/// `reason`, `actor` and `evidence_url` are notes for operators; no logic depends on them.
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct PauseRecord {
266    /// External id of the component to pause.
267    pub component_id: ComponentId,
268    /// Why the component is paused.
269    pub reason: Option<String>,
270    /// Who asked for the pause: an operator, or the service that called the admin API.
271    pub actor: Option<String>,
272    /// Link to evidence for the pause, such as a failing quote or an incident report.
273    pub evidence_url: Option<String>,
274}
275
276/// The end of admin pauses, with optional audit details for operators.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct UnpauseRecord {
279    /// Why the pauses ended.
280    pub reason: Option<String>,
281    /// Who ended the pauses: an operator, or the service that called the admin API.
282    pub actor: Option<String>,
283}
284
285/// An admin pause that is in effect.
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct ComponentPause {
288    pub protocol_system: ProtocolSystem,
289    pub record: PauseRecord,
290    /// When the pause started.
291    pub paused_at: NaiveDateTime,
292}
293
294/// Token quality range filter
295///
296/// The quality range is considered inclusive and used as a filter, will be applied as such.
297#[derive(Debug, Clone)]
298pub struct QualityRange {
299    pub min: Option<i32>,
300    pub max: Option<i32>,
301}
302
303impl QualityRange {
304    pub fn new(min: i32, max: i32) -> Self {
305        Self { min: Some(min), max: Some(max) }
306    }
307
308    pub fn min_only(min: i32) -> Self {
309        Self { min: Some(min), max: None }
310    }
311
312    #[expect(
313        non_snake_case,
314        reason = "named after the Option::None it stands for; renaming the public constructor is a breaking change"
315    )]
316    pub fn None() -> Self {
317        Self { min: None, max: None }
318    }
319}
320
321pub struct GetAmountOutParams {
322    pub amount_in: BigUint,
323    pub token_in: Bytes,
324    pub token_out: Bytes,
325    pub sender: Bytes,
326    pub receiver: Bytes,
327    /// The end user's EOA (`tx.origin`), for RFQ providers that ask for it. `None` lets the
328    /// provider use its own default.
329    pub origin: Option<Bytes>,
330}
331
332impl From<dto::ProtocolStateDelta> for ProtocolComponentStateDelta {
333    fn from(value: dto::ProtocolStateDelta) -> Self {
334        Self {
335            component_id: value.component_id,
336            updated_attributes: value.updated_attributes,
337            deleted_attributes: value.deleted_attributes,
338            created_attributes: HashSet::new(),
339        }
340    }
341}
342
343impl From<dto::ComponentBalance> for ComponentBalance {
344    fn from(value: dto::ComponentBalance) -> Self {
345        Self {
346            token: value.token,
347            balance: value.balance,
348            balance_float: value.balance_float,
349            modify_tx: value.modify_tx,
350            component_id: value.component_id,
351        }
352    }
353}
354
355impl From<dto::ProtocolComponent> for ProtocolComponent {
356    fn from(value: dto::ProtocolComponent) -> Self {
357        Self {
358            id: value.id,
359            protocol_system: value.protocol_system,
360            protocol_type_name: value.protocol_type_name,
361            chain: value.chain.into(),
362            tokens: value.tokens,
363            contract_addresses: value.contract_ids,
364            static_attributes: value.static_attributes,
365            change: value.change.into(),
366            creation_tx: value.creation_tx,
367            created_at: value.created_at,
368        }
369    }
370}
371
372impl From<dto::ResponseProtocolState> for ProtocolComponentState {
373    fn from(value: dto::ResponseProtocolState) -> Self {
374        Self {
375            component_id: value.component_id,
376            attributes: value.attributes,
377            balances: value.balances,
378        }
379    }
380}
381
382#[cfg(test)]
383mod test {
384    use super::*;
385
386    fn create_state(id: String) -> ProtocolComponentStateDelta {
387        let attributes1: HashMap<String, Bytes> = vec![
388            ("reserve1".to_owned(), Bytes::from(1000u64).lpad(32, 0)),
389            ("reserve2".to_owned(), Bytes::from(500u64).lpad(32, 0)),
390            ("static_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
391        ]
392        .into_iter()
393        .collect();
394        ProtocolComponentStateDelta {
395            component_id: id,
396            updated_attributes: attributes1,
397            deleted_attributes: HashSet::new(),
398            ..Default::default()
399        }
400    }
401
402    #[test]
403    fn test_merge_protocol_state_updates() {
404        let mut state_1 = create_state("State1".to_owned());
405        state_1
406            .updated_attributes
407            .insert("to_be_removed".to_owned(), Bytes::from(1u64).lpad(32, 0));
408        state_1.deleted_attributes = vec!["to_add_back".to_owned()]
409            .into_iter()
410            .collect();
411
412        let attributes2: HashMap<String, Bytes> = vec![
413            ("reserve1".to_owned(), Bytes::from(900u64).lpad(32, 0)),
414            ("reserve2".to_owned(), Bytes::from(550u64).lpad(32, 0)),
415            ("new_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
416            ("to_add_back".to_owned(), Bytes::from(200u64).lpad(32, 0)),
417        ]
418        .into_iter()
419        .collect();
420        let del_attributes2: HashSet<String> = vec!["to_be_removed".to_owned()]
421            .into_iter()
422            .collect();
423        let mut state_2 = create_state("State1".to_owned());
424        state_2.updated_attributes = attributes2;
425        state_2.deleted_attributes = del_attributes2;
426
427        let res = state_1.merge(state_2);
428
429        assert!(res.is_ok());
430        let expected_attributes: HashMap<String, Bytes> = vec![
431            ("reserve1".to_owned(), Bytes::from(900u64).lpad(32, 0)),
432            ("reserve2".to_owned(), Bytes::from(550u64).lpad(32, 0)),
433            ("static_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
434            ("new_attribute".to_owned(), Bytes::from(1u64).lpad(32, 0)),
435            ("to_add_back".to_owned(), Bytes::from(200u64).lpad(32, 0)),
436        ]
437        .into_iter()
438        .collect();
439        assert_eq!(state_1.updated_attributes, expected_attributes);
440        let expected_del_attributes: HashSet<String> = vec!["to_be_removed".to_owned()]
441            .into_iter()
442            .collect();
443        assert_eq!(state_1.deleted_attributes, expected_del_attributes);
444    }
445
446    #[test]
447    fn test_merge_protocol_state_update_wrong_id() {
448        let mut state1 = create_state("State1".to_owned());
449        let state2 = create_state("State2".to_owned());
450
451        let res = state1.merge(state2);
452
453        assert_eq!(
454            res,
455            Err(MergeError::IdMismatch(
456                "ProtocolComponentStateDeltas".to_string(),
457                "State1".to_string(),
458                "State2".to_string(),
459            ))
460        );
461    }
462}