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