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