Skip to main content

tycho_common/
dto.rs

1//! Data Transfer Objects (or structs)
2//!
3//! These structs serve to serialise and deserialize messages between server and client, they should
4//! be very simple and ideally not contain any business logic.
5//!
6//! Structs in here implement utoipa traits so they can be used to derive an OpenAPI schema.
7#![expect(
8    deprecated,
9    reason = "DTOs that are deprecated for consumers are still defined and used within this module"
10)]
11use std::{
12    collections::{BTreeMap, HashMap, HashSet},
13    fmt,
14    hash::{Hash, Hasher},
15    str::FromStr,
16};
17
18use arrayvec::ArrayString;
19use chrono::{NaiveDateTime, Utc};
20use deepsize::{Context, DeepSizeOf};
21use serde::{de, Deserialize, Deserializer, Serialize};
22use strum_macros::{Display, EnumString};
23use thiserror::Error;
24use utoipa::{IntoParams, ToSchema};
25use uuid::Uuid;
26
27use crate::{
28    models::{
29        self, chain_config::ChainConfigError, Address, Balance, Code, ComponentId, StoreKey,
30        StoreVal,
31    },
32    serde_primitives::{
33        hex_bytes, hex_bytes_option, hex_hashmap_key, hex_hashmap_key_value, hex_hashmap_value,
34    },
35    Bytes,
36};
37
38/// Currently supported Blockchains
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default, ToSchema)]
40#[serde(rename_all = "lowercase")]
41pub enum Chain {
42    #[default]
43    Ethereum,
44    Starknet,
45    ZkSync,
46    Arbitrum,
47    Base,
48    Bsc,
49    Unichain,
50    Polygon,
51    Plasma,
52    Robinhood,
53    Arc,
54    Elysium,
55    #[schema(value_type = String)]
56    Custom(ArrayString<32>),
57}
58
59impl DeepSizeOf for Chain {
60    fn deep_size_of_children(&self, _context: &mut Context) -> usize {
61        0
62    }
63}
64
65pub use models::chain_config::TvlThresholdTier;
66
67impl Chain {
68    /// Returns a default TVL threshold in native token units for the given tier.
69    pub fn default_tvl_threshold(&self, tier: TvlThresholdTier) -> f64 {
70        models::Chain::from(*self).default_tvl_threshold(tier)
71    }
72}
73
74impl fmt::Display for Chain {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        models::Chain::from(*self).fmt(f)
77    }
78}
79
80impl FromStr for Chain {
81    type Err = ChainConfigError;
82
83    fn from_str(s: &str) -> Result<Self, Self::Err> {
84        models::Chain::from_str(s).map(Self::from)
85    }
86}
87
88impl From<models::contract::Account> for ResponseAccount {
89    fn from(value: models::contract::Account) -> Self {
90        ResponseAccount::new(
91            value.chain.into(),
92            value.address,
93            value.title,
94            value.slots,
95            value.native_balance,
96            value
97                .token_balances
98                .into_iter()
99                .map(|(k, v)| (k, v.balance))
100                .collect(),
101            value.code,
102            value.code_hash,
103            value.balance_modify_tx,
104            value.code_modify_tx,
105            value.creation_tx,
106        )
107    }
108}
109
110impl From<models::Chain> for Chain {
111    fn from(value: models::Chain) -> Self {
112        match value {
113            models::Chain::Ethereum => Chain::Ethereum,
114            models::Chain::Starknet => Chain::Starknet,
115            models::Chain::ZkSync => Chain::ZkSync,
116            models::Chain::Arbitrum => Chain::Arbitrum,
117            models::Chain::Base => Chain::Base,
118            models::Chain::Bsc => Chain::Bsc,
119            models::Chain::Unichain => Chain::Unichain,
120            models::Chain::Polygon => Chain::Polygon,
121            models::Chain::Plasma => Chain::Plasma,
122            models::Chain::Robinhood => Chain::Robinhood,
123            models::Chain::Arc => Chain::Arc,
124            models::Chain::Elysium => Chain::Elysium,
125            models::Chain::Custom(id) => Chain::Custom(
126                ArrayString::from(id.as_str())
127                    .expect("custom chain name is already within 32 bytes"),
128            ),
129        }
130    }
131}
132
133#[derive(
134    Debug,
135    PartialEq,
136    Default,
137    Copy,
138    Clone,
139    Deserialize,
140    Serialize,
141    ToSchema,
142    EnumString,
143    Display,
144    DeepSizeOf,
145)]
146pub enum ChangeType {
147    #[default]
148    Update,
149    Deletion,
150    Creation,
151    Unspecified,
152}
153
154impl From<models::ChangeType> for ChangeType {
155    fn from(value: models::ChangeType) -> Self {
156        match value {
157            models::ChangeType::Update => ChangeType::Update,
158            models::ChangeType::Creation => ChangeType::Creation,
159            models::ChangeType::Deletion => ChangeType::Deletion,
160        }
161    }
162}
163
164impl ChangeType {
165    pub fn merge(&self, other: &Self) -> Self {
166        if matches!(self, Self::Creation) {
167            Self::Creation
168        } else {
169            *other
170        }
171    }
172}
173
174#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Default)]
175pub struct ExtractorIdentity {
176    pub chain: Chain,
177    pub name: String,
178}
179
180impl ExtractorIdentity {
181    pub fn new(chain: Chain, name: &str) -> Self {
182        Self { chain, name: name.to_owned() }
183    }
184}
185
186impl fmt::Display for ExtractorIdentity {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        write!(f, "{}:{}", self.chain, self.name)
189    }
190}
191
192/// A command sent from the client to the server
193#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
194#[serde(tag = "method", rename_all = "lowercase")]
195pub enum Command {
196    Subscribe {
197        extractor_id: ExtractorIdentity,
198        include_state: bool,
199        /// Enable zstd compression for messages in this subscription.
200        /// Defaults to false for backward compatibility.
201        #[serde(default)]
202        compression: bool,
203        /// Enables receiving partial block update messages in this subscription.
204        /// Defaults to false for backward compatibility.
205        #[serde(default)]
206        partial_blocks: bool,
207    },
208    Unsubscribe {
209        subscription_id: Uuid,
210    },
211}
212
213/// A easy serializable version of `models::error::WebsocketError`
214///
215/// This serves purely to transfer errors via websocket. It is meant to render
216/// similarly to the original struct but does not have server side debug information
217/// attached.
218///
219/// It should contain information needed to handle errors correctly on the client side.
220#[derive(Error, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
221pub enum WebsocketError {
222    #[error("Extractor not found: {0}")]
223    ExtractorNotFound(ExtractorIdentity),
224
225    #[error("Subscription not found: {0}")]
226    SubscriptionNotFound(Uuid),
227
228    #[error("Failed to parse JSON: {1}, msg: {0}")]
229    ParseError(String, String),
230
231    #[error("Failed to subscribe to extractor: {0}")]
232    SubscribeError(ExtractorIdentity),
233
234    #[error("Failed to compress message for subscription: {0}, error: {1}")]
235    CompressionError(Uuid, String),
236}
237
238impl From<crate::models::error::WebsocketError> for WebsocketError {
239    fn from(value: crate::models::error::WebsocketError) -> Self {
240        match value {
241            crate::models::error::WebsocketError::ExtractorNotFound(eid) => {
242                Self::ExtractorNotFound(eid.into())
243            }
244            crate::models::error::WebsocketError::SubscriptionNotFound(sid) => {
245                Self::SubscriptionNotFound(sid)
246            }
247            crate::models::error::WebsocketError::ParseError(raw, error) => {
248                Self::ParseError(error.to_string(), raw)
249            }
250            crate::models::error::WebsocketError::SubscribeError(eid) => {
251                Self::SubscribeError(eid.into())
252            }
253            crate::models::error::WebsocketError::CompressionError(sid, error) => {
254                Self::CompressionError(sid, error.to_string())
255            }
256        }
257    }
258}
259
260/// A response sent from the server to the client
261#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
262#[serde(tag = "method", rename_all = "lowercase")]
263pub enum Response {
264    NewSubscription { extractor_id: ExtractorIdentity, subscription_id: Uuid },
265    SubscriptionEnded { subscription_id: Uuid },
266    Error(WebsocketError),
267}
268
269/// A message sent from the server to the client
270#[expect(
271    clippy::large_enum_variant,
272    reason = "public API; boxing the large variant is a breaking change"
273)]
274#[derive(Serialize, Deserialize, Debug, Display, Clone)]
275#[serde(untagged)]
276pub enum WebSocketMessage {
277    BlockAggregatedChanges { subscription_id: Uuid, deltas: BlockAggregatedChanges },
278    Response(Response),
279}
280
281#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default, ToSchema)]
282pub struct Block {
283    pub number: u64,
284    #[serde(with = "hex_bytes")]
285    pub hash: Bytes,
286    #[serde(with = "hex_bytes")]
287    pub parent_hash: Bytes,
288    pub chain: Chain,
289    pub ts: NaiveDateTime,
290}
291
292#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema, Eq, Hash, DeepSizeOf)]
293#[serde(deny_unknown_fields)]
294pub struct BlockParam {
295    #[schema(value_type=Option<String>)]
296    #[serde(with = "hex_bytes_option", default)]
297    pub hash: Option<Bytes>,
298    #[deprecated(
299        note = "The `chain` field is deprecated and will be removed in a future version."
300    )]
301    #[serde(default)]
302    pub chain: Option<Chain>,
303    #[serde(default)]
304    pub number: Option<i64>,
305}
306
307impl From<&Block> for BlockParam {
308    fn from(value: &Block) -> Self {
309        // The hash should uniquely identify a block across chains
310        BlockParam { hash: Some(value.hash.clone()), chain: None, number: None }
311    }
312}
313
314#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
315pub struct TokenBalances(#[serde(with = "hex_hashmap_key")] pub HashMap<Bytes, ComponentBalance>);
316
317impl From<HashMap<Bytes, ComponentBalance>> for TokenBalances {
318    fn from(value: HashMap<Bytes, ComponentBalance>) -> Self {
319        TokenBalances(value)
320    }
321}
322
323#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
324pub struct Transaction {
325    #[serde(with = "hex_bytes")]
326    pub hash: Bytes,
327    #[serde(with = "hex_bytes")]
328    pub block_hash: Bytes,
329    #[serde(with = "hex_bytes")]
330    pub from: Bytes,
331    #[serde(with = "hex_bytes_option")]
332    pub to: Option<Bytes>,
333    pub index: u64,
334}
335
336impl Transaction {
337    pub fn new(hash: Bytes, block_hash: Bytes, from: Bytes, to: Option<Bytes>, index: u64) -> Self {
338        Self { hash, block_hash, from, to, index }
339    }
340}
341
342/// A container for updates grouped by account/component.
343#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
344pub struct BlockAggregatedChanges {
345    pub extractor: String,
346    pub chain: Chain,
347    pub block: Block,
348    pub finalized_block_height: u64,
349    pub revert: bool,
350    #[serde(with = "hex_hashmap_key", default)]
351    pub new_tokens: HashMap<Bytes, ResponseToken>,
352    #[serde(alias = "account_deltas", with = "hex_hashmap_key")]
353    pub account_updates: HashMap<Bytes, AccountUpdate>,
354    #[serde(alias = "state_deltas")]
355    pub state_updates: HashMap<String, ProtocolStateDelta>,
356    pub new_protocol_components: HashMap<String, ProtocolComponent>,
357    pub deleted_protocol_components: HashMap<String, ProtocolComponent>,
358    pub component_balances: HashMap<String, TokenBalances>,
359    pub account_balances: HashMap<Bytes, HashMap<Bytes, AccountBalance>>,
360    pub component_tvl: HashMap<String, f64>,
361    pub dci_update: DCIUpdate,
362    /// The index of the partial block. None if it's a full block.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub partial_block_index: Option<u32>,
365}
366
367impl BlockAggregatedChanges {
368    #[expect(
369        clippy::too_many_arguments,
370        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
371    )]
372    pub fn new(
373        extractor: &str,
374        chain: Chain,
375        block: Block,
376        finalized_block_height: u64,
377        revert: bool,
378        account_updates: HashMap<Bytes, AccountUpdate>,
379        state_updates: HashMap<String, ProtocolStateDelta>,
380        new_protocol_components: HashMap<String, ProtocolComponent>,
381        deleted_protocol_components: HashMap<String, ProtocolComponent>,
382        component_balances: HashMap<String, HashMap<Bytes, ComponentBalance>>,
383        account_balances: HashMap<Bytes, HashMap<Bytes, AccountBalance>>,
384        dci_update: DCIUpdate,
385    ) -> Self {
386        BlockAggregatedChanges {
387            extractor: extractor.to_owned(),
388            chain,
389            block,
390            finalized_block_height,
391            revert,
392            new_tokens: HashMap::new(),
393            account_updates,
394            state_updates,
395            new_protocol_components,
396            deleted_protocol_components,
397            component_balances: component_balances
398                .into_iter()
399                .map(|(k, v)| (k, v.into()))
400                .collect(),
401            account_balances,
402            component_tvl: HashMap::new(),
403            dci_update,
404            partial_block_index: None,
405        }
406    }
407
408    pub fn merge(mut self, other: Self) -> Self {
409        other
410            .account_updates
411            .into_iter()
412            .for_each(|(k, v)| {
413                self.account_updates
414                    .entry(k)
415                    .and_modify(|e| {
416                        e.merge(&v);
417                    })
418                    .or_insert(v);
419            });
420
421        other
422            .state_updates
423            .into_iter()
424            .for_each(|(k, v)| {
425                self.state_updates
426                    .entry(k)
427                    .and_modify(|e| {
428                        e.merge(&v);
429                    })
430                    .or_insert(v);
431            });
432
433        other
434            .component_balances
435            .into_iter()
436            .for_each(|(k, v)| {
437                self.component_balances
438                    .entry(k)
439                    .and_modify(|e| e.0.extend(v.0.clone()))
440                    .or_insert_with(|| v);
441            });
442
443        other
444            .account_balances
445            .into_iter()
446            .for_each(|(k, v)| {
447                self.account_balances
448                    .entry(k)
449                    .and_modify(|e| e.extend(v.clone()))
450                    .or_insert(v);
451            });
452
453        self.component_tvl
454            .extend(other.component_tvl);
455        self.new_protocol_components
456            .extend(other.new_protocol_components);
457        self.deleted_protocol_components
458            .extend(other.deleted_protocol_components);
459        self.revert = other.revert;
460        self.block = other.block;
461
462        self
463    }
464
465    pub fn get_block(&self) -> &Block {
466        &self.block
467    }
468
469    pub fn is_revert(&self) -> bool {
470        self.revert
471    }
472
473    pub fn filter_by_component<F: Fn(&str) -> bool>(&mut self, keep: F) {
474        self.state_updates
475            .retain(|k, _| keep(k));
476        self.component_balances
477            .retain(|k, _| keep(k));
478        self.component_tvl
479            .retain(|k, _| keep(k));
480    }
481
482    pub fn filter_by_contract<F: Fn(&Bytes) -> bool>(&mut self, keep: F) {
483        self.account_updates
484            .retain(|k, _| keep(k));
485        self.account_balances
486            .retain(|k, _| keep(k));
487    }
488
489    pub fn n_changes(&self) -> usize {
490        self.account_updates.len() + self.state_updates.len()
491    }
492
493    pub fn drop_state(&self) -> Self {
494        Self {
495            extractor: self.extractor.clone(),
496            chain: self.chain,
497            block: self.block.clone(),
498            finalized_block_height: self.finalized_block_height,
499            revert: self.revert,
500            new_tokens: self.new_tokens.clone(),
501            account_updates: HashMap::new(),
502            state_updates: HashMap::new(),
503            new_protocol_components: self.new_protocol_components.clone(),
504            deleted_protocol_components: self.deleted_protocol_components.clone(),
505            component_balances: self.component_balances.clone(),
506            account_balances: self.account_balances.clone(),
507            component_tvl: self.component_tvl.clone(),
508            dci_update: self.dci_update.clone(),
509            partial_block_index: self.partial_block_index,
510        }
511    }
512
513    pub fn is_partial_block(&self) -> bool {
514        self.partial_block_index.is_some()
515    }
516}
517
518impl From<models::blockchain::Block> for Block {
519    fn from(value: models::blockchain::Block) -> Self {
520        Self {
521            number: value.number,
522            hash: value.hash,
523            parent_hash: value.parent_hash,
524            chain: value.chain.into(),
525            ts: value.ts,
526        }
527    }
528}
529
530impl From<models::protocol::ComponentBalance> for ComponentBalance {
531    fn from(value: models::protocol::ComponentBalance) -> Self {
532        Self {
533            token: value.token,
534            balance: value.balance,
535            balance_float: value.balance_float,
536            modify_tx: value.modify_tx,
537            component_id: value.component_id,
538        }
539    }
540}
541
542impl From<models::contract::AccountBalance> for AccountBalance {
543    fn from(value: models::contract::AccountBalance) -> Self {
544        Self {
545            account: value.account,
546            token: value.token,
547            balance: value.balance,
548            modify_tx: value.modify_tx,
549        }
550    }
551}
552
553impl From<models::blockchain::BlockAggregatedChanges> for BlockAggregatedChanges {
554    fn from(value: models::blockchain::BlockAggregatedChanges) -> Self {
555        Self {
556            extractor: value.extractor,
557            chain: value.chain.into(),
558            block: value.block.into(),
559            finalized_block_height: value.finalized_block_height,
560            revert: value.revert,
561            account_updates: value
562                .account_deltas
563                .into_iter()
564                .map(|(k, v)| (k, v.into()))
565                .collect(),
566            state_updates: value
567                .state_deltas
568                .into_iter()
569                .map(|(k, v)| (k, v.into()))
570                .collect(),
571            new_protocol_components: value
572                .new_protocol_components
573                .into_iter()
574                .map(|(k, v)| (k, v.into()))
575                .collect(),
576            deleted_protocol_components: value
577                .deleted_protocol_components
578                .into_iter()
579                .map(|(k, v)| (k, v.into()))
580                .collect(),
581            component_balances: value
582                .component_balances
583                .into_iter()
584                .map(|(component_id, v)| {
585                    let balances: HashMap<Bytes, ComponentBalance> = v
586                        .into_iter()
587                        .map(|(k, v)| (k, ComponentBalance::from(v)))
588                        .collect();
589                    (component_id, balances.into())
590                })
591                .collect(),
592            account_balances: value
593                .account_balances
594                .into_iter()
595                .map(|(k, v)| {
596                    (
597                        k,
598                        v.into_iter()
599                            .map(|(k, v)| (k, v.into()))
600                            .collect(),
601                    )
602                })
603                .collect(),
604            dci_update: value.dci_update.into(),
605            new_tokens: value
606                .new_tokens
607                .into_iter()
608                .map(|(k, v)| (k, v.into()))
609                .collect(),
610            component_tvl: value.component_tvl,
611            partial_block_index: value.partial_block_index,
612        }
613    }
614}
615
616#[derive(PartialEq, Serialize, Deserialize, Clone, Debug, ToSchema)]
617pub struct AccountUpdate {
618    #[serde(with = "hex_bytes")]
619    #[schema(value_type=String)]
620    pub address: Bytes,
621    pub chain: Chain,
622    #[serde(with = "hex_hashmap_key_value")]
623    #[schema(value_type=HashMap<String, String>)]
624    pub slots: HashMap<Bytes, Bytes>,
625    #[serde(with = "hex_bytes_option")]
626    #[schema(value_type=Option<String>)]
627    pub balance: Option<Bytes>,
628    #[serde(with = "hex_bytes_option")]
629    #[schema(value_type=Option<String>)]
630    pub code: Option<Bytes>,
631    pub change: ChangeType,
632}
633
634impl AccountUpdate {
635    pub fn new(
636        address: Bytes,
637        chain: Chain,
638        slots: HashMap<Bytes, Bytes>,
639        balance: Option<Bytes>,
640        code: Option<Bytes>,
641        change: ChangeType,
642    ) -> Self {
643        Self { address, chain, slots, balance, code, change }
644    }
645
646    /// Merges a newer update for the same account into this one.
647    ///
648    /// Fields absent in `other` keep their current values, matching
649    /// [`models::contract::AccountDelta::merge`].
650    pub fn merge(&mut self, other: &Self) {
651        self.slots.extend(
652            other
653                .slots
654                .iter()
655                .map(|(k, v)| (k.clone(), v.clone())),
656        );
657        if other.balance.is_some() {
658            self.balance.clone_from(&other.balance);
659        }
660        if other.code.is_some() {
661            self.code.clone_from(&other.code);
662        }
663        self.change = self.change.merge(&other.change);
664    }
665}
666
667impl From<models::contract::AccountDelta> for AccountUpdate {
668    fn from(value: models::contract::AccountDelta) -> Self {
669        let code = value.code().clone();
670        let change_type = value.change_type().into();
671        AccountUpdate::new(
672            value.address,
673            value.chain.into(),
674            value
675                .slots
676                .into_iter()
677                .map(|(k, v)| (k, v.unwrap_or_default()))
678                .collect(),
679            value.balance,
680            code,
681            change_type,
682        )
683    }
684}
685
686/// Represents the static parts of a protocol component.
687#[derive(Debug, Clone, PartialEq, Default, Deserialize, Serialize, ToSchema)]
688pub struct ProtocolComponent {
689    /// Unique identifier for this component
690    pub id: String,
691    /// Protocol system this component is part of
692    pub protocol_system: String,
693    /// Type of the protocol system
694    pub protocol_type_name: String,
695    pub chain: Chain,
696    /// Token addresses the component operates on
697    #[schema(value_type=Vec<String>)]
698    pub tokens: Vec<Bytes>,
699    /// Contract addresses involved in the components operations (may be empty for
700    /// native implementations)
701    #[serde(alias = "contract_addresses")]
702    #[schema(value_type=Vec<String>)]
703    pub contract_ids: Vec<Bytes>,
704    /// Constant attributes of the component
705    #[serde(with = "hex_hashmap_value")]
706    #[schema(value_type=HashMap<String, String>)]
707    pub static_attributes: HashMap<String, Bytes>,
708    /// Indicates if last change was update, create or delete (for internal use only).
709    #[serde(default)]
710    pub change: ChangeType,
711    /// Transaction hash which created this component
712    #[serde(with = "hex_bytes")]
713    #[schema(value_type=String)]
714    pub creation_tx: Bytes,
715    /// Date time of creation in UTC time
716    pub created_at: NaiveDateTime,
717}
718
719// Manual impl as `NaiveDateTime` structure referenced in `created_at` does not implement DeepSizeOf
720impl DeepSizeOf for ProtocolComponent {
721    fn deep_size_of_children(&self, context: &mut Context) -> usize {
722        self.id.deep_size_of_children(context) +
723            self.protocol_system
724                .deep_size_of_children(context) +
725            self.protocol_type_name
726                .deep_size_of_children(context) +
727            self.chain
728                .deep_size_of_children(context) +
729            self.tokens
730                .deep_size_of_children(context) +
731            self.contract_ids
732                .deep_size_of_children(context) +
733            self.static_attributes
734                .deep_size_of_children(context) +
735            self.change
736                .deep_size_of_children(context) +
737            self.creation_tx
738                .deep_size_of_children(context)
739    }
740}
741
742impl<T> From<models::protocol::ProtocolComponent<T>> for ProtocolComponent
743where
744    T: Into<Address> + Clone,
745{
746    fn from(value: models::protocol::ProtocolComponent<T>) -> Self {
747        Self {
748            id: value.id,
749            protocol_system: value.protocol_system,
750            protocol_type_name: value.protocol_type_name,
751            chain: value.chain.into(),
752            tokens: value
753                .tokens
754                .into_iter()
755                .map(|t| t.into())
756                .collect(),
757            contract_ids: value.contract_addresses,
758            static_attributes: value.static_attributes,
759            change: value.change.into(),
760            creation_tx: value.creation_tx,
761            created_at: value.created_at,
762        }
763    }
764}
765
766#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
767pub struct ComponentBalance {
768    #[serde(with = "hex_bytes")]
769    pub token: Bytes,
770    pub balance: Bytes,
771    pub balance_float: f64,
772    #[serde(with = "hex_bytes")]
773    pub modify_tx: Bytes,
774    pub component_id: String,
775}
776
777#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize, ToSchema)]
778/// Represents a change in protocol state.
779pub struct ProtocolStateDelta {
780    pub component_id: String,
781    #[schema(value_type=HashMap<String, String>)]
782    pub updated_attributes: HashMap<String, Bytes>,
783    pub deleted_attributes: HashSet<String>,
784}
785
786impl From<models::protocol::ProtocolComponentStateDelta> for ProtocolStateDelta {
787    fn from(value: models::protocol::ProtocolComponentStateDelta) -> Self {
788        Self {
789            component_id: value.component_id,
790            updated_attributes: value.updated_attributes,
791            deleted_attributes: value.deleted_attributes,
792        }
793    }
794}
795
796impl ProtocolStateDelta {
797    /// Merges 'other' into 'self'.
798    ///
799    ///
800    /// During merge of these deltas a special situation can arise when an attribute is present in
801    /// `self.deleted_attributes` and `other.update_attributes``. If we would just merge the sets
802    /// of deleted attributes or vice versa, it would be ambiguous and potential lead to a
803    /// deletion of an attribute that should actually be present, or retention of an actually
804    /// deleted attribute.
805    ///
806    /// This situation is handled the following way:
807    ///
808    ///     - If an attribute is deleted and in the next message recreated, it is removed from the
809    ///       set of deleted attributes and kept in updated_attributes. This way it's temporary
810    ///       deletion is never communicated to the final receiver.
811    ///     - If an attribute was updated and is deleted in the next message, it is removed from
812    ///       updated attributes and kept in deleted. This way the attributes temporary update (or
813    ///       potentially short-lived existence) before its deletion is never communicated to the
814    ///       final receiver.
815    pub fn merge(&mut self, other: &Self) {
816        // either updated and then deleted -> keep in deleted, remove from updated
817        self.updated_attributes
818            .retain(|k, _| !other.deleted_attributes.contains(k));
819
820        // or deleted and then updated/recreated -> remove from deleted and keep in updated
821        self.deleted_attributes.retain(|attr| {
822            !other
823                .updated_attributes
824                .contains_key(attr)
825        });
826
827        // simply merge updates
828        self.updated_attributes.extend(
829            other
830                .updated_attributes
831                .iter()
832                .map(|(k, v)| (k.clone(), v.clone())),
833        );
834
835        // simply merge deletions
836        self.deleted_attributes
837            .extend(other.deleted_attributes.iter().cloned());
838    }
839}
840
841/// Pagination parameter
842#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, Eq, Hash, DeepSizeOf)]
843#[serde(deny_unknown_fields)]
844pub struct PaginationParams {
845    /// What page to retrieve
846    #[serde(default)]
847    pub page: i64,
848    /// How many results to return per page
849    #[serde(default)]
850    #[schema(default = 100)]
851    pub page_size: i64,
852}
853
854impl PaginationParams {
855    pub fn new(page: i64, page_size: i64) -> Self {
856        Self { page, page_size }
857    }
858}
859
860impl Default for PaginationParams {
861    fn default() -> Self {
862        PaginationParams { page: 0, page_size: 100 }
863    }
864}
865
866/// Defines pagination size limits for request types.
867///
868/// Different limits apply based on whether compression is enabled,
869/// as compressed responses can safely transfer more data.
870pub trait PaginationLimits {
871    /// Maximum page size when compression is enabled (e.g., zstd)
872    const MAX_PAGE_SIZE_COMPRESSED: i64;
873
874    /// Maximum page size when compression is disabled
875    const MAX_PAGE_SIZE_UNCOMPRESSED: i64;
876
877    /// Returns the effective maximum page size based on compression setting
878    fn effective_max_page_size(compression: bool) -> i64 {
879        if compression {
880            Self::MAX_PAGE_SIZE_COMPRESSED
881        } else {
882            Self::MAX_PAGE_SIZE_UNCOMPRESSED
883        }
884    }
885
886    /// Returns a reference to the pagination parameters
887    fn pagination(&self) -> &PaginationParams;
888}
889
890/// Macro to implement PaginationLimits for request types
891///
892/// When INCREASING these limits, ensure to immediately redeploy the servers.
893///
894/// Why: pagination limits are shared. Clients use these constants to set their max page size.
895/// When clients upgrade before servers, they request more than old servers allow and get errors.
896macro_rules! impl_pagination_limits {
897    ($type:ty, compressed = $comp:expr, uncompressed = $uncomp:expr) => {
898        impl $crate::dto::PaginationLimits for $type {
899            const MAX_PAGE_SIZE_COMPRESSED: i64 = $comp;
900            const MAX_PAGE_SIZE_UNCOMPRESSED: i64 = $uncomp;
901
902            fn pagination(&self) -> &$crate::dto::PaginationParams {
903                &self.pagination
904            }
905        }
906    };
907}
908
909#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, Eq, Hash, DeepSizeOf)]
910#[serde(deny_unknown_fields)]
911pub struct PaginationResponse {
912    pub page: i64,
913    pub page_size: i64,
914    /// The total number of items available across all pages of results
915    pub total: i64,
916}
917
918/// Current pagination information
919impl PaginationResponse {
920    pub fn new(page: i64, page_size: i64, total: i64) -> Self {
921        Self { page, page_size, total }
922    }
923
924    pub fn total_pages(&self) -> i64 {
925        // ceil(total / page_size)
926        (self.total + self.page_size - 1) / self.page_size
927    }
928}
929
930#[derive(
931    Clone, Serialize, Debug, Default, Deserialize, PartialEq, ToSchema, Eq, Hash, DeepSizeOf,
932)]
933#[serde(deny_unknown_fields)]
934pub struct StateRequestBody {
935    /// Filters response by contract addresses
936    #[serde(alias = "contractIds")]
937    #[schema(value_type=Option<Vec<String>>)]
938    pub contract_ids: Option<Vec<Bytes>>,
939    /// Does not filter response, only required to correctly apply unconfirmed state
940    /// from ReorgBuffers
941    #[serde(alias = "protocolSystem", default)]
942    pub protocol_system: String,
943    #[serde(default = "VersionParam::default")]
944    pub version: VersionParam,
945    #[serde(default)]
946    pub chain: Chain,
947    #[serde(default)]
948    pub pagination: PaginationParams,
949}
950
951// When INCREASING these limits, please read the warning in the macro definition.
952impl_pagination_limits!(StateRequestBody, compressed = 1200, uncompressed = 100);
953
954impl StateRequestBody {
955    pub fn new(
956        contract_ids: Option<Vec<Bytes>>,
957        protocol_system: String,
958        version: VersionParam,
959        chain: Chain,
960        pagination: PaginationParams,
961    ) -> Self {
962        Self { contract_ids, protocol_system, version, chain, pagination }
963    }
964
965    #[expect(
966        clippy::needless_pass_by_value,
967        reason = "public API; taking `&BlockParam` is a breaking change"
968    )]
969    pub fn from_block(protocol_system: &str, block: BlockParam) -> Self {
970        Self {
971            contract_ids: None,
972            protocol_system: protocol_system.to_string(),
973            version: VersionParam { timestamp: None, block: Some(block.clone()) },
974            chain: block.chain.unwrap_or_default(),
975            pagination: PaginationParams::default(),
976        }
977    }
978
979    pub fn from_timestamp(protocol_system: &str, timestamp: NaiveDateTime, chain: Chain) -> Self {
980        Self {
981            contract_ids: None,
982            protocol_system: protocol_system.to_string(),
983            version: VersionParam { timestamp: Some(timestamp), block: None },
984            chain,
985            pagination: PaginationParams::default(),
986        }
987    }
988}
989
990/// Response from Tycho server for a contract state request.
991#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, DeepSizeOf)]
992pub struct StateRequestResponse {
993    pub accounts: Vec<ResponseAccount>,
994    pub pagination: PaginationResponse,
995}
996
997impl StateRequestResponse {
998    pub fn new(accounts: Vec<ResponseAccount>, pagination: PaginationResponse) -> Self {
999        Self { accounts, pagination }
1000    }
1001}
1002
1003#[derive(PartialEq, Clone, Serialize, Deserialize, Default, ToSchema, DeepSizeOf)]
1004#[serde(rename = "Account")]
1005/// Account struct for the response from Tycho server for a contract state request.
1006///
1007/// Code is serialized as a hex string instead of a list of bytes.
1008pub struct ResponseAccount {
1009    pub chain: Chain,
1010    /// The address of the account as hex encoded string
1011    #[schema(value_type=String, example="0xc9f2e6ea1637E499406986ac50ddC92401ce1f58")]
1012    #[serde(with = "hex_bytes")]
1013    pub address: Bytes,
1014    /// The title of the account usualy specifying its function within the protocol
1015    #[schema(value_type=String, example="Protocol Vault")]
1016    pub title: String,
1017    /// Contract storage map of hex encoded string values
1018    #[schema(value_type=HashMap<String, String>, example=json!({"0x....": "0x...."}))]
1019    #[serde(with = "hex_hashmap_key_value")]
1020    pub slots: HashMap<Bytes, Bytes>,
1021    /// The balance of the account in the native token
1022    #[schema(value_type=String, example="0x00")]
1023    #[serde(with = "hex_bytes")]
1024    pub native_balance: Bytes,
1025    /// Balances of this account in other tokens (only tokens balance that are
1026    /// relevant to the protocol are returned here)
1027    #[schema(value_type=HashMap<String, String>, example=json!({"0x....": "0x...."}))]
1028    #[serde(with = "hex_hashmap_key_value")]
1029    pub token_balances: HashMap<Bytes, Bytes>,
1030    /// The accounts code as hex encoded string
1031    #[schema(value_type=String, example="0xBADBABE")]
1032    #[serde(with = "hex_bytes")]
1033    pub code: Bytes,
1034    /// The hash of above code
1035    #[schema(value_type=String, example="0x123456789")]
1036    #[serde(with = "hex_bytes")]
1037    pub code_hash: Bytes,
1038    /// Transaction hash which last modified native balance
1039    #[schema(value_type=String, example="0x8f1133bfb054a23aedfe5d25b1d81b96195396d8b88bd5d4bcf865fc1ae2c3f4")]
1040    #[serde(with = "hex_bytes")]
1041    pub balance_modify_tx: Bytes,
1042    /// Transaction hash which last modified code
1043    #[schema(value_type=String, example="0x8f1133bfb054a23aedfe5d25b1d81b96195396d8b88bd5d4bcf865fc1ae2c3f4")]
1044    #[serde(with = "hex_bytes")]
1045    pub code_modify_tx: Bytes,
1046    /// Transaction hash which created the account
1047    #[deprecated(note = "The `creation_tx` field is deprecated.")]
1048    #[schema(value_type=Option<String>, example="0x8f1133bfb054a23aedfe5d25b1d81b96195396d8b88bd5d4bcf865fc1ae2c3f4")]
1049    #[serde(with = "hex_bytes_option")]
1050    pub creation_tx: Option<Bytes>,
1051}
1052
1053impl ResponseAccount {
1054    #[expect(
1055        clippy::too_many_arguments,
1056        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
1057    )]
1058    pub fn new(
1059        chain: Chain,
1060        address: Bytes,
1061        title: String,
1062        slots: HashMap<Bytes, Bytes>,
1063        native_balance: Bytes,
1064        token_balances: HashMap<Bytes, Bytes>,
1065        code: Bytes,
1066        code_hash: Bytes,
1067        balance_modify_tx: Bytes,
1068        code_modify_tx: Bytes,
1069        creation_tx: Option<Bytes>,
1070    ) -> Self {
1071        Self {
1072            chain,
1073            address,
1074            title,
1075            slots,
1076            native_balance,
1077            token_balances,
1078            code,
1079            code_hash,
1080            balance_modify_tx,
1081            code_modify_tx,
1082            creation_tx,
1083        }
1084    }
1085}
1086
1087/// Implement Debug for ResponseAccount manually to avoid printing the code field.
1088impl fmt::Debug for ResponseAccount {
1089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1090        f.debug_struct("ResponseAccount")
1091            .field("chain", &self.chain)
1092            .field("address", &self.address)
1093            .field("title", &self.title)
1094            .field("slots", &self.slots)
1095            .field("native_balance", &self.native_balance)
1096            .field("token_balances", &self.token_balances)
1097            .field("code", &format!("[{} bytes]", self.code.len()))
1098            .field("code_hash", &self.code_hash)
1099            .field("balance_modify_tx", &self.balance_modify_tx)
1100            .field("code_modify_tx", &self.code_modify_tx)
1101            .field("creation_tx", &self.creation_tx)
1102            .finish()
1103    }
1104}
1105
1106#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
1107pub struct AccountBalance {
1108    #[serde(with = "hex_bytes")]
1109    pub account: Bytes,
1110    #[serde(with = "hex_bytes")]
1111    pub token: Bytes,
1112    #[serde(with = "hex_bytes")]
1113    pub balance: Bytes,
1114    #[serde(with = "hex_bytes")]
1115    pub modify_tx: Bytes,
1116}
1117
1118#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema)]
1119#[serde(deny_unknown_fields)]
1120pub struct ContractId {
1121    #[serde(with = "hex_bytes")]
1122    #[schema(value_type=String)]
1123    pub address: Bytes,
1124    pub chain: Chain,
1125}
1126
1127/// Uniquely identifies a contract on a specific chain.
1128impl ContractId {
1129    pub fn new(chain: Chain, address: Bytes) -> Self {
1130        Self { address, chain }
1131    }
1132
1133    pub fn address(&self) -> &Bytes {
1134        &self.address
1135    }
1136}
1137
1138impl fmt::Display for ContractId {
1139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140        write!(f, "{:?}: 0x{}", self.chain, hex::encode(&self.address))
1141    }
1142}
1143
1144/// The version of the requested state, given as either a timestamp or a block.
1145///
1146/// If block is provided, the state at that exact block is returned. Will error if the block
1147/// has not been processed yet. If timestamp is provided, the state at the latest block before
1148/// that timestamp is returned.
1149/// Defaults to the current time.
1150#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema, Eq, Hash)]
1151#[serde(deny_unknown_fields)]
1152pub struct VersionParam {
1153    pub timestamp: Option<NaiveDateTime>,
1154    pub block: Option<BlockParam>,
1155}
1156
1157impl DeepSizeOf for VersionParam {
1158    fn deep_size_of_children(&self, context: &mut Context) -> usize {
1159        if let Some(block) = &self.block {
1160            return block.deep_size_of_children(context);
1161        }
1162
1163        0
1164    }
1165}
1166
1167impl VersionParam {
1168    pub fn new(timestamp: Option<NaiveDateTime>, block: Option<BlockParam>) -> Self {
1169        Self { timestamp, block }
1170    }
1171
1172    pub fn at_block(chain: Chain, block_number: u64) -> Self {
1173        Self::new(
1174            None,
1175            Some({
1176                #[expect(
1177                    deprecated,
1178                    reason = "BlockParam is deprecated for consumers but still constructed by this crate"
1179                )]
1180                #[expect(
1181                    clippy::cast_possible_wrap,
1182                    reason = "public API; returning a Result for block numbers above i64::MAX is a breaking change"
1183                )]
1184                BlockParam { hash: None, chain: Some(chain), number: Some(block_number as i64) }
1185            }),
1186        )
1187    }
1188}
1189
1190impl Default for VersionParam {
1191    fn default() -> Self {
1192        VersionParam { timestamp: Some(Utc::now().naive_utc()), block: None }
1193    }
1194}
1195
1196#[deprecated(note = "Use StateRequestBody instead")]
1197#[derive(Serialize, Deserialize, Default, Debug, IntoParams)]
1198pub struct StateRequestParameters {
1199    /// The minimum TVL of the protocol components to return, denoted in the chain's native token.
1200    #[param(default = 0)]
1201    pub tvl_gt: Option<u64>,
1202    /// The minimum inertia of the protocol components to return.
1203    #[param(default = 0)]
1204    pub inertia_min_gt: Option<u64>,
1205    /// Whether to include ERC20 balances in the response.
1206    #[serde(default = "default_include_balances_flag")]
1207    pub include_balances: bool,
1208    #[serde(default)]
1209    pub pagination: PaginationParams,
1210}
1211
1212impl StateRequestParameters {
1213    pub fn new(include_balances: bool) -> Self {
1214        Self {
1215            tvl_gt: None,
1216            inertia_min_gt: None,
1217            include_balances,
1218            pagination: PaginationParams::default(),
1219        }
1220    }
1221
1222    pub fn to_query_string(&self) -> String {
1223        let mut parts = vec![format!("include_balances={}", self.include_balances)];
1224
1225        if let Some(tvl_gt) = self.tvl_gt {
1226            parts.push(format!("tvl_gt={tvl_gt}"));
1227        }
1228
1229        if let Some(inertia) = self.inertia_min_gt {
1230            parts.push(format!("inertia_min_gt={inertia}"));
1231        }
1232
1233        let mut res = parts.join("&");
1234        if !res.is_empty() {
1235            res = format!("?{res}");
1236        }
1237        res
1238    }
1239}
1240
1241#[derive(
1242    Serialize, Deserialize, Debug, Default, PartialEq, ToSchema, Eq, Hash, Clone, DeepSizeOf,
1243)]
1244#[serde(deny_unknown_fields)]
1245pub struct TokensRequestBody {
1246    /// Filters tokens by addresses
1247    #[serde(alias = "tokenAddresses")]
1248    #[schema(value_type=Option<Vec<String>>)]
1249    pub token_addresses: Option<Vec<Bytes>>,
1250    /// Quality is between 0-100, where:
1251    ///  - 100: Normal ERC-20 Token behavior
1252    ///  - 75: Rebasing token
1253    ///  - 50: Fee-on-transfer token
1254    ///  - 10: Token analysis failed at first detection
1255    ///  - 5: Token analysis failed multiple times (after creation)
1256    ///  - 0: Failed to extract attributes, like Decimal or Symbol
1257    #[serde(default)]
1258    pub min_quality: Option<i32>,
1259    /// Filters tokens by recent trade activity
1260    #[serde(default)]
1261    pub traded_n_days_ago: Option<u64>,
1262    /// Max page size supported is 3000
1263    #[serde(default)]
1264    pub pagination: PaginationParams,
1265    /// Filter tokens by blockchain, default 'ethereum'
1266    #[serde(default)]
1267    pub chain: Chain,
1268}
1269
1270// When INCREASING these limits, please read the warning in the macro definition.
1271impl_pagination_limits!(TokensRequestBody, compressed = 12900, uncompressed = 3000);
1272
1273/// Response from Tycho server for a tokens request.
1274#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, Eq, Hash, DeepSizeOf)]
1275pub struct TokensRequestResponse {
1276    pub tokens: Vec<ResponseToken>,
1277    pub pagination: PaginationResponse,
1278}
1279
1280impl TokensRequestResponse {
1281    pub fn new(tokens: Vec<ResponseToken>, pagination_request: &PaginationResponse) -> Self {
1282        Self { tokens, pagination: pagination_request.clone() }
1283    }
1284}
1285
1286#[derive(
1287    PartialEq, Debug, Clone, Serialize, Deserialize, Default, ToSchema, Eq, Hash, DeepSizeOf,
1288)]
1289#[serde(rename = "Token")]
1290/// Token struct for the response from Tycho server for a tokens request.
1291pub struct ResponseToken {
1292    pub chain: Chain,
1293    /// The address of this token as hex encoded string
1294    #[schema(value_type=String, example="0xc9f2e6ea1637E499406986ac50ddC92401ce1f58")]
1295    #[serde(with = "hex_bytes")]
1296    pub address: Bytes,
1297    /// A shorthand symbol for this token (not unique)
1298    #[schema(value_type=String, example="WETH")]
1299    pub symbol: String,
1300    /// The number of decimals used to represent token values
1301    pub decimals: u32,
1302    /// The tax this token charges on transfers in basis points
1303    pub tax: u64,
1304    /// Gas usage of the token, currently is always a single averaged value
1305    pub gas: Vec<Option<u64>>,
1306    /// Quality is between 0-100, where:
1307    ///  - 100: Normal ERC-20 Token behavior
1308    ///  - 75: Rebasing token
1309    ///  - 50: Fee-on-transfer token
1310    ///  - 10: Token analysis failed at first detection
1311    ///  - 5: Token analysis failed multiple times (after creation)
1312    ///  - 0: Failed to extract attributes, like Decimal or Symbol
1313    pub quality: u32,
1314}
1315
1316impl From<models::token::Token> for ResponseToken {
1317    fn from(value: models::token::Token) -> Self {
1318        Self {
1319            chain: value.chain.into(),
1320            address: value.address,
1321            symbol: value.symbol,
1322            decimals: value.decimals,
1323            tax: value.tax,
1324            gas: value.gas,
1325            quality: value.quality,
1326        }
1327    }
1328}
1329
1330#[derive(Serialize, Deserialize, Debug, Default, ToSchema, Clone, DeepSizeOf)]
1331#[serde(deny_unknown_fields)]
1332pub struct ProtocolComponentsRequestBody {
1333    /// Filters by protocol, required to correctly apply unconfirmed state from
1334    /// ReorgBuffers
1335    pub protocol_system: String,
1336    /// Filter by component ids
1337    #[schema(value_type=Option<Vec<String>>)]
1338    #[serde(alias = "componentAddresses")]
1339    pub component_ids: Option<Vec<ComponentId>>,
1340    /// The minimum TVL of the protocol components to return, denoted in the chain's
1341    /// native token.
1342    #[serde(default)]
1343    pub tvl_gt: Option<f64>,
1344    #[serde(default)]
1345    pub chain: Chain,
1346    /// Max page size supported is 500
1347    #[serde(default)]
1348    pub pagination: PaginationParams,
1349}
1350
1351// When INCREASING these limits, please read the warning in the macro definition.
1352impl_pagination_limits!(ProtocolComponentsRequestBody, compressed = 2550, uncompressed = 500);
1353
1354// Implement PartialEq where tvl is considered equal if the difference is less than 1e-6
1355impl PartialEq for ProtocolComponentsRequestBody {
1356    fn eq(&self, other: &Self) -> bool {
1357        let tvl_close_enough = match (self.tvl_gt, other.tvl_gt) {
1358            (Some(a), Some(b)) => (a - b).abs() < 1e-6,
1359            (None, None) => true,
1360            _ => false,
1361        };
1362
1363        self.protocol_system == other.protocol_system &&
1364            self.component_ids == other.component_ids &&
1365            tvl_close_enough &&
1366            self.chain == other.chain &&
1367            self.pagination == other.pagination
1368    }
1369}
1370
1371// Implement Eq without any new logic
1372impl Eq for ProtocolComponentsRequestBody {}
1373
1374impl Hash for ProtocolComponentsRequestBody {
1375    fn hash<H: Hasher>(&self, state: &mut H) {
1376        self.protocol_system.hash(state);
1377        self.component_ids.hash(state);
1378
1379        // Handle the f64 `tvl_gt` field by converting it into a hashable integer
1380        if let Some(tvl) = self.tvl_gt {
1381            // Convert f64 to bits and hash those bits
1382            tvl.to_bits().hash(state);
1383        } else {
1384            // Use a constant value to represent None
1385            state.write_u8(0);
1386        }
1387
1388        self.chain.hash(state);
1389        self.pagination.hash(state);
1390    }
1391}
1392
1393impl ProtocolComponentsRequestBody {
1394    pub fn system_filtered(system: &str, tvl_gt: Option<f64>, chain: Chain) -> Self {
1395        Self {
1396            protocol_system: system.to_string(),
1397            component_ids: None,
1398            tvl_gt,
1399            chain,
1400            pagination: Default::default(),
1401        }
1402    }
1403
1404    pub fn id_filtered(system: &str, ids: Vec<String>, chain: Chain) -> Self {
1405        Self {
1406            protocol_system: system.to_string(),
1407            component_ids: Some(ids),
1408            tvl_gt: None,
1409            chain,
1410            pagination: Default::default(),
1411        }
1412    }
1413}
1414
1415impl ProtocolComponentsRequestBody {
1416    pub fn new(
1417        protocol_system: String,
1418        component_ids: Option<Vec<String>>,
1419        tvl_gt: Option<f64>,
1420        chain: Chain,
1421        pagination: PaginationParams,
1422    ) -> Self {
1423        Self { protocol_system, component_ids, tvl_gt, chain, pagination }
1424    }
1425}
1426
1427#[deprecated(note = "Use ProtocolComponentsRequestBody instead")]
1428#[derive(Serialize, Deserialize, Default, Debug, IntoParams)]
1429pub struct ProtocolComponentRequestParameters {
1430    /// The minimum TVL of the protocol components to return, denoted in the chain's native token.
1431    #[param(default = 0)]
1432    pub tvl_gt: Option<f64>,
1433}
1434
1435impl ProtocolComponentRequestParameters {
1436    pub fn tvl_filtered(min_tvl: f64) -> Self {
1437        Self { tvl_gt: Some(min_tvl) }
1438    }
1439}
1440
1441impl ProtocolComponentRequestParameters {
1442    pub fn to_query_string(&self) -> String {
1443        if let Some(tvl_gt) = self.tvl_gt {
1444            return format!("?tvl_gt={tvl_gt}");
1445        }
1446        String::new()
1447    }
1448}
1449
1450/// Response from Tycho server for a protocol components request.
1451#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, DeepSizeOf)]
1452pub struct ProtocolComponentRequestResponse {
1453    pub protocol_components: Vec<ProtocolComponent>,
1454    pub pagination: PaginationResponse,
1455}
1456
1457impl ProtocolComponentRequestResponse {
1458    pub fn new(
1459        protocol_components: Vec<ProtocolComponent>,
1460        pagination: PaginationResponse,
1461    ) -> Self {
1462        Self { protocol_components, pagination }
1463    }
1464}
1465
1466#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema, Eq, Hash)]
1467#[serde(deny_unknown_fields)]
1468#[deprecated]
1469pub struct ProtocolId {
1470    pub id: String,
1471    pub chain: Chain,
1472}
1473
1474impl From<ProtocolId> for String {
1475    fn from(protocol_id: ProtocolId) -> Self {
1476        protocol_id.id
1477    }
1478}
1479
1480impl AsRef<str> for ProtocolId {
1481    fn as_ref(&self) -> &str {
1482        &self.id
1483    }
1484}
1485
1486/// Protocol State struct for the response from Tycho server for a protocol state request.
1487#[derive(Debug, Clone, PartialEq, Default, Deserialize, Serialize, ToSchema, DeepSizeOf)]
1488pub struct ResponseProtocolState {
1489    /// Component id this state belongs to
1490    pub component_id: String,
1491    /// Attributes of the component. If an attribute's value is a `bigint`,
1492    /// it will be encoded as a big endian signed hex string.
1493    #[schema(value_type=HashMap<String, String>)]
1494    #[serde(with = "hex_hashmap_value")]
1495    pub attributes: HashMap<String, Bytes>,
1496    /// Sum aggregated balances of the component
1497    #[schema(value_type=HashMap<String, String>)]
1498    #[serde(with = "hex_hashmap_key_value")]
1499    pub balances: HashMap<Bytes, Bytes>,
1500}
1501
1502impl From<models::protocol::ProtocolComponentState> for ResponseProtocolState {
1503    fn from(value: models::protocol::ProtocolComponentState) -> Self {
1504        Self {
1505            component_id: value.component_id,
1506            attributes: value.attributes,
1507            balances: value.balances,
1508        }
1509    }
1510}
1511
1512fn default_include_balances_flag() -> bool {
1513    true
1514}
1515
1516/// Max page size supported is 100
1517#[derive(Clone, Debug, Serialize, PartialEq, ToSchema, Default, Eq, Hash, DeepSizeOf)]
1518#[serde(deny_unknown_fields)]
1519pub struct ProtocolStateRequestBody {
1520    /// Filters response by protocol components ids
1521    #[serde(alias = "protocolIds")]
1522    pub protocol_ids: Option<Vec<String>>,
1523    /// Filters by protocol, required to correctly apply unconfirmed state from
1524    /// ReorgBuffers
1525    #[serde(alias = "protocolSystem")]
1526    pub protocol_system: String,
1527    #[serde(default)]
1528    pub chain: Chain,
1529    /// Whether to include account balances in the response. Defaults to true.
1530    #[serde(default = "default_include_balances_flag")]
1531    pub include_balances: bool,
1532    #[serde(default = "VersionParam::default")]
1533    pub version: VersionParam,
1534    #[serde(default)]
1535    pub pagination: PaginationParams,
1536}
1537
1538// When INCREASING these limits, please read the warning in the macro definition.
1539impl_pagination_limits!(ProtocolStateRequestBody, compressed = 360, uncompressed = 100);
1540
1541impl ProtocolStateRequestBody {
1542    pub fn id_filtered<I, T>(ids: I) -> Self
1543    where
1544        I: IntoIterator<Item = T>,
1545        T: Into<String>,
1546    {
1547        Self {
1548            protocol_ids: Some(
1549                ids.into_iter()
1550                    .map(Into::into)
1551                    .collect(),
1552            ),
1553            ..Default::default()
1554        }
1555    }
1556}
1557
1558/// Custom deserializer for ProtocolStateRequestBody to support backwards compatibility with the old
1559/// ProtocolIds format.
1560/// To be removed when the old format is no longer supported.
1561impl<'de> Deserialize<'de> for ProtocolStateRequestBody {
1562    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1563    where
1564        D: Deserializer<'de>,
1565    {
1566        #[derive(Deserialize)]
1567        #[serde(untagged)]
1568        enum ProtocolIdOrString {
1569            Old(Vec<ProtocolId>),
1570            New(Vec<String>),
1571        }
1572
1573        struct ProtocolStateRequestBodyVisitor;
1574
1575        impl<'de> de::Visitor<'de> for ProtocolStateRequestBodyVisitor {
1576            type Value = ProtocolStateRequestBody;
1577
1578            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1579                formatter.write_str("struct ProtocolStateRequestBody")
1580            }
1581
1582            fn visit_map<V>(self, mut map: V) -> Result<ProtocolStateRequestBody, V::Error>
1583            where
1584                V: de::MapAccess<'de>,
1585            {
1586                let mut protocol_ids = None;
1587                let mut protocol_system = None;
1588                let mut version = None;
1589                let mut chain = None;
1590                let mut include_balances = None;
1591                let mut pagination = None;
1592
1593                while let Some(key) = map.next_key::<String>()? {
1594                    match key.as_str() {
1595                        "protocol_ids" | "protocolIds" => {
1596                            let value: ProtocolIdOrString = map.next_value()?;
1597                            protocol_ids = match value {
1598                                ProtocolIdOrString::Old(ids) => {
1599                                    Some(ids.into_iter().map(|p| p.id).collect())
1600                                }
1601                                ProtocolIdOrString::New(ids_str) => Some(ids_str),
1602                            };
1603                        }
1604                        "protocol_system" | "protocolSystem" => {
1605                            protocol_system = Some(map.next_value()?);
1606                        }
1607                        "version" => {
1608                            version = Some(map.next_value()?);
1609                        }
1610                        "chain" => {
1611                            chain = Some(map.next_value()?);
1612                        }
1613                        "include_balances" => {
1614                            include_balances = Some(map.next_value()?);
1615                        }
1616                        "pagination" => {
1617                            pagination = Some(map.next_value()?);
1618                        }
1619                        _ => {
1620                            return Err(de::Error::unknown_field(
1621                                &key,
1622                                &[
1623                                    "contract_ids",
1624                                    "protocol_system",
1625                                    "version",
1626                                    "chain",
1627                                    "include_balances",
1628                                    "pagination",
1629                                ],
1630                            ))
1631                        }
1632                    }
1633                }
1634
1635                Ok(ProtocolStateRequestBody {
1636                    protocol_ids,
1637                    protocol_system: protocol_system.unwrap_or_default(),
1638                    version: version.unwrap_or_else(VersionParam::default),
1639                    chain: chain.unwrap_or_else(Chain::default),
1640                    include_balances: include_balances.unwrap_or(true),
1641                    pagination: pagination.unwrap_or_else(PaginationParams::default),
1642                })
1643            }
1644        }
1645
1646        deserializer.deserialize_struct(
1647            "ProtocolStateRequestBody",
1648            &[
1649                "contract_ids",
1650                "protocol_system",
1651                "version",
1652                "chain",
1653                "include_balances",
1654                "pagination",
1655            ],
1656            ProtocolStateRequestBodyVisitor,
1657        )
1658    }
1659}
1660
1661#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, DeepSizeOf)]
1662pub struct ProtocolStateRequestResponse {
1663    pub states: Vec<ResponseProtocolState>,
1664    pub pagination: PaginationResponse,
1665}
1666
1667impl ProtocolStateRequestResponse {
1668    pub fn new(states: Vec<ResponseProtocolState>, pagination: PaginationResponse) -> Self {
1669        Self { states, pagination }
1670    }
1671}
1672
1673#[derive(Serialize, Clone, PartialEq, Hash, Eq)]
1674pub struct ProtocolComponentId {
1675    pub chain: Chain,
1676    pub system: String,
1677    pub id: String,
1678}
1679
1680#[derive(Debug, Serialize, ToSchema)]
1681#[serde(tag = "status", content = "message")]
1682#[schema(example = json!({"status": "NotReady", "message": "No db connection"}))]
1683pub enum Health {
1684    Ready,
1685    Starting(String),
1686    NotReady(String),
1687}
1688
1689#[derive(Serialize, Deserialize, Debug, Default, PartialEq, ToSchema, Eq, Hash, Clone)]
1690#[serde(deny_unknown_fields)]
1691pub struct ProtocolSystemsRequestBody {
1692    #[serde(default)]
1693    pub chain: Chain,
1694    #[serde(default)]
1695    pub pagination: PaginationParams,
1696}
1697
1698// When INCREASING these limits, please read the warning in the macro definition.
1699impl_pagination_limits!(ProtocolSystemsRequestBody, compressed = 100, uncompressed = 100);
1700
1701#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, Eq, Hash)]
1702pub struct ProtocolSystemsRequestResponse {
1703    /// List of currently supported protocol systems
1704    pub protocol_systems: Vec<String>,
1705    /// Protocol systems that use Dynamic Contract Indexing (DCI).
1706    /// Clients should only fetch entrypoints for these protocols.
1707    #[serde(default)]
1708    pub dci_protocols: Vec<String>,
1709    pub pagination: PaginationResponse,
1710}
1711
1712impl ProtocolSystemsRequestResponse {
1713    pub fn new(
1714        protocol_systems: Vec<String>,
1715        dci_protocols: Vec<String>,
1716        pagination: PaginationResponse,
1717    ) -> Self {
1718        Self { protocol_systems, dci_protocols, pagination }
1719    }
1720}
1721
1722#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
1723pub struct DCIUpdate {
1724    /// Map of component id to the new entrypoints associated with the component
1725    pub new_entrypoints: HashMap<ComponentId, HashSet<EntryPoint>>,
1726    /// Map of entrypoint id to the new entrypoint params associtated with it (and optionally the
1727    /// component linked to those params)
1728    pub new_entrypoint_params: HashMap<String, HashSet<(TracingParams, String)>>,
1729    /// Map of entrypoint id to its trace result
1730    pub trace_results: HashMap<String, TracingResult>,
1731}
1732
1733impl From<models::blockchain::DCIUpdate> for DCIUpdate {
1734    fn from(value: models::blockchain::DCIUpdate) -> Self {
1735        Self {
1736            new_entrypoints: value
1737                .new_entrypoints
1738                .into_iter()
1739                .map(|(k, v)| {
1740                    (
1741                        k,
1742                        v.into_iter()
1743                            .map(|v| v.into())
1744                            .collect(),
1745                    )
1746                })
1747                .collect(),
1748            new_entrypoint_params: value
1749                .new_entrypoint_params
1750                .into_iter()
1751                .map(|(k, v)| {
1752                    (
1753                        k,
1754                        v.into_iter()
1755                            .map(|(params, i)| (params.into(), i))
1756                            .collect(),
1757                    )
1758                })
1759                .collect(),
1760            trace_results: value
1761                .trace_results
1762                .into_iter()
1763                .map(|(k, v)| (k, v.into()))
1764                .collect(),
1765        }
1766    }
1767}
1768
1769#[derive(Serialize, Deserialize, Debug, Default, PartialEq, ToSchema, Eq, Hash, Clone)]
1770#[serde(deny_unknown_fields)]
1771pub struct ComponentTvlRequestBody {
1772    #[serde(default)]
1773    pub chain: Chain,
1774    /// Filters protocol components by protocol system
1775    /// Useful when `component_ids` is omitted to fetch all components under a specific system.
1776    #[serde(alias = "protocolSystem")]
1777    pub protocol_system: Option<String>,
1778    #[serde(default)]
1779    pub component_ids: Option<Vec<String>>,
1780    #[serde(default)]
1781    pub pagination: PaginationParams,
1782}
1783
1784// When INCREASING these limits, please read the warning in the macro definition.
1785impl_pagination_limits!(ComponentTvlRequestBody, compressed = 100, uncompressed = 100);
1786
1787impl ComponentTvlRequestBody {
1788    pub fn system_filtered(system: &str, chain: Chain) -> Self {
1789        Self {
1790            chain,
1791            protocol_system: Some(system.to_string()),
1792            component_ids: None,
1793            pagination: Default::default(),
1794        }
1795    }
1796
1797    pub fn id_filtered(ids: Vec<String>, chain: Chain) -> Self {
1798        Self {
1799            chain,
1800            protocol_system: None,
1801            component_ids: Some(ids),
1802            pagination: Default::default(),
1803        }
1804    }
1805}
1806// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema, Eq, Hash)]
1807#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ToSchema)]
1808pub struct ComponentTvlRequestResponse {
1809    pub tvl: HashMap<String, f64>,
1810    pub pagination: PaginationResponse,
1811}
1812
1813impl ComponentTvlRequestResponse {
1814    pub fn new(tvl: HashMap<String, f64>, pagination: PaginationResponse) -> Self {
1815        Self { tvl, pagination }
1816    }
1817}
1818
1819#[derive(
1820    Serialize, Deserialize, Debug, Default, PartialEq, ToSchema, Eq, Hash, Clone, DeepSizeOf,
1821)]
1822pub struct TracedEntryPointRequestBody {
1823    #[serde(default)]
1824    pub chain: Chain,
1825    /// Filters by protocol, required to correctly apply unconfirmed state from
1826    /// ReorgBuffers
1827    pub protocol_system: String,
1828    /// Filter by component ids
1829    #[schema(value_type = Option<Vec<String>>)]
1830    pub component_ids: Option<Vec<ComponentId>>,
1831    /// Max page size supported is 100
1832    #[serde(default)]
1833    pub pagination: PaginationParams,
1834}
1835
1836// When INCREASING these limits, please read the warning in the macro definition.
1837impl_pagination_limits!(TracedEntryPointRequestBody, compressed = 100, uncompressed = 100);
1838
1839#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema, Eq, Hash, DeepSizeOf)]
1840pub struct EntryPoint {
1841    #[schema(example = "0xEdf63cce4bA70cbE74064b7687882E71ebB0e988:getRate()")]
1842    /// Entry point id.
1843    pub external_id: String,
1844    #[schema(value_type=String, example="0x8f4E8439b970363648421C692dd897Fb9c0Bd1D9")]
1845    #[serde(with = "hex_bytes")]
1846    /// The address of the contract to trace.
1847    pub target: Bytes,
1848    #[schema(example = "getRate()")]
1849    /// The signature of the function to trace.
1850    pub signature: String,
1851}
1852
1853#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema, Eq, Hash, DeepSizeOf)]
1854pub enum StorageOverride {
1855    /// Applies changes incrementally to the existing account storage.
1856    /// Only modifies the specific storage slots provided in the map while
1857    /// preserving all other storage slots.
1858    #[schema(value_type=HashMap<String, String>)]
1859    Diff(BTreeMap<StoreKey, StoreVal>),
1860
1861    /// Completely replaces the account's storage state.
1862    /// Only the storage slots provided in the map will exist after the operation,
1863    /// and any existing storage slots not included will be cleared/zeroed.
1864    #[schema(value_type=HashMap<String, String>)]
1865    Replace(BTreeMap<StoreKey, StoreVal>),
1866}
1867
1868impl From<models::blockchain::StorageOverride> for StorageOverride {
1869    fn from(value: models::blockchain::StorageOverride) -> Self {
1870        match value {
1871            models::blockchain::StorageOverride::Diff(diff) => StorageOverride::Diff(diff),
1872            models::blockchain::StorageOverride::Replace(replace) => {
1873                StorageOverride::Replace(replace)
1874            }
1875        }
1876    }
1877}
1878
1879/// State overrides for an account.
1880///
1881/// Used to modify account state. Commonly used for testing contract interactions with specific
1882/// state conditions or simulating transactions with modified balances/code.
1883#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema, Eq, Hash, DeepSizeOf)]
1884pub struct AccountOverrides {
1885    /// Storage slots to override
1886    pub slots: Option<StorageOverride>,
1887    #[schema(value_type=Option<String>)]
1888    /// Native token balance override
1889    pub native_balance: Option<Balance>,
1890    #[schema(value_type=Option<String>)]
1891    /// Contract code override
1892    pub code: Option<Code>,
1893}
1894
1895impl From<models::blockchain::AccountOverrides> for AccountOverrides {
1896    fn from(value: models::blockchain::AccountOverrides) -> Self {
1897        AccountOverrides {
1898            slots: value.slots.map(|s| s.into()),
1899            native_balance: value.native_balance,
1900            code: value.code,
1901        }
1902    }
1903}
1904
1905#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema, Eq, Hash, DeepSizeOf)]
1906pub struct RPCTracerParams {
1907    /// The caller address of the transaction, if not provided tracing uses the default value
1908    /// for an address defined by the VM.
1909    #[schema(value_type=Option<String>)]
1910    #[serde(with = "hex_bytes_option", default)]
1911    pub caller: Option<Bytes>,
1912    /// The call data used for the tracing call, this needs to include the function selector
1913    #[schema(value_type=String, example="0x679aefce")]
1914    #[serde(with = "hex_bytes")]
1915    pub calldata: Bytes,
1916    /// Optionally allow for state overrides so that the call works as expected
1917    pub state_overrides: Option<BTreeMap<Address, AccountOverrides>>,
1918    /// Addresses to prune from trace results. Useful for hooks that use mock
1919    /// accounts/routers that shouldn't be tracked in the final DCI results.
1920    #[schema(value_type=Option<Vec<String>>)]
1921    #[serde(default)]
1922    pub prune_addresses: Option<Vec<Address>>,
1923}
1924
1925impl From<models::blockchain::RPCTracerParams> for RPCTracerParams {
1926    fn from(value: models::blockchain::RPCTracerParams) -> Self {
1927        RPCTracerParams {
1928            caller: value.caller,
1929            calldata: value.calldata,
1930            state_overrides: value.state_overrides.map(|overrides| {
1931                overrides
1932                    .into_iter()
1933                    .map(|(address, account_overrides)| (address, account_overrides.into()))
1934                    .collect()
1935            }),
1936            prune_addresses: value.prune_addresses,
1937        }
1938    }
1939}
1940
1941#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone, Hash, DeepSizeOf, ToSchema)]
1942#[serde(tag = "method", rename_all = "lowercase")]
1943pub enum TracingParams {
1944    /// Uses RPC calls to retrieve the called addresses and retriggers
1945    RPCTracer(RPCTracerParams),
1946}
1947
1948impl From<models::blockchain::TracingParams> for TracingParams {
1949    fn from(value: models::blockchain::TracingParams) -> Self {
1950        match value {
1951            models::blockchain::TracingParams::RPCTracer(params) => {
1952                TracingParams::RPCTracer(params.into())
1953            }
1954        }
1955    }
1956}
1957
1958impl From<models::blockchain::EntryPoint> for EntryPoint {
1959    fn from(value: models::blockchain::EntryPoint) -> Self {
1960        Self { external_id: value.external_id, target: value.target, signature: value.signature }
1961    }
1962}
1963
1964#[derive(Serialize, Deserialize, Debug, PartialEq, ToSchema, Eq, Clone, DeepSizeOf)]
1965pub struct EntryPointWithTracingParams {
1966    /// The entry point object
1967    pub entry_point: EntryPoint,
1968    /// The parameters used
1969    pub params: TracingParams,
1970}
1971
1972impl From<models::blockchain::EntryPointWithTracingParams> for EntryPointWithTracingParams {
1973    fn from(value: models::blockchain::EntryPointWithTracingParams) -> Self {
1974        Self { entry_point: value.entry_point.into(), params: value.params.into() }
1975    }
1976}
1977
1978#[derive(
1979    Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize, DeepSizeOf,
1980)]
1981pub struct AddressStorageLocation {
1982    pub key: StoreKey,
1983    pub offset: u8,
1984}
1985
1986impl AddressStorageLocation {
1987    pub fn new(key: StoreKey, offset: u8) -> Self {
1988        Self { key, offset }
1989    }
1990}
1991
1992impl From<models::blockchain::AddressStorageLocation> for AddressStorageLocation {
1993    fn from(value: models::blockchain::AddressStorageLocation) -> Self {
1994        Self { key: value.key, offset: value.offset }
1995    }
1996}
1997
1998fn deserialize_retriggers_from_value(
1999    value: &serde_json::Value,
2000) -> Result<HashSet<(StoreKey, AddressStorageLocation)>, String> {
2001    use serde::Deserialize;
2002    use serde_json::Value;
2003
2004    let mut result = HashSet::new();
2005
2006    if let Value::Array(items) = value {
2007        for item in items {
2008            if let Value::Array(pair) = item {
2009                if pair.len() == 2 {
2010                    let key = StoreKey::deserialize(&pair[0])
2011                        .map_err(|e| format!("Failed to deserialize key: {}", e))?;
2012
2013                    // Handle both old format (string) and new format (AddressStorageLocation)
2014                    let addr_storage = match &pair[1] {
2015                        Value::String(_) => {
2016                            // Old format: just a string key with offset defaulted to 0
2017                            let storage_key = StoreKey::deserialize(&pair[1]).map_err(|e| {
2018                                format!("Failed to deserialize old format storage key: {}", e)
2019                            })?;
2020                            AddressStorageLocation::new(storage_key, 12)
2021                        }
2022                        Value::Object(_) => {
2023                            // New format: AddressStorageLocation struct
2024                            AddressStorageLocation::deserialize(&pair[1]).map_err(|e| {
2025                                format!("Failed to deserialize AddressStorageLocation: {}", e)
2026                            })?
2027                        }
2028                        Value::Null | Value::Bool(_) | Value::Number(_) | Value::Array(_) => {
2029                            return Err("Invalid retrigger format".to_string())
2030                        }
2031                    };
2032
2033                    result.insert((key, addr_storage));
2034                }
2035            }
2036        }
2037    }
2038
2039    Ok(result)
2040}
2041
2042#[derive(Serialize, Debug, Default, PartialEq, ToSchema, Eq, Clone, DeepSizeOf)]
2043pub struct TracingResult {
2044    #[schema(value_type=HashSet<(String, String)>)]
2045    pub retriggers: HashSet<(StoreKey, AddressStorageLocation)>,
2046    #[schema(value_type=HashMap<String,HashSet<String>>)]
2047    pub accessed_slots: HashMap<Address, HashSet<StoreKey>>,
2048}
2049
2050/// Deserialize TracingResult with backward compatibility for retriggers
2051/// TODO: remove this after offset detection is deployed in production
2052impl<'de> Deserialize<'de> for TracingResult {
2053    fn deserialize<D>(deserializer: D) -> Result<TracingResult, D::Error>
2054    where
2055        D: Deserializer<'de>,
2056    {
2057        use serde::de::Error;
2058        use serde_json::Value;
2059
2060        let value = Value::deserialize(deserializer)?;
2061        let mut result = TracingResult::default();
2062
2063        if let Value::Object(map) = value {
2064            // Deserialize retriggers using our custom deserializer
2065            if let Some(retriggers_value) = map.get("retriggers") {
2066                result.retriggers =
2067                    deserialize_retriggers_from_value(retriggers_value).map_err(|e| {
2068                        D::Error::custom(format!("Failed to deserialize retriggers: {}", e))
2069                    })?;
2070            }
2071
2072            // Deserialize accessed_slots normally
2073            if let Some(accessed_slots_value) = map.get("accessed_slots") {
2074                result.accessed_slots = serde_json::from_value(accessed_slots_value.clone())
2075                    .map_err(|e| {
2076                        D::Error::custom(format!("Failed to deserialize accessed_slots: {}", e))
2077                    })?;
2078            }
2079        }
2080
2081        Ok(result)
2082    }
2083}
2084
2085impl From<models::blockchain::TracingResult> for TracingResult {
2086    fn from(value: models::blockchain::TracingResult) -> Self {
2087        TracingResult {
2088            retriggers: value
2089                .retriggers
2090                .into_iter()
2091                .map(|(k, v)| (k, v.into()))
2092                .collect(),
2093            accessed_slots: value.accessed_slots,
2094        }
2095    }
2096}
2097
2098#[derive(Serialize, PartialEq, ToSchema, Eq, Clone, Debug, Deserialize, DeepSizeOf)]
2099pub struct TracedEntryPointRequestResponse {
2100    /// Map of protocol component id to a list of a tuple containing each entry point with its
2101    /// tracing parameters and its corresponding tracing results.
2102    #[schema(value_type = HashMap<String, Vec<(EntryPointWithTracingParams, TracingResult)>>)]
2103    pub traced_entry_points:
2104        HashMap<ComponentId, Vec<(EntryPointWithTracingParams, TracingResult)>>,
2105    pub pagination: PaginationResponse,
2106}
2107
2108#[derive(Serialize, Deserialize, Debug, Default, PartialEq, ToSchema, Eq, Clone)]
2109pub struct AddEntryPointRequestBody {
2110    #[serde(default)]
2111    pub chain: Chain,
2112    #[schema(value_type=String)]
2113    #[serde(default)]
2114    pub block_hash: Bytes,
2115    /// The map of component ids to their tracing params to insert
2116    #[schema(value_type = Vec<(String, Vec<EntryPointWithTracingParams>)>)]
2117    pub entry_points_with_tracing_data: Vec<(ComponentId, Vec<EntryPointWithTracingParams>)>,
2118}
2119
2120#[derive(Serialize, PartialEq, ToSchema, Eq, Clone, Debug, Deserialize)]
2121pub struct AddEntryPointRequestResponse {
2122    /// Map of protocol component id to a list of a tuple containing each entry point with its
2123    /// tracing parameters and its corresponding tracing results.
2124    #[schema(value_type = HashMap<String, Vec<(EntryPointWithTracingParams, TracingResult)>>)]
2125    pub traced_entry_points:
2126        HashMap<ComponentId, Vec<(EntryPointWithTracingParams, TracingResult)>>,
2127}
2128
2129#[cfg(test)]
2130mod test {
2131    use std::str::FromStr;
2132
2133    use maplit::hashmap;
2134    use rstest::rstest;
2135
2136    use super::*;
2137
2138    /// Test backward compatibility for Command::Subscribe compression field.
2139    /// Should default to false when not specified.
2140    #[rstest]
2141    #[case::legacy_format(None, false)]
2142    #[case::explicit_true(Some(true), true)]
2143    #[case::explicit_false(Some(false), false)]
2144    fn test_subscribe_compression_backward_compatibility(
2145        #[case] compression: Option<bool>,
2146        #[case] expected: bool,
2147    ) {
2148        use serde_json::json;
2149
2150        let mut json_value = json!({
2151            "method": "subscribe",
2152            "extractor_id": {
2153                "chain": "ethereum",
2154                "name": "test"
2155            },
2156            "include_state": true
2157        });
2158
2159        if let Some(value) = compression {
2160            json_value["compression"] = json!(value);
2161        }
2162
2163        let command: Command =
2164            serde_json::from_value(json_value).expect("Failed to deserialize Subscribe command");
2165
2166        if let Command::Subscribe { compression, .. } = command {
2167            assert_eq!(compression, expected);
2168        } else {
2169            panic!("Expected Subscribe command");
2170        }
2171    }
2172
2173    /// Test backward compatibility for Command::Subscribe partial_blocks field.
2174    /// Should default to false when not specified.
2175    #[rstest]
2176    #[case::legacy_format(None, false)]
2177    #[case::explicit_true(Some(true), true)]
2178    #[case::explicit_false(Some(false), false)]
2179    fn test_subscribe_partial_blocks_backward_compatibility(
2180        #[case] partial_blocks: Option<bool>,
2181        #[case] expected: bool,
2182    ) {
2183        use serde_json::json;
2184
2185        let mut json_value = json!({
2186            "method": "subscribe",
2187            "extractor_id": {
2188                "chain": "ethereum",
2189                "name": "test"
2190            },
2191            "include_state": true
2192        });
2193
2194        if let Some(value) = partial_blocks {
2195            json_value["partial_blocks"] = json!(value);
2196        }
2197
2198        let command: Command =
2199            serde_json::from_value(json_value).expect("Failed to deserialize Subscribe command");
2200
2201        if let Command::Subscribe { partial_blocks, .. } = command {
2202            assert_eq!(partial_blocks, expected);
2203        } else {
2204            panic!("Expected Subscribe command");
2205        }
2206    }
2207
2208    /// Test backward compatibility for ProtocolSystemsRequestResponse dci_protocols field.
2209    /// Should default to empty vec when not specified (old server responses).
2210    #[rstest]
2211    #[case::legacy_format(None, vec![])]
2212    #[case::with_dci(Some(vec!["vm:curve"]), vec!["vm:curve"])]
2213    #[case::empty_dci(Some(vec![]), vec![])]
2214    fn test_protocol_systems_dci_backward_compatibility(
2215        #[case] dci_protocols: Option<Vec<&str>>,
2216        #[case] expected: Vec<&str>,
2217    ) {
2218        use serde_json::json;
2219
2220        let mut json_value = json!({
2221            "protocol_systems": ["uniswap_v2", "vm:curve"],
2222            "pagination": { "page": 0, "page_size": 20, "total": 2 }
2223        });
2224
2225        if let Some(dci) = dci_protocols {
2226            json_value["dci_protocols"] = json!(dci);
2227        }
2228
2229        let resp: ProtocolSystemsRequestResponse =
2230            serde_json::from_value(json_value).expect("Failed to deserialize response");
2231
2232        assert_eq!(resp.dci_protocols, expected);
2233
2234        // Verify round-trip
2235        let serialized = serde_json::to_string(&resp).unwrap();
2236        let round_tripped: ProtocolSystemsRequestResponse =
2237            serde_json::from_str(&serialized).unwrap();
2238        assert_eq!(resp, round_tripped);
2239    }
2240
2241    #[test]
2242    fn test_tracing_result_backward_compatibility() {
2243        use serde_json::json;
2244
2245        // Test old format (string storage locations)
2246        let old_format_json = json!({
2247            "retriggers": [
2248                ["0x01", "0x02"],
2249                ["0x03", "0x04"]
2250            ],
2251            "accessed_slots": {
2252                "0x05": ["0x06", "0x07"]
2253            }
2254        });
2255
2256        let result: TracingResult = serde_json::from_value(old_format_json).unwrap();
2257
2258        // Check that retriggers were deserialized correctly with offset 0
2259        assert_eq!(result.retriggers.len(), 2);
2260        let retriggers_vec: Vec<_> = result.retriggers.iter().collect();
2261        assert!(retriggers_vec.iter().any(|(k, v)| {
2262            k == &Bytes::from("0x01") && v.key == Bytes::from("0x02") && v.offset == 12
2263        }));
2264        assert!(retriggers_vec.iter().any(|(k, v)| {
2265            k == &Bytes::from("0x03") && v.key == Bytes::from("0x04") && v.offset == 12
2266        }));
2267
2268        // Test new format (AddressStorageLocation objects)
2269        let new_format_json = json!({
2270            "retriggers": [
2271                ["0x01", {"key": "0x02", "offset": 12}],
2272                ["0x03", {"key": "0x04", "offset": 5}]
2273            ],
2274            "accessed_slots": {
2275                "0x05": ["0x06", "0x07"]
2276            }
2277        });
2278
2279        let result2: TracingResult = serde_json::from_value(new_format_json).unwrap();
2280
2281        // Check that new format retriggers were deserialized correctly with proper offsets
2282        assert_eq!(result2.retriggers.len(), 2);
2283        let retriggers_vec2: Vec<_> = result2.retriggers.iter().collect();
2284        assert!(retriggers_vec2.iter().any(|(k, v)| {
2285            k == &Bytes::from("0x01") && v.key == Bytes::from("0x02") && v.offset == 12
2286        }));
2287        assert!(retriggers_vec2.iter().any(|(k, v)| {
2288            k == &Bytes::from("0x03") && v.key == Bytes::from("0x04") && v.offset == 5
2289        }));
2290    }
2291
2292    #[rstest]
2293    #[case::legacy_format(None, None)]
2294    #[case::full_block(Some(serde_json::Value::Null), None)]
2295    #[case::partial_block(Some(serde_json::json!(1)), Some(1))]
2296    fn test_block_changes_is_partial_backward_compatibility(
2297        #[case] has_partial_value: Option<serde_json::Value>,
2298        #[case] expected: Option<u32>,
2299    ) {
2300        use serde_json::json;
2301
2302        let mut json_value = json!({
2303            "extractor": "test_extractor",
2304            "chain": "ethereum",
2305            "block": {
2306                "number": 100,
2307                "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2308                "parent_hash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
2309                "chain": "ethereum",
2310                "ts": "2024-01-01T00:00:00"
2311            },
2312            "finalized_block_height": 99,
2313            "revert": false,
2314            "new_tokens": {},
2315            "account_updates": {},
2316            "state_updates": {},
2317            "new_protocol_components": {},
2318            "deleted_protocol_components": {},
2319            "component_balances": {},
2320            "account_balances": {},
2321            "component_tvl": {},
2322            "dci_update": {
2323                "new_entrypoints": {},
2324                "new_entrypoint_params": {},
2325                "trace_results": {}
2326            }
2327        });
2328
2329        // Add is_partial field only if specified
2330        if let Some(partial_value) = has_partial_value {
2331            json_value["partial_block_index"] = partial_value;
2332        }
2333
2334        let block_changes: BlockAggregatedChanges = serde_json::from_value(json_value)
2335            .expect("Failed to deserialize BlockAggregatedChanges");
2336
2337        assert_eq!(block_changes.partial_block_index, expected);
2338    }
2339
2340    #[test]
2341    fn test_protocol_components_equality() {
2342        let body1 = ProtocolComponentsRequestBody {
2343            protocol_system: "protocol1".to_string(),
2344            component_ids: Some(vec!["component1".to_string(), "component2".to_string()]),
2345            tvl_gt: Some(1000.0),
2346            chain: Chain::Ethereum,
2347            pagination: PaginationParams::default(),
2348        };
2349
2350        let body2 = ProtocolComponentsRequestBody {
2351            protocol_system: "protocol1".to_string(),
2352            component_ids: Some(vec!["component1".to_string(), "component2".to_string()]),
2353            tvl_gt: Some(1000.0 + 1e-7), // Within the tolerance ±1e-6
2354            chain: Chain::Ethereum,
2355            pagination: PaginationParams::default(),
2356        };
2357
2358        // These should be considered equal due to the tolerance in tvl_gt
2359        assert_eq!(body1, body2);
2360    }
2361
2362    #[test]
2363    fn test_protocol_components_inequality() {
2364        let body1 = ProtocolComponentsRequestBody {
2365            protocol_system: "protocol1".to_string(),
2366            component_ids: Some(vec!["component1".to_string(), "component2".to_string()]),
2367            tvl_gt: Some(1000.0),
2368            chain: Chain::Ethereum,
2369            pagination: PaginationParams::default(),
2370        };
2371
2372        let body2 = ProtocolComponentsRequestBody {
2373            protocol_system: "protocol1".to_string(),
2374            component_ids: Some(vec!["component1".to_string(), "component2".to_string()]),
2375            tvl_gt: Some(1000.0 + 1e-5), // Outside the tolerance ±1e-6
2376            chain: Chain::Ethereum,
2377            pagination: PaginationParams::default(),
2378        };
2379
2380        // These should not be equal due to the difference in tvl_gt
2381        assert_ne!(body1, body2);
2382    }
2383
2384    #[test]
2385    fn test_parse_state_request() {
2386        let json_str = r#"
2387    {
2388        "contractIds": [
2389            "0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092"
2390        ],
2391        "protocol_system": "uniswap_v2",
2392        "version": {
2393            "timestamp": "2069-01-01T04:20:00",
2394            "block": {
2395                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2396                "number": 213,
2397                "chain": "ethereum"
2398            }
2399        }
2400    }
2401    "#;
2402
2403        let result: StateRequestBody = serde_json::from_str(json_str).unwrap();
2404
2405        let contract0 = "b4eccE46b8D4e4abFd03C9B806276A6735C9c092"
2406            .parse()
2407            .unwrap();
2408        let block_hash = "24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4"
2409            .parse()
2410            .unwrap();
2411        let block_number = 213;
2412
2413        let expected_timestamp =
2414            NaiveDateTime::parse_from_str("2069-01-01T04:20:00", "%Y-%m-%dT%H:%M:%S").unwrap();
2415
2416        let expected = StateRequestBody {
2417            contract_ids: Some(vec![contract0]),
2418            protocol_system: "uniswap_v2".to_string(),
2419            version: VersionParam {
2420                timestamp: Some(expected_timestamp),
2421                block: Some(BlockParam {
2422                    hash: Some(block_hash),
2423                    chain: Some(Chain::Ethereum),
2424                    number: Some(block_number),
2425                }),
2426            },
2427            chain: Chain::Ethereum,
2428            pagination: PaginationParams::default(),
2429        };
2430
2431        assert_eq!(result, expected);
2432    }
2433
2434    #[test]
2435    fn test_parse_state_request_dual_interface() {
2436        let json_common = r#"
2437    {
2438        "__CONTRACT_IDS__": [
2439            "0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092"
2440        ],
2441        "version": {
2442            "timestamp": "2069-01-01T04:20:00",
2443            "block": {
2444                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2445                "number": 213,
2446                "chain": "ethereum"
2447            }
2448        }
2449    }
2450    "#;
2451
2452        let json_str_snake = json_common.replace("\"__CONTRACT_IDS__\"", "\"contract_ids\"");
2453        let json_str_camel = json_common.replace("\"__CONTRACT_IDS__\"", "\"contractIds\"");
2454
2455        let snake: StateRequestBody = serde_json::from_str(&json_str_snake).unwrap();
2456        let camel: StateRequestBody = serde_json::from_str(&json_str_camel).unwrap();
2457
2458        assert_eq!(snake, camel);
2459    }
2460
2461    #[test]
2462    fn test_parse_state_request_unknown_field() {
2463        let body = r#"
2464    {
2465        "contract_ids_with_typo_error": [
2466            {
2467                "address": "0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092",
2468                "chain": "ethereum"
2469            }
2470        ],
2471        "version": {
2472            "timestamp": "2069-01-01T04:20:00",
2473            "block": {
2474                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2475                "parentHash": "0x8d75152454e60413efe758cc424bfd339897062d7e658f302765eb7b50971815",
2476                "number": 213,
2477                "chain": "ethereum"
2478            }
2479        }
2480    }
2481    "#;
2482
2483        let decoded = serde_json::from_str::<StateRequestBody>(body);
2484
2485        assert!(decoded.is_err(), "Expected an error due to unknown field");
2486
2487        if let Err(e) = decoded {
2488            assert!(
2489                e.to_string()
2490                    .contains("unknown field `contract_ids_with_typo_error`"),
2491                "Error message does not contain expected unknown field information"
2492            );
2493        }
2494    }
2495
2496    #[test]
2497    fn test_parse_state_request_no_contract_specified() {
2498        let json_str = r#"
2499    {
2500        "protocol_system": "uniswap_v2",
2501        "version": {
2502            "timestamp": "2069-01-01T04:20:00",
2503            "block": {
2504                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2505                "number": 213,
2506                "chain": "ethereum"
2507            }
2508        }
2509    }
2510    "#;
2511
2512        let result: StateRequestBody = serde_json::from_str(json_str).unwrap();
2513
2514        let block_hash = "24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4".into();
2515        let block_number = 213;
2516        let expected_timestamp =
2517            NaiveDateTime::parse_from_str("2069-01-01T04:20:00", "%Y-%m-%dT%H:%M:%S").unwrap();
2518
2519        let expected = StateRequestBody {
2520            contract_ids: None,
2521            protocol_system: "uniswap_v2".to_string(),
2522            version: VersionParam {
2523                timestamp: Some(expected_timestamp),
2524                block: Some(BlockParam {
2525                    hash: Some(block_hash),
2526                    chain: Some(Chain::Ethereum),
2527                    number: Some(block_number),
2528                }),
2529            },
2530            chain: Chain::Ethereum,
2531            pagination: PaginationParams { page: 0, page_size: 100 },
2532        };
2533
2534        assert_eq!(result, expected);
2535    }
2536
2537    #[rstest]
2538    #[case::deprecated_ids(
2539        r#"
2540    {
2541        "protocol_ids": [
2542            {
2543                "id": "0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092",
2544                "chain": "ethereum"
2545            }
2546        ],
2547        "protocol_system": "uniswap_v2",
2548        "include_balances": false,
2549        "version": {
2550            "timestamp": "2069-01-01T04:20:00",
2551            "block": {
2552                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2553                "number": 213,
2554                "chain": "ethereum"
2555            }
2556        }
2557    }
2558    "#
2559    )]
2560    #[case(
2561        r#"
2562    {
2563        "protocolIds": [
2564            "0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092"
2565        ],
2566        "protocol_system": "uniswap_v2",
2567        "include_balances": false,
2568        "version": {
2569            "timestamp": "2069-01-01T04:20:00",
2570            "block": {
2571                "hash": "0x24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4",
2572                "number": 213,
2573                "chain": "ethereum"
2574            }
2575        }
2576    }
2577    "#
2578    )]
2579    fn test_parse_protocol_state_request(#[case] json_str: &str) {
2580        let result: ProtocolStateRequestBody = serde_json::from_str(json_str).unwrap();
2581
2582        let block_hash = "24101f9cb26cd09425b52da10e8c2f56ede94089a8bbe0f31f1cda5f4daa52c4"
2583            .parse()
2584            .unwrap();
2585        let block_number = 213;
2586
2587        let expected_timestamp =
2588            NaiveDateTime::parse_from_str("2069-01-01T04:20:00", "%Y-%m-%dT%H:%M:%S").unwrap();
2589
2590        let expected = ProtocolStateRequestBody {
2591            protocol_ids: Some(vec!["0xb4eccE46b8D4e4abFd03C9B806276A6735C9c092".to_string()]),
2592            protocol_system: "uniswap_v2".to_string(),
2593            version: VersionParam {
2594                timestamp: Some(expected_timestamp),
2595                block: Some(BlockParam {
2596                    hash: Some(block_hash),
2597                    chain: Some(Chain::Ethereum),
2598                    number: Some(block_number),
2599                }),
2600            },
2601            chain: Chain::Ethereum,
2602            include_balances: false,
2603            pagination: PaginationParams::default(),
2604        };
2605
2606        assert_eq!(result, expected);
2607    }
2608
2609    #[rstest]
2610    #[case::with_protocol_ids(vec![ProtocolId { id: "id1".to_string(), chain: Chain::Ethereum }, ProtocolId { id: "id2".to_string(), chain: Chain::Ethereum }], vec!["id1".to_string(), "id2".to_string()])]
2611    #[case::with_strings(vec!["id1".to_string(), "id2".to_string()], vec!["id1".to_string(), "id2".to_string()])]
2612    fn test_id_filtered<T>(#[case] input_ids: Vec<T>, #[case] expected_ids: Vec<String>)
2613    where
2614        T: Into<String> + Clone,
2615    {
2616        let request_body = ProtocolStateRequestBody::id_filtered(input_ids);
2617
2618        assert_eq!(request_body.protocol_ids, Some(expected_ids));
2619    }
2620
2621    fn create_models_block_changes() -> crate::models::blockchain::BlockAggregatedChanges {
2622        let base_ts = 1694534400; // Example base timestamp for 2023-09-14T00:00:00
2623
2624        crate::models::blockchain::BlockAggregatedChanges {
2625            extractor: "native_name".to_string(),
2626            block: models::blockchain::Block::new(
2627                3,
2628                models::Chain::Ethereum,
2629                Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000000003").unwrap(),
2630                Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000000002").unwrap(),
2631                chrono::DateTime::from_timestamp(base_ts + 3000, 0).unwrap().naive_utc(),
2632            ),
2633            db_committed_block_height: Some(1),
2634            finalized_block_height: 1,
2635            revert: true,
2636            state_deltas: HashMap::from([
2637                ("pc_1".to_string(), models::protocol::ProtocolComponentStateDelta {
2638                    component_id: "pc_1".to_string(),
2639                    updated_attributes: HashMap::from([
2640                        ("attr_2".to_string(), Bytes::from("0x0000000000000002")),
2641                        ("attr_1".to_string(), Bytes::from("0x00000000000003e8")),
2642                    ]),
2643                    deleted_attributes: HashSet::new(),
2644                    ..Default::default()
2645                }),
2646            ]),
2647            new_protocol_components: HashMap::from([
2648                ("pc_2".to_string(), crate::models::protocol::ProtocolComponent {
2649                    id: "pc_2".to_string(),
2650                    protocol_system: "native_protocol_system".to_string(),
2651                    protocol_type_name: "pt_1".to_string(),
2652                    chain: models::Chain::Ethereum,
2653                    tokens: vec![
2654                        Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
2655                        Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
2656                    ],
2657                    contract_addresses: vec![],
2658                    static_attributes: HashMap::new(),
2659                    change: models::ChangeType::Creation,
2660                    creation_tx: Bytes::from_str("0x000000000000000000000000000000000000000000000000000000000000c351").unwrap(),
2661                    created_at: chrono::DateTime::from_timestamp(base_ts + 5000, 0).unwrap().naive_utc(),
2662                }),
2663            ]),
2664            deleted_protocol_components: HashMap::from([
2665                ("pc_3".to_string(), crate::models::protocol::ProtocolComponent {
2666                    id: "pc_3".to_string(),
2667                    protocol_system: "native_protocol_system".to_string(),
2668                    protocol_type_name: "pt_2".to_string(),
2669                    chain: models::Chain::Ethereum,
2670                    tokens: vec![
2671                        Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
2672                        Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
2673                    ],
2674                    contract_addresses: vec![],
2675                    static_attributes: HashMap::new(),
2676                    change: models::ChangeType::Deletion,
2677                    creation_tx: Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000009c41").unwrap(),
2678                    created_at: chrono::DateTime::from_timestamp(base_ts + 4000, 0).unwrap().naive_utc(),
2679                }),
2680            ]),
2681            component_balances: HashMap::from([
2682                ("pc_1".to_string(), HashMap::from([
2683                    (Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(), models::protocol::ComponentBalance {
2684                        token: Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
2685                        balance: Bytes::from("0x00000001"),
2686                        balance_float: 1.0,
2687                        modify_tx: Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000000000").unwrap(),
2688                        component_id: "pc_1".to_string(),
2689                    }),
2690                    (Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(), models::protocol::ComponentBalance {
2691                        token: Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
2692                        balance: Bytes::from("0x000003e8"),
2693                        balance_float: 1000.0,
2694                        modify_tx: Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000007531").unwrap(),
2695                        component_id: "pc_1".to_string(),
2696                    }),
2697                ])),
2698            ]),
2699            account_balances: HashMap::from([
2700                (Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(), HashMap::from([
2701                    (Bytes::from_str("0x7a250d5630b4cf539739df2c5dacb4c659f2488d").unwrap(), models::contract::AccountBalance {
2702                        account: Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
2703                        token: Bytes::from_str("0x7a250d5630b4cf539739df2c5dacb4c659f2488d").unwrap(),
2704                        balance: Bytes::from("0x000003e8"),
2705                        modify_tx: Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000007531").unwrap(),
2706                    }),
2707                    ])),
2708            ]),
2709            ..Default::default()
2710        }
2711    }
2712
2713    #[test]
2714    fn test_serialize_deserialize_block_changes() {
2715        // Test that models::BlockAggregatedChanges serialized as json can be deserialized as
2716        // dto::BlockAggregatedChanges.
2717
2718        // Create a models::BlockAggregatedChanges instance
2719        let block_entity_changes = create_models_block_changes();
2720
2721        // Serialize the struct into JSON
2722        let json_data = serde_json::to_string(&block_entity_changes).expect("Failed to serialize");
2723
2724        // Deserialize the JSON back into a dto::BlockAggregatedChanges struct
2725        serde_json::from_str::<BlockAggregatedChanges>(&json_data).expect("parsing failed");
2726    }
2727
2728    #[test]
2729    fn test_parse_block_changes() {
2730        let json_data = r#"
2731        {
2732            "extractor": "vm:ambient",
2733            "chain": "ethereum",
2734            "block": {
2735                "number": 123,
2736                "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2737                "parent_hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2738                "chain": "ethereum",
2739                "ts": "2023-09-14T00:00:00"
2740            },
2741            "finalized_block_height": 0,
2742            "revert": false,
2743            "new_tokens": {},
2744            "account_updates": {
2745                "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2746                    "address": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2747                    "chain": "ethereum",
2748                    "slots": {},
2749                    "balance": "0x01f4",
2750                    "code": "",
2751                    "change": "Update"
2752                }
2753            },
2754            "state_updates": {
2755                "component_1": {
2756                    "component_id": "component_1",
2757                    "updated_attributes": {"attr1": "0x01"},
2758                    "deleted_attributes": ["attr2"]
2759                }
2760            },
2761            "new_protocol_components":
2762                { "protocol_1": {
2763                        "id": "protocol_1",
2764                        "protocol_system": "system_1",
2765                        "protocol_type_name": "type_1",
2766                        "chain": "ethereum",
2767                        "tokens": ["0x01", "0x02"],
2768                        "contract_ids": ["0x01", "0x02"],
2769                        "static_attributes": {"attr1": "0x01f4"},
2770                        "change": "Update",
2771                        "creation_tx": "0x01",
2772                        "created_at": "2023-09-14T00:00:00"
2773                    }
2774                },
2775            "deleted_protocol_components": {},
2776            "component_balances": {
2777                "protocol_1":
2778                    {
2779                        "0x01": {
2780                            "token": "0x01",
2781                            "balance": "0xb77831d23691653a01",
2782                            "balance_float": 3.3844151001790677e21,
2783                            "modify_tx": "0x01",
2784                            "component_id": "protocol_1"
2785                        }
2786                    }
2787            },
2788            "account_balances": {
2789                "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2790                    "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2791                        "account": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2792                        "token": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2793                        "balance": "0x01f4",
2794                        "modify_tx": "0x01"
2795                    }
2796                }
2797            },
2798            "component_tvl": {
2799                "protocol_1": 1000.0
2800            },
2801            "dci_update": {
2802                "new_entrypoints": {
2803                    "component_1": [
2804                        {
2805                            "external_id": "0x01:sig()",
2806                            "target": "0x01",
2807                            "signature": "sig()"
2808                        }
2809                    ]
2810                },
2811                "new_entrypoint_params": {
2812                    "0x01:sig()": [
2813                        [
2814                            {
2815                                "method": "rpctracer",
2816                                "caller": "0x01",
2817                                "calldata": "0x02"
2818                            },
2819                            "component_1"
2820                        ]
2821                    ]
2822                },
2823                "trace_results": {
2824                    "0x01:sig()": {
2825                        "retriggers": [
2826                            ["0x01", {"key": "0x02", "offset": 12}]
2827                        ],
2828                        "accessed_slots": {
2829                            "0x03": ["0x03", "0x04"]
2830                        }
2831                    }
2832                }
2833            }
2834        }
2835        "#;
2836
2837        serde_json::from_str::<BlockAggregatedChanges>(json_data).expect("parsing failed");
2838    }
2839
2840    #[test]
2841    fn test_parse_websocket_message() {
2842        let json_data = r#"
2843        {
2844            "subscription_id": "5d23bfbe-89ad-4ea3-8672-dc9e973ac9dc",
2845            "deltas": {
2846                "type": "BlockAggregatedChanges",
2847                "extractor": "uniswap_v2",
2848                "chain": "ethereum",
2849                "block": {
2850                    "number": 19291517,
2851                    "hash": "0xbc3ea4896c0be8da6229387a8571b72818aa258daf4fab46471003ad74c4ee83",
2852                    "parent_hash": "0x89ca5b8d593574cf6c886f41ef8208bf6bdc1a90ef36046cb8c84bc880b9af8f",
2853                    "chain": "ethereum",
2854                    "ts": "2024-02-23T16:35:35"
2855                },
2856                "finalized_block_height": 0,
2857                "revert": false,
2858                "new_tokens": {},
2859                "account_updates": {
2860                    "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2861                        "address": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2862                        "chain": "ethereum",
2863                        "slots": {},
2864                        "balance": "0x01f4",
2865                        "code": "",
2866                        "change": "Update"
2867                    }
2868                },
2869                "state_updates": {
2870                    "0xde6faedbcae38eec6d33ad61473a04a6dd7f6e28": {
2871                        "component_id": "0xde6faedbcae38eec6d33ad61473a04a6dd7f6e28",
2872                        "updated_attributes": {
2873                            "reserve0": "0x87f7b5973a7f28a8b32404",
2874                            "reserve1": "0x09e9564b11"
2875                        },
2876                        "deleted_attributes": []
2877                    },
2878                    "0x99c59000f5a76c54c4fd7d82720c045bdcf1450d": {
2879                        "component_id": "0x99c59000f5a76c54c4fd7d82720c045bdcf1450d",
2880                        "updated_attributes": {
2881                            "reserve1": "0x44d9a8fd662c2f4d03",
2882                            "reserve0": "0x500b1261f811d5bf423e"
2883                        },
2884                        "deleted_attributes": []
2885                    }
2886                },
2887                "new_protocol_components": {},
2888                "deleted_protocol_components": {},
2889                "component_balances": {
2890                    "0x99c59000f5a76c54c4fd7d82720c045bdcf1450d": {
2891                        "0x9012744b7a564623b6c3e40b144fc196bdedf1a9": {
2892                            "token": "0x9012744b7a564623b6c3e40b144fc196bdedf1a9",
2893                            "balance": "0x500b1261f811d5bf423e",
2894                            "balance_float": 3.779935574269033E23,
2895                            "modify_tx": "0xe46c4db085fb6c6f3408a65524555797adb264e1d5cf3b66ad154598f85ac4bf",
2896                            "component_id": "0x99c59000f5a76c54c4fd7d82720c045bdcf1450d"
2897                        },
2898                        "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2": {
2899                            "token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
2900                            "balance": "0x44d9a8fd662c2f4d03",
2901                            "balance_float": 1.270062661329837E21,
2902                            "modify_tx": "0xe46c4db085fb6c6f3408a65524555797adb264e1d5cf3b66ad154598f85ac4bf",
2903                            "component_id": "0x99c59000f5a76c54c4fd7d82720c045bdcf1450d"
2904                        }
2905                    }
2906                },
2907                "account_balances": {
2908                    "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2909                        "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": {
2910                            "account": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2911                            "token": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
2912                            "balance": "0x01f4",
2913                            "modify_tx": "0x01"
2914                        }
2915                    }
2916                },
2917                "component_tvl": {},
2918                "dci_update": {
2919                    "new_entrypoints": {
2920                        "0xde6faedbcae38eec6d33ad61473a04a6dd7f6e28": [
2921                            {
2922                                "external_id": "0x01:sig()",
2923                                "target": "0x01",
2924                                "signature": "sig()"
2925                            }
2926                        ]
2927                    },
2928                    "new_entrypoint_params": {
2929                        "0x01:sig()": [
2930                            [
2931                                {
2932                                    "method": "rpctracer",
2933                                    "caller": "0x01",
2934                                    "calldata": "0x02"
2935                                },
2936                                "0xde6faedbcae38eec6d33ad61473a04a6dd7f6e28"
2937                            ]
2938                        ]
2939                    },
2940                    "trace_results": {
2941                        "0x01:sig()": {
2942                            "retriggers": [
2943                                ["0x01", {"key": "0x02", "offset": 12}]
2944                            ],
2945                            "accessed_slots": {
2946                                "0x03": ["0x03", "0x04"]
2947                            }
2948                        }
2949                    }
2950                }
2951            }
2952        }
2953        "#;
2954        serde_json::from_str::<WebSocketMessage>(json_data).expect("parsing failed");
2955    }
2956
2957    #[test]
2958    fn test_protocol_state_delta_merge_update_delete() {
2959        // Initialize ProtocolStateDelta instances
2960        let mut delta1 = ProtocolStateDelta {
2961            component_id: "Component1".to_string(),
2962            updated_attributes: HashMap::from([(
2963                "Attribute1".to_string(),
2964                Bytes::from("0xbadbabe420"),
2965            )]),
2966            deleted_attributes: HashSet::new(),
2967        };
2968        let delta2 = ProtocolStateDelta {
2969            component_id: "Component1".to_string(),
2970            updated_attributes: HashMap::from([(
2971                "Attribute2".to_string(),
2972                Bytes::from("0x0badbabe"),
2973            )]),
2974            deleted_attributes: HashSet::from(["Attribute1".to_string()]),
2975        };
2976        let exp = ProtocolStateDelta {
2977            component_id: "Component1".to_string(),
2978            updated_attributes: HashMap::from([(
2979                "Attribute2".to_string(),
2980                Bytes::from("0x0badbabe"),
2981            )]),
2982            deleted_attributes: HashSet::from(["Attribute1".to_string()]),
2983        };
2984
2985        delta1.merge(&delta2);
2986
2987        assert_eq!(delta1, exp);
2988    }
2989
2990    #[test]
2991    fn test_protocol_state_delta_merge_delete_update() {
2992        // Initialize ProtocolStateDelta instances
2993        let mut delta1 = ProtocolStateDelta {
2994            component_id: "Component1".to_string(),
2995            updated_attributes: HashMap::new(),
2996            deleted_attributes: HashSet::from(["Attribute1".to_string()]),
2997        };
2998        let delta2 = ProtocolStateDelta {
2999            component_id: "Component1".to_string(),
3000            updated_attributes: HashMap::from([(
3001                "Attribute1".to_string(),
3002                Bytes::from("0x0badbabe"),
3003            )]),
3004            deleted_attributes: HashSet::new(),
3005        };
3006        let exp = ProtocolStateDelta {
3007            component_id: "Component1".to_string(),
3008            updated_attributes: HashMap::from([(
3009                "Attribute1".to_string(),
3010                Bytes::from("0x0badbabe"),
3011            )]),
3012            deleted_attributes: HashSet::new(),
3013        };
3014
3015        delta1.merge(&delta2);
3016
3017        assert_eq!(delta1, exp);
3018    }
3019
3020    #[test]
3021    fn test_account_update_merge() {
3022        // Initialize AccountUpdate instances with same address and valid hex strings for Bytes
3023        let mut account1 = AccountUpdate::new(
3024            Bytes::from(b"0x1234"),
3025            Chain::Ethereum,
3026            HashMap::from([(Bytes::from("0xaabb"), Bytes::from("0xccdd"))]),
3027            Some(Bytes::from("0x1000")),
3028            Some(Bytes::from("0xdeadbeaf")),
3029            ChangeType::Creation,
3030        );
3031
3032        let account2 = AccountUpdate::new(
3033            Bytes::from(b"0x1234"), // Same id as account1
3034            Chain::Ethereum,
3035            HashMap::from([(Bytes::from("0xeeff"), Bytes::from("0x11223344"))]),
3036            Some(Bytes::from("0x2000")),
3037            Some(Bytes::from("0xcafebabe")),
3038            ChangeType::Update,
3039        );
3040
3041        // Merge account2 into account1
3042        account1.merge(&account2);
3043
3044        // Define the expected state after merge
3045        let expected = AccountUpdate::new(
3046            Bytes::from(b"0x1234"), // Same id as before the merge
3047            Chain::Ethereum,
3048            HashMap::from([
3049                (Bytes::from("0xaabb"), Bytes::from("0xccdd")), // Original slot from account1
3050                (Bytes::from("0xeeff"), Bytes::from("0x11223344")), // New slot from account2
3051            ]),
3052            Some(Bytes::from("0x2000")),     // Updated balance
3053            Some(Bytes::from("0xcafebabe")), // Updated code
3054            ChangeType::Creation,            // Updated change type
3055        );
3056
3057        // Assert the new account1 equals to the expected state
3058        assert_eq!(account1, expected);
3059    }
3060
3061    #[test]
3062    fn test_account_update_merge_keeps_code_and_balance_when_other_carries_none() {
3063        let mut creation = AccountUpdate::new(
3064            Bytes::from(b"0x1234"),
3065            Chain::Ethereum,
3066            HashMap::from([(Bytes::from("0xaabb"), Bytes::from("0xccdd"))]),
3067            Some(Bytes::from("0x1000")),
3068            Some(Bytes::from("0xdeadbeaf")),
3069            ChangeType::Creation,
3070        );
3071
3072        // Storage-only delta for the same account, as produced during catch-up reduce(merge).
3073        let storage_only_update = AccountUpdate::new(
3074            Bytes::from(b"0x1234"),
3075            Chain::Ethereum,
3076            HashMap::from([(Bytes::from("0xeeff"), Bytes::from("0x11223344"))]),
3077            None,
3078            None,
3079            ChangeType::Update,
3080        );
3081
3082        creation.merge(&storage_only_update);
3083
3084        assert_eq!(creation.change, ChangeType::Creation);
3085        assert_eq!(creation.code, Some(Bytes::from("0xdeadbeaf")));
3086        assert_eq!(creation.balance, Some(Bytes::from("0x1000")));
3087        assert_eq!(
3088            creation.slots,
3089            HashMap::from([
3090                (Bytes::from("0xaabb"), Bytes::from("0xccdd")),
3091                (Bytes::from("0xeeff"), Bytes::from("0x11223344")),
3092            ])
3093        );
3094    }
3095
3096    #[test]
3097    fn test_block_account_changes_merge() {
3098        // Prepare account updates
3099        let old_account_updates: HashMap<Bytes, AccountUpdate> = [(
3100            Bytes::from("0x0011"),
3101            AccountUpdate {
3102                address: Bytes::from("0x00"),
3103                chain: Chain::Ethereum,
3104                slots: HashMap::from([(Bytes::from("0x0022"), Bytes::from("0x0033"))]),
3105                balance: Some(Bytes::from("0x01")),
3106                code: Some(Bytes::from("0x02")),
3107                change: ChangeType::Creation,
3108            },
3109        )]
3110        .into_iter()
3111        .collect();
3112        let new_account_updates: HashMap<Bytes, AccountUpdate> = [(
3113            Bytes::from("0x0011"),
3114            AccountUpdate {
3115                address: Bytes::from("0x00"),
3116                chain: Chain::Ethereum,
3117                slots: HashMap::from([(Bytes::from("0x0044"), Bytes::from("0x0055"))]),
3118                balance: Some(Bytes::from("0x03")),
3119                code: Some(Bytes::from("0x04")),
3120                change: ChangeType::Update,
3121            },
3122        )]
3123        .into_iter()
3124        .collect();
3125        // Create initial and new BlockAccountChanges instances
3126        let block_account_changes_initial = BlockAggregatedChanges {
3127            extractor: "extractor1".to_string(),
3128            revert: false,
3129            account_updates: old_account_updates,
3130            ..Default::default()
3131        };
3132
3133        let block_account_changes_new = BlockAggregatedChanges {
3134            extractor: "extractor2".to_string(),
3135            revert: true,
3136            account_updates: new_account_updates,
3137            ..Default::default()
3138        };
3139
3140        // Merge the new BlockAggregatedChanges into the initial one
3141        let res = block_account_changes_initial.merge(block_account_changes_new);
3142
3143        // Create the expected result of the merge operation
3144        let expected_account_updates: HashMap<Bytes, AccountUpdate> = [(
3145            Bytes::from("0x0011"),
3146            AccountUpdate {
3147                address: Bytes::from("0x00"),
3148                chain: Chain::Ethereum,
3149                slots: HashMap::from([
3150                    (Bytes::from("0x0044"), Bytes::from("0x0055")),
3151                    (Bytes::from("0x0022"), Bytes::from("0x0033")),
3152                ]),
3153                balance: Some(Bytes::from("0x03")),
3154                code: Some(Bytes::from("0x04")),
3155                change: ChangeType::Creation,
3156            },
3157        )]
3158        .into_iter()
3159        .collect();
3160        let block_account_changes_expected = BlockAggregatedChanges {
3161            extractor: "extractor1".to_string(),
3162            revert: true,
3163            account_updates: expected_account_updates,
3164            ..Default::default()
3165        };
3166        assert_eq!(res, block_account_changes_expected);
3167    }
3168
3169    #[test]
3170    fn test_block_entity_changes_merge() {
3171        // Initialize two BlockAggregatedChanges instances with different details
3172        let block_entity_changes_result1 = BlockAggregatedChanges {
3173            extractor: String::from("extractor1"),
3174            revert: false,
3175            state_updates: hashmap! { "state1".to_string() => ProtocolStateDelta::default() },
3176            new_protocol_components: hashmap! { "component1".to_string() => ProtocolComponent::default() },
3177            deleted_protocol_components: HashMap::new(),
3178            component_balances: hashmap! {
3179                "component1".to_string() => TokenBalances(hashmap! {
3180                    Bytes::from("0x01") => ComponentBalance {
3181                            token: Bytes::from("0x01"),
3182                            balance: Bytes::from("0x01"),
3183                            balance_float: 1.0,
3184                            modify_tx: Bytes::from("0x00"),
3185                            component_id: "component1".to_string()
3186                        },
3187                    Bytes::from("0x02") => ComponentBalance {
3188                        token: Bytes::from("0x02"),
3189                        balance: Bytes::from("0x02"),
3190                        balance_float: 2.0,
3191                        modify_tx: Bytes::from("0x00"),
3192                        component_id: "component1".to_string()
3193                    },
3194                })
3195
3196            },
3197            component_tvl: hashmap! { "tvl1".to_string() => 1000.0 },
3198            ..Default::default()
3199        };
3200        let block_entity_changes_result2 = BlockAggregatedChanges {
3201            extractor: String::from("extractor2"),
3202            revert: true,
3203            state_updates: hashmap! { "state2".to_string() => ProtocolStateDelta::default() },
3204            new_protocol_components: hashmap! { "component2".to_string() => ProtocolComponent::default() },
3205            deleted_protocol_components: hashmap! { "component3".to_string() => ProtocolComponent::default() },
3206            component_balances: hashmap! {
3207                "component1".to_string() => TokenBalances::default(),
3208                "component2".to_string() => TokenBalances::default()
3209            },
3210            component_tvl: hashmap! { "tvl2".to_string() => 2000.0 },
3211            ..Default::default()
3212        };
3213
3214        let res = block_entity_changes_result1.merge(block_entity_changes_result2);
3215
3216        let expected_block_entity_changes_result = BlockAggregatedChanges {
3217            extractor: String::from("extractor1"),
3218            revert: true,
3219            state_updates: hashmap! {
3220                "state1".to_string() => ProtocolStateDelta::default(),
3221                "state2".to_string() => ProtocolStateDelta::default(),
3222            },
3223            new_protocol_components: hashmap! {
3224                "component1".to_string() => ProtocolComponent::default(),
3225                "component2".to_string() => ProtocolComponent::default(),
3226            },
3227            deleted_protocol_components: hashmap! {
3228                "component3".to_string() => ProtocolComponent::default(),
3229            },
3230            component_balances: hashmap! {
3231                "component1".to_string() => TokenBalances(hashmap! {
3232                    Bytes::from("0x01") => ComponentBalance {
3233                            token: Bytes::from("0x01"),
3234                            balance: Bytes::from("0x01"),
3235                            balance_float: 1.0,
3236                            modify_tx: Bytes::from("0x00"),
3237                            component_id: "component1".to_string()
3238                        },
3239                    Bytes::from("0x02") => ComponentBalance {
3240                        token: Bytes::from("0x02"),
3241                        balance: Bytes::from("0x02"),
3242                        balance_float: 2.0,
3243                        modify_tx: Bytes::from("0x00"),
3244                        component_id: "component1".to_string()
3245                        },
3246                    }),
3247                "component2".to_string() => TokenBalances::default(),
3248            },
3249            component_tvl: hashmap! {
3250                "tvl1".to_string() => 1000.0,
3251                "tvl2".to_string() => 2000.0
3252            },
3253            ..Default::default()
3254        };
3255
3256        assert_eq!(res, expected_block_entity_changes_result);
3257    }
3258
3259    #[test]
3260    fn test_websocket_error_serialization() {
3261        let extractor_id = ExtractorIdentity::new(Chain::Ethereum, "test_extractor");
3262        let subscription_id = Uuid::new_v4();
3263
3264        // Test ExtractorNotFound serialization
3265        let error = WebsocketError::ExtractorNotFound(extractor_id.clone());
3266        let json = serde_json::to_string(&error).unwrap();
3267        let deserialized: WebsocketError = serde_json::from_str(&json).unwrap();
3268        assert_eq!(error, deserialized);
3269
3270        // Test SubscriptionNotFound serialization
3271        let error = WebsocketError::SubscriptionNotFound(subscription_id);
3272        let json = serde_json::to_string(&error).unwrap();
3273        let deserialized: WebsocketError = serde_json::from_str(&json).unwrap();
3274        assert_eq!(error, deserialized);
3275
3276        // Test ParseError serialization
3277        let error = WebsocketError::ParseError("{asd".to_string(), "invalid json".to_string());
3278        let json = serde_json::to_string(&error).unwrap();
3279        let deserialized: WebsocketError = serde_json::from_str(&json).unwrap();
3280        assert_eq!(error, deserialized);
3281
3282        // Test SubscribeError serialization
3283        let error = WebsocketError::SubscribeError(extractor_id);
3284        let json = serde_json::to_string(&error).unwrap();
3285        let deserialized: WebsocketError = serde_json::from_str(&json).unwrap();
3286        assert_eq!(error, deserialized);
3287
3288        // Test CompressionError serialization
3289        let error =
3290            WebsocketError::CompressionError(subscription_id, "Compression failed".to_string());
3291        let json = serde_json::to_string(&error).unwrap();
3292        let deserialized: WebsocketError = serde_json::from_str(&json).unwrap();
3293        assert_eq!(error, deserialized);
3294    }
3295
3296    #[test]
3297    fn test_websocket_message_with_error_response() {
3298        let error =
3299            WebsocketError::ParseError("}asdfas".to_string(), "malformed request".to_string());
3300        let response = Response::Error(error.clone());
3301        let message = WebSocketMessage::Response(response);
3302
3303        let json = serde_json::to_string(&message).unwrap();
3304        let deserialized: WebSocketMessage = serde_json::from_str(&json).unwrap();
3305
3306        if let WebSocketMessage::Response(Response::Error(deserialized_error)) = deserialized {
3307            assert_eq!(error, deserialized_error);
3308        } else {
3309            panic!("Expected WebSocketMessage::Response(Response::Error)");
3310        }
3311    }
3312
3313    #[test]
3314    fn test_websocket_error_conversion_from_models() {
3315        use crate::models::error;
3316
3317        let extractor_id =
3318            crate::models::ExtractorIdentity::new(crate::models::Chain::Ethereum, "test");
3319        let subscription_id = Uuid::new_v4();
3320
3321        // Test ExtractorNotFound conversion
3322        let models_error = error::WebsocketError::ExtractorNotFound(extractor_id.clone());
3323        let dto_error: WebsocketError = models_error.into();
3324        assert_eq!(dto_error, WebsocketError::ExtractorNotFound(extractor_id.clone().into()));
3325
3326        // Test SubscriptionNotFound conversion
3327        let models_error = error::WebsocketError::SubscriptionNotFound(subscription_id);
3328        let dto_error: WebsocketError = models_error.into();
3329        assert_eq!(dto_error, WebsocketError::SubscriptionNotFound(subscription_id));
3330
3331        // Test ParseError conversion - create a real JSON parse error
3332        let json_result: Result<serde_json::Value, _> = serde_json::from_str("{invalid json");
3333        let json_error = json_result.unwrap_err();
3334        let models_error =
3335            error::WebsocketError::ParseError("{invalid json".to_string(), json_error);
3336        let dto_error: WebsocketError = models_error.into();
3337        if let WebsocketError::ParseError(msg, error_msg) = dto_error {
3338            // Just check that we have a non-empty error message
3339            assert!(!error_msg.is_empty(), "Error message should not be empty, got: '{}'", msg);
3340        } else {
3341            panic!("Expected ParseError variant");
3342        }
3343
3344        // Test SubscribeError conversion
3345        let models_error = error::WebsocketError::SubscribeError(extractor_id.clone());
3346        let dto_error: WebsocketError = models_error.into();
3347        assert_eq!(dto_error, WebsocketError::SubscribeError(extractor_id.into()));
3348
3349        // Test CompressionError conversion
3350        let io_error = std::io::Error::other("Compression failed");
3351        let models_error = error::WebsocketError::CompressionError(subscription_id, io_error);
3352        let dto_error: WebsocketError = models_error.into();
3353        if let WebsocketError::CompressionError(sub_id, msg) = &dto_error {
3354            assert_eq!(*sub_id, subscription_id);
3355            assert!(msg.contains("Compression failed"));
3356        } else {
3357            panic!("Expected CompressionError variant");
3358        }
3359    }
3360}
3361
3362#[cfg(test)]
3363mod memory_size_tests {
3364    use std::collections::HashMap;
3365
3366    use super::*;
3367
3368    #[test]
3369    fn test_state_request_response_memory_size_empty() {
3370        let response = StateRequestResponse {
3371            accounts: vec![],
3372            pagination: PaginationResponse::new(1, 10, 0),
3373        };
3374
3375        let size = response.deep_size_of();
3376
3377        // Should at least include base struct sizes
3378        assert!(size >= 48, "Empty response should have minimum size of 48 bytes, got {}", size);
3379        assert!(size < 200, "Empty response should not be too large, got {}", size);
3380    }
3381
3382    #[test]
3383    fn test_state_request_response_memory_size_scales_with_slots() {
3384        let create_response_with_slots = |slot_count: usize| {
3385            let mut slots = HashMap::new();
3386            for i in 0..slot_count {
3387                let key = vec![u8::try_from(i).unwrap(); 32]; // 32-byte key
3388                let value = vec![u8::try_from(i + 100).unwrap(); 32]; // 32-byte value
3389                slots.insert(key.into(), value.into());
3390            }
3391
3392            let account = ResponseAccount::new(
3393                Chain::Ethereum,
3394                vec![1; 20].into(),
3395                "Pool".to_string(),
3396                slots,
3397                vec![1; 32].into(),
3398                HashMap::new(),
3399                vec![].into(), // empty code
3400                vec![1; 32].into(),
3401                vec![1; 32].into(),
3402                vec![1; 32].into(),
3403                None,
3404            );
3405
3406            StateRequestResponse {
3407                accounts: vec![account],
3408                pagination: PaginationResponse::new(1, 10, 1),
3409            }
3410        };
3411
3412        let small_response = create_response_with_slots(10);
3413        let large_response = create_response_with_slots(100);
3414
3415        let small_size = small_response.deep_size_of();
3416        let large_size = large_response.deep_size_of();
3417
3418        // Large response should be significantly bigger
3419        assert!(
3420            large_size > small_size * 5,
3421            "Large response ({} bytes) should be much larger than small response ({} bytes)",
3422            large_size,
3423            small_size
3424        );
3425
3426        // Each slot should contribute at least 64 bytes (32 + 32 + overhead)
3427        let size_diff = large_size - small_size;
3428        let expected_min_diff = 90 * 64; // 90 additional slots * 64 bytes each
3429        assert!(
3430            size_diff > expected_min_diff,
3431            "Size difference ({} bytes) should reflect the additional slot data",
3432            size_diff
3433        );
3434    }
3435}
3436
3437#[cfg(test)]
3438mod pagination_limits_tests {
3439    use super::*;
3440
3441    // Test struct for pagination limits
3442    #[derive(Clone, Debug)]
3443    struct TestRequestBody {
3444        pagination: PaginationParams,
3445    }
3446
3447    // Implement pagination limits for test struct
3448    impl_pagination_limits!(TestRequestBody, compressed = 500, uncompressed = 50);
3449
3450    #[test]
3451    fn test_effective_max_page_size() {
3452        // Test effective max with compression enabled
3453        let max_size = TestRequestBody::effective_max_page_size(true);
3454        assert_eq!(max_size, 500, "Should return compressed limit when compression is enabled");
3455
3456        // Test effective max with compression disabled
3457        let max_size = TestRequestBody::effective_max_page_size(false);
3458        assert_eq!(max_size, 50, "Should return uncompressed limit when compression is disabled");
3459    }
3460}