Skip to main content

nautilus_blockchain/data/
subscription.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use ahash::{AHashMap, AHashSet};
17use alloy::primitives::{Address, keccak256};
18use nautilus_core::hex;
19use nautilus_model::defi::DexType;
20
21/// Manages subscriptions to DeFi protocol events (swaps, mints, burns, collects) across different DEXs.
22///
23/// This manager counts the owners of each pool address per event type, so overlapping
24/// subscriptions (a complete pool and a narrower event subscription) release independently.
25/// It also maintains the event signature encodings for efficient filtering.
26#[derive(Debug, Default)]
27pub struct DefiDataSubscriptionManager {
28    block_demand_explicit: bool,
29    block_demand_pool_events: bool,
30    block_feed_backend: Option<BlockFeedBackend>,
31    pool_swap_event_encoded: AHashMap<DexType, String>,
32    pool_mint_event_encoded: AHashMap<DexType, String>,
33    pool_burn_event_encoded: AHashMap<DexType, String>,
34    pool_collect_event_encoded: AHashMap<DexType, String>,
35    pool_flash_event_encoded: AHashMap<DexType, String>,
36    pool_fee_protocol_update_event_encoded: AHashMap<DexType, String>,
37    pool_fee_protocol_collect_event_encoded: AHashMap<DexType, String>,
38    subscribed_pool_swaps: AHashMap<DexType, PoolEventDemand>,
39    subscribed_pool_mints: AHashMap<DexType, PoolEventDemand>,
40    subscribed_pool_burns: AHashMap<DexType, PoolEventDemand>,
41    subscribed_pool_collects: AHashMap<DexType, PoolEventDemand>,
42    subscribed_pool_flashes: AHashMap<DexType, PoolEventDemand>,
43    subscribed_pool_fee_protocol_updates: AHashMap<DexType, PoolEventDemand>,
44    subscribed_pool_fee_protocol_collects: AHashMap<DexType, PoolEventDemand>,
45}
46
47impl DefiDataSubscriptionManager {
48    /// Creates a new [`DefiDataSubscriptionManager`] instance.
49    #[must_use]
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    pub(crate) fn add_block_demand(
55        &mut self,
56        owner: BlockFeedOwner,
57        preferred_backend: BlockFeedBackend,
58    ) -> Option<BlockFeedBackend> {
59        match owner {
60            BlockFeedOwner::Explicit => self.block_demand_explicit = true,
61            BlockFeedOwner::PoolEvents => self.block_demand_pool_events = true,
62        }
63
64        self.block_feed_backend
65            .is_none()
66            .then_some(preferred_backend)
67    }
68
69    pub(crate) fn block_feed_started(&mut self, backend: BlockFeedBackend) {
70        self.block_feed_backend = Some(backend);
71    }
72
73    pub(crate) fn remove_block_demand(
74        &mut self,
75        owner: BlockFeedOwner,
76    ) -> Option<BlockFeedBackend> {
77        match owner {
78            BlockFeedOwner::Explicit => self.block_demand_explicit = false,
79            BlockFeedOwner::PoolEvents => self.block_demand_pool_events = false,
80        }
81
82        if self.has_block_demand() {
83            None
84        } else {
85            self.block_feed_backend
86        }
87    }
88
89    pub(crate) fn block_feed_stopped(&mut self, backend: BlockFeedBackend) {
90        if self.block_feed_backend == Some(backend) {
91            self.block_feed_backend = None;
92        }
93    }
94
95    pub(crate) fn clear_block_demand(&mut self) {
96        self.block_demand_explicit = false;
97        self.block_demand_pool_events = false;
98        self.block_feed_backend = None;
99    }
100
101    pub(crate) fn has_pool_event_subscriptions(&self) -> bool {
102        self.subscribed_pool_swaps
103            .values()
104            .chain(self.subscribed_pool_mints.values())
105            .chain(self.subscribed_pool_burns.values())
106            .chain(self.subscribed_pool_collects.values())
107            .chain(self.subscribed_pool_flashes.values())
108            .chain(self.subscribed_pool_fee_protocol_updates.values())
109            .chain(self.subscribed_pool_fee_protocol_collects.values())
110            .any(|addresses| !addresses.is_empty())
111    }
112
113    fn has_block_demand(&self) -> bool {
114        self.block_demand_explicit || self.block_demand_pool_events
115    }
116
117    /// Gets all unique contract addresses subscribed for any event type for a given DEX.
118    #[must_use]
119    pub fn get_subscribed_dex_contract_addresses(&self, dex: &DexType) -> Vec<Address> {
120        let mut unique_addresses = AHashSet::new();
121
122        if let Some(addresses) = self.subscribed_pool_swaps.get(dex) {
123            unique_addresses.extend(addresses.keys().copied());
124        }
125
126        if let Some(addresses) = self.subscribed_pool_mints.get(dex) {
127            unique_addresses.extend(addresses.keys().copied());
128        }
129
130        if let Some(addresses) = self.subscribed_pool_burns.get(dex) {
131            unique_addresses.extend(addresses.keys().copied());
132        }
133
134        if let Some(addresses) = self.subscribed_pool_collects.get(dex) {
135            unique_addresses.extend(addresses.keys().copied());
136        }
137
138        if let Some(addresses) = self.subscribed_pool_flashes.get(dex) {
139            unique_addresses.extend(addresses.keys().copied());
140        }
141
142        if let Some(addresses) = self.subscribed_pool_fee_protocol_updates.get(dex) {
143            unique_addresses.extend(addresses.keys().copied());
144        }
145
146        if let Some(addresses) = self.subscribed_pool_fee_protocol_collects.get(dex) {
147            unique_addresses.extend(addresses.keys().copied());
148        }
149
150        unique_addresses.into_iter().collect()
151    }
152
153    /// Gets all event signatures (keccak256 hashes) registered for a given DEX.
154    #[must_use]
155    pub fn get_subscribed_dex_event_signatures(&self, dex: &DexType) -> Vec<String> {
156        let mut result = Vec::new();
157
158        if let Some(swap_event_signature) = self.pool_swap_event_encoded.get(dex) {
159            result.push(swap_event_signature.clone());
160        }
161
162        if let Some(mint_event_signature) = self.pool_mint_event_encoded.get(dex) {
163            result.push(mint_event_signature.clone());
164        }
165
166        if let Some(burn_event_signature) = self.pool_burn_event_encoded.get(dex) {
167            result.push(burn_event_signature.clone());
168        }
169
170        if let Some(collect_event_signature) = self.pool_collect_event_encoded.get(dex) {
171            result.push(collect_event_signature.clone());
172        }
173
174        if let Some(flash_event_signature) = self.pool_flash_event_encoded.get(dex) {
175            result.push(flash_event_signature.clone());
176        }
177
178        if let Some(fee_protocol_update_event_signature) =
179            self.pool_fee_protocol_update_event_encoded.get(dex)
180        {
181            result.push(fee_protocol_update_event_signature.clone());
182        }
183
184        if let Some(fee_protocol_collect_event_signature) =
185            self.pool_fee_protocol_collect_event_encoded.get(dex)
186        {
187            result.push(fee_protocol_collect_event_signature.clone());
188        }
189
190        result
191    }
192
193    /// Gets event signatures with at least one subscribed pool address for a given DEX.
194    #[must_use]
195    pub fn get_active_subscribed_dex_event_signatures(&self, dex: &DexType) -> Vec<String> {
196        let mut result = Vec::new();
197
198        if self
199            .subscribed_pool_swaps
200            .get(dex)
201            .is_some_and(|addresses| !addresses.is_empty())
202            && let Some(signature) = self.pool_swap_event_encoded.get(dex)
203        {
204            result.push(signature.clone());
205        }
206
207        if self
208            .subscribed_pool_mints
209            .get(dex)
210            .is_some_and(|addresses| !addresses.is_empty())
211            && let Some(signature) = self.pool_mint_event_encoded.get(dex)
212        {
213            result.push(signature.clone());
214        }
215
216        if self
217            .subscribed_pool_burns
218            .get(dex)
219            .is_some_and(|addresses| !addresses.is_empty())
220            && let Some(signature) = self.pool_burn_event_encoded.get(dex)
221        {
222            result.push(signature.clone());
223        }
224
225        if self
226            .subscribed_pool_collects
227            .get(dex)
228            .is_some_and(|addresses| !addresses.is_empty())
229            && let Some(signature) = self.pool_collect_event_encoded.get(dex)
230        {
231            result.push(signature.clone());
232        }
233
234        if self
235            .subscribed_pool_flashes
236            .get(dex)
237            .is_some_and(|addresses| !addresses.is_empty())
238            && let Some(signature) = self.pool_flash_event_encoded.get(dex)
239        {
240            result.push(signature.clone());
241        }
242
243        if self
244            .subscribed_pool_fee_protocol_updates
245            .get(dex)
246            .is_some_and(|addresses| !addresses.is_empty())
247            && let Some(signature) = self.pool_fee_protocol_update_event_encoded.get(dex)
248        {
249            result.push(signature.clone());
250        }
251
252        if self
253            .subscribed_pool_fee_protocol_collects
254            .get(dex)
255            .is_some_and(|addresses| !addresses.is_empty())
256            && let Some(signature) = self.pool_fee_protocol_collect_event_encoded.get(dex)
257        {
258            result.push(signature.clone());
259        }
260
261        result
262    }
263
264    /// Gets pool addresses subscribed to swap events for a given DEX.
265    #[must_use]
266    pub fn get_subscribed_pool_swap_addresses(&self, dex: &DexType) -> Vec<Address> {
267        self.subscribed_pool_swaps
268            .get(dex)
269            .map_or_default(|addresses| addresses.keys().copied().collect())
270    }
271
272    /// Gets pool addresses subscribed to mint events for a given DEX.
273    #[must_use]
274    pub fn get_subscribed_pool_mint_addresses(&self, dex: &DexType) -> Vec<Address> {
275        self.subscribed_pool_mints
276            .get(dex)
277            .map_or_default(|addresses| addresses.keys().copied().collect())
278    }
279
280    /// Gets pool addresses subscribed to burn events for a given DEX.
281    #[must_use]
282    pub fn get_subscribed_pool_burn_addresses(&self, dex: &DexType) -> Vec<Address> {
283        self.subscribed_pool_burns
284            .get(dex)
285            .map_or_default(|addresses| addresses.keys().copied().collect())
286    }
287
288    /// Gets pool addresses subscribed to collect events for a given DEX.
289    #[must_use]
290    pub fn get_subscribed_pool_collect_addresses(&self, dex: &DexType) -> Vec<Address> {
291        self.subscribed_pool_collects
292            .get(dex)
293            .map_or_default(|addresses| addresses.keys().copied().collect())
294    }
295
296    /// Gets pool addresses subscribed to flash events for a given DEX.
297    #[must_use]
298    pub fn get_subscribed_pool_flash_addresses(&self, dex: &DexType) -> Vec<Address> {
299        self.subscribed_pool_flashes
300            .get(dex)
301            .map_or_default(|addresses| addresses.keys().copied().collect())
302    }
303
304    /// Gets pool addresses subscribed to fee-protocol update events for a given DEX.
305    #[must_use]
306    pub fn get_subscribed_pool_fee_protocol_update_addresses(&self, dex: &DexType) -> Vec<Address> {
307        self.subscribed_pool_fee_protocol_updates
308            .get(dex)
309            .map_or_default(|addresses| addresses.keys().copied().collect())
310    }
311
312    /// Gets pool addresses subscribed to fee-protocol collect events for a given DEX.
313    #[must_use]
314    pub fn get_subscribed_pool_fee_protocol_collect_addresses(
315        &self,
316        dex: &DexType,
317    ) -> Vec<Address> {
318        self.subscribed_pool_fee_protocol_collects
319            .get(dex)
320            .map_or_default(|addresses| addresses.keys().copied().collect())
321    }
322
323    /// Gets the swap event signature for a specific DEX.
324    #[must_use]
325    pub fn get_dex_pool_swap_event_signature(&self, dex: &DexType) -> Option<String> {
326        self.pool_swap_event_encoded.get(dex).cloned()
327    }
328
329    /// Gets the mint event signature for a specific DEX.
330    #[must_use]
331    pub fn get_dex_pool_mint_event_signature(&self, dex: &DexType) -> Option<String> {
332        self.pool_mint_event_encoded.get(dex).cloned()
333    }
334    /// Gets the burn event signature for a specific DEX.
335    #[must_use]
336    pub fn get_dex_pool_burn_event_signature(&self, dex: &DexType) -> Option<String> {
337        self.pool_burn_event_encoded.get(dex).cloned()
338    }
339
340    /// Gets the collect event signature for a specific DEX.
341    #[must_use]
342    pub fn get_dex_pool_collect_event_signature(&self, dex: &DexType) -> Option<String> {
343        self.pool_collect_event_encoded.get(dex).cloned()
344    }
345
346    /// Gets the flash event signature for a specific DEX.
347    #[must_use]
348    pub fn get_dex_pool_flash_event_signature(&self, dex: &DexType) -> Option<String> {
349        self.pool_flash_event_encoded.get(dex).cloned()
350    }
351
352    /// Gets the fee-protocol update event signature for a specific DEX.
353    #[must_use]
354    pub fn get_dex_pool_fee_protocol_update_event_signature(
355        &self,
356        dex: &DexType,
357    ) -> Option<String> {
358        self.pool_fee_protocol_update_event_encoded
359            .get(dex)
360            .cloned()
361    }
362
363    /// Gets the fee-protocol collect event signature for a specific DEX.
364    #[must_use]
365    pub fn get_dex_pool_fee_protocol_collect_event_signature(
366        &self,
367        dex: &DexType,
368    ) -> Option<String> {
369        self.pool_fee_protocol_collect_event_encoded
370            .get(dex)
371            .cloned()
372    }
373
374    /// Normalizes an event signature to a consistent format.
375    ///
376    /// Accepts:
377    /// - A raw event signature like "Swap(address,address,int256,int256,uint160,uint128,int24)".
378    /// - A pre-encoded topic like "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67".
379    /// - A hex string without 0x prefix.
380    ///
381    /// Returns a normalized "0x..." format string.
382    fn normalize_topic(sig: &str) -> String {
383        let s = sig.trim();
384
385        // Check if it's already a properly formatted hex string with 0x prefix
386        if let Some(rest) = s.strip_prefix("0x")
387            && rest.len() == 64
388            && rest.chars().all(|c| c.is_ascii_hexdigit())
389        {
390            return format!("0x{}", rest.to_ascii_lowercase());
391        }
392
393        // Check if it's a hex string without 0x prefix
394        if s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) {
395            return format!("0x{}", s.to_ascii_lowercase());
396        }
397
398        // Otherwise, it's a raw signature that needs hashing
399        hex::encode_prefixed(keccak256(s.as_bytes()))
400    }
401
402    /// Registers a DEX with its event signatures for subscription management.
403    ///
404    /// This must be called before subscribing to any events for a DEX.
405    /// Event signatures can be either raw signatures or pre-encoded keccak256 hashes.
406    pub fn register_dex_for_subscriptions(
407        &mut self,
408        dex: DexType,
409        swap_event_signature: &str,
410        mint_event_signature: &str,
411        burn_event_signature: &str,
412        collect_event_signature: &str,
413        flash_event_signature: Option<&str>,
414    ) {
415        self.subscribed_pool_swaps
416            .insert(dex, PoolEventDemand::new());
417        self.pool_swap_event_encoded
418            .insert(dex, Self::normalize_topic(swap_event_signature));
419
420        self.subscribed_pool_mints
421            .insert(dex, PoolEventDemand::new());
422        self.pool_mint_event_encoded
423            .insert(dex, Self::normalize_topic(mint_event_signature));
424
425        self.subscribed_pool_burns
426            .insert(dex, PoolEventDemand::new());
427        self.pool_burn_event_encoded
428            .insert(dex, Self::normalize_topic(burn_event_signature));
429
430        self.subscribed_pool_collects
431            .insert(dex, PoolEventDemand::new());
432        self.pool_collect_event_encoded
433            .insert(dex, Self::normalize_topic(collect_event_signature));
434
435        if let Some(flash_event_signature) = flash_event_signature {
436            self.subscribed_pool_flashes
437                .insert(dex, PoolEventDemand::new());
438            self.pool_flash_event_encoded
439                .insert(dex, Self::normalize_topic(flash_event_signature));
440        }
441
442        log::debug!("Registered DEX for subscriptions: {dex:?}");
443    }
444
445    /// Registers optional fee-protocol event signatures for subscription management.
446    pub fn register_dex_fee_protocol_events(
447        &mut self,
448        dex: DexType,
449        fee_protocol_update_event_signature: Option<&str>,
450        fee_protocol_collect_event_signature: Option<&str>,
451    ) {
452        if let Some(fee_protocol_update_event_signature) = fee_protocol_update_event_signature {
453            self.subscribed_pool_fee_protocol_updates
454                .insert(dex, PoolEventDemand::new());
455            self.pool_fee_protocol_update_event_encoded.insert(
456                dex,
457                Self::normalize_topic(fee_protocol_update_event_signature),
458            );
459        }
460
461        if let Some(fee_protocol_collect_event_signature) = fee_protocol_collect_event_signature {
462            self.subscribed_pool_fee_protocol_collects
463                .insert(dex, PoolEventDemand::new());
464            self.pool_fee_protocol_collect_event_encoded.insert(
465                dex,
466                Self::normalize_topic(fee_protocol_collect_event_signature),
467            );
468        }
469    }
470
471    /// Subscribes to every event type of a specific pool address on a DEX.
472    pub fn subscribe_pool(&mut self, dex: DexType, address: Address) {
473        self.subscribe_swaps(dex, address);
474        self.subscribe_mints(dex, address);
475        self.subscribe_burns(dex, address);
476        self.subscribe_collects(dex, address);
477        self.subscribe_flashes(dex, address);
478        self.subscribe_fee_protocol_updates(dex, address);
479        self.subscribe_fee_protocol_collects(dex, address);
480    }
481
482    /// Unsubscribes from every event type of a specific pool address on a DEX.
483    pub fn unsubscribe_pool(&mut self, dex: DexType, address: Address) {
484        self.unsubscribe_swaps(dex, address);
485        self.unsubscribe_mints(dex, address);
486        self.unsubscribe_burns(dex, address);
487        self.unsubscribe_collects(dex, address);
488        self.unsubscribe_flashes(dex, address);
489        self.unsubscribe_fee_protocol_updates(dex, address);
490        self.unsubscribe_fee_protocol_collects(dex, address);
491    }
492
493    /// Subscribes to swap events for a specific pool address on a DEX.
494    pub fn subscribe_swaps(&mut self, dex: DexType, address: Address) {
495        if let Some(pool_set) = self.subscribed_pool_swaps.get_mut(&dex) {
496            acquire_pool_event(pool_set, address);
497        } else {
498            log::error!("DEX not registered for swap subscriptions: {dex:?}");
499        }
500    }
501
502    /// Subscribes to mint events for a specific pool address on a DEX.
503    pub fn subscribe_mints(&mut self, dex: DexType, address: Address) {
504        if let Some(pool_set) = self.subscribed_pool_mints.get_mut(&dex) {
505            acquire_pool_event(pool_set, address);
506        } else {
507            log::error!("DEX not registered for mint subscriptions: {dex:?}");
508        }
509    }
510
511    /// Subscribes to burn events for a specific pool address on a DEX.
512    pub fn subscribe_burns(&mut self, dex: DexType, address: Address) {
513        if let Some(pool_set) = self.subscribed_pool_burns.get_mut(&dex) {
514            acquire_pool_event(pool_set, address);
515        } else {
516            log::warn!("DEX not registered for burn subscriptions: {dex:?}");
517        }
518    }
519
520    /// Unsubscribes from swap events for a specific pool address on a DEX.
521    pub fn unsubscribe_swaps(&mut self, dex: DexType, address: Address) {
522        if let Some(pool_set) = self.subscribed_pool_swaps.get_mut(&dex) {
523            release_pool_event(pool_set, address);
524        } else {
525            log::error!("DEX not registered for swap subscriptions: {dex:?}");
526        }
527    }
528
529    /// Unsubscribes from mint events for a specific pool address on a DEX.
530    pub fn unsubscribe_mints(&mut self, dex: DexType, address: Address) {
531        if let Some(pool_set) = self.subscribed_pool_mints.get_mut(&dex) {
532            release_pool_event(pool_set, address);
533        } else {
534            log::error!("DEX not registered for mint subscriptions: {dex:?}");
535        }
536    }
537
538    /// Unsubscribes from burn events for a specific pool address on a DEX.
539    pub fn unsubscribe_burns(&mut self, dex: DexType, address: Address) {
540        if let Some(pool_set) = self.subscribed_pool_burns.get_mut(&dex) {
541            release_pool_event(pool_set, address);
542        } else {
543            log::error!("DEX not registered for burn subscriptions: {dex:?}");
544        }
545    }
546
547    /// Subscribes to collect events for a specific pool address on a DEX.
548    pub fn subscribe_collects(&mut self, dex: DexType, address: Address) {
549        if let Some(pool_set) = self.subscribed_pool_collects.get_mut(&dex) {
550            acquire_pool_event(pool_set, address);
551        } else {
552            log::error!("DEX not registered for collect subscriptions: {dex:?}");
553        }
554    }
555
556    /// Unsubscribes from collect events for a specific pool address on a DEX.
557    pub fn unsubscribe_collects(&mut self, dex: DexType, address: Address) {
558        if let Some(pool_set) = self.subscribed_pool_collects.get_mut(&dex) {
559            release_pool_event(pool_set, address);
560        } else {
561            log::error!("DEX not registered for collect subscriptions: {dex:?}");
562        }
563    }
564
565    /// Subscribes to flash events for a specific pool address on a DEX.
566    pub fn subscribe_flashes(&mut self, dex: DexType, address: Address) {
567        if let Some(pool_set) = self.subscribed_pool_flashes.get_mut(&dex) {
568            acquire_pool_event(pool_set, address);
569        } else {
570            log::error!("DEX not registered for flash subscriptions: {dex:?}");
571        }
572    }
573
574    /// Unsubscribes from flash events for a specific pool address on a DEX.
575    pub fn unsubscribe_flashes(&mut self, dex: DexType, address: Address) {
576        if let Some(pool_set) = self.subscribed_pool_flashes.get_mut(&dex) {
577            release_pool_event(pool_set, address);
578        } else {
579            log::error!("DEX not registered for flash subscriptions: {dex:?}");
580        }
581    }
582
583    /// Subscribes to fee-protocol update events for a specific pool address on a DEX.
584    pub fn subscribe_fee_protocol_updates(&mut self, dex: DexType, address: Address) {
585        if let Some(pool_set) = self.subscribed_pool_fee_protocol_updates.get_mut(&dex) {
586            acquire_pool_event(pool_set, address);
587        }
588    }
589
590    /// Unsubscribes from fee-protocol update events for a specific pool address on a DEX.
591    pub fn unsubscribe_fee_protocol_updates(&mut self, dex: DexType, address: Address) {
592        if let Some(pool_set) = self.subscribed_pool_fee_protocol_updates.get_mut(&dex) {
593            release_pool_event(pool_set, address);
594        }
595    }
596
597    /// Subscribes to fee-protocol collect events for a specific pool address on a DEX.
598    pub fn subscribe_fee_protocol_collects(&mut self, dex: DexType, address: Address) {
599        if let Some(pool_set) = self.subscribed_pool_fee_protocol_collects.get_mut(&dex) {
600            acquire_pool_event(pool_set, address);
601        }
602    }
603
604    /// Unsubscribes from fee-protocol collect events for a specific pool address on a DEX.
605    pub fn unsubscribe_fee_protocol_collects(&mut self, dex: DexType, address: Address) {
606        if let Some(pool_set) = self.subscribed_pool_fee_protocol_collects.get_mut(&dex) {
607            release_pool_event(pool_set, address);
608        }
609    }
610}
611
612/// Owner count per pool address for one event kind; an address is present only while owned.
613type PoolEventDemand = AHashMap<Address, usize>;
614
615fn acquire_pool_event(demand: &mut PoolEventDemand, address: Address) {
616    *demand.entry(address).or_default() += 1;
617}
618
619fn release_pool_event(demand: &mut PoolEventDemand, address: Address) {
620    if let Some(owners) = demand.get_mut(&address) {
621        *owners -= 1;
622        if *owners == 0 {
623            demand.remove(&address);
624        }
625    }
626}
627
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629pub(crate) enum BlockFeedBackend {
630    Rpc,
631    HyperSync,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub(crate) enum BlockFeedOwner {
636    Explicit,
637    PoolEvents,
638}
639
640#[cfg(test)]
641mod tests {
642    use alloy::primitives::address;
643    use rstest::{fixture, rstest};
644
645    use super::*;
646
647    #[fixture]
648    fn manager() -> DefiDataSubscriptionManager {
649        DefiDataSubscriptionManager::new()
650    }
651
652    #[fixture]
653    fn registered_manager() -> DefiDataSubscriptionManager {
654        let mut manager = DefiDataSubscriptionManager::new();
655        manager.register_dex_for_subscriptions(
656            DexType::UniswapV3,
657            "Swap(address,address,int256,int256,uint160,uint128,int24)",
658            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
659            "Burn(address,int24,int24,uint128,uint256,uint256)",
660            "Collect(address,address,int24,int24,uint128,uint128)",
661            Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
662        );
663        manager
664    }
665
666    #[rstest]
667    #[case(BlockFeedBackend::Rpc)]
668    #[case(BlockFeedBackend::HyperSync)]
669    fn block_feed_pool_only_stops_with_final_owner(#[case] backend: BlockFeedBackend) {
670        let mut manager = DefiDataSubscriptionManager::new();
671
672        assert_eq!(
673            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
674            Some(backend)
675        );
676        manager.block_feed_started(backend);
677
678        assert_eq!(
679            manager.remove_block_demand(BlockFeedOwner::PoolEvents),
680            Some(backend)
681        );
682        manager.block_feed_stopped(backend);
683
684        assert_eq!(
685            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
686            Some(backend)
687        );
688    }
689
690    #[rstest]
691    #[case(BlockFeedBackend::Rpc)]
692    #[case(BlockFeedBackend::HyperSync)]
693    fn block_feed_repeated_commands_are_idempotent(#[case] backend: BlockFeedBackend) {
694        let mut manager = DefiDataSubscriptionManager::new();
695
696        assert_eq!(
697            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
698            Some(backend)
699        );
700        manager.block_feed_started(backend);
701        assert_eq!(
702            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
703            None
704        );
705
706        assert_eq!(
707            manager.remove_block_demand(BlockFeedOwner::Explicit),
708            Some(backend)
709        );
710        manager.block_feed_stopped(backend);
711        assert_eq!(manager.remove_block_demand(BlockFeedOwner::Explicit), None);
712    }
713
714    #[rstest]
715    #[case(BlockFeedBackend::Rpc)]
716    #[case(BlockFeedBackend::HyperSync)]
717    fn block_feed_explicit_demand_survives_pool_unsubscribe(#[case] backend: BlockFeedBackend) {
718        let mut manager = DefiDataSubscriptionManager::new();
719
720        assert_eq!(
721            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
722            Some(backend)
723        );
724        manager.block_feed_started(backend);
725        assert_eq!(
726            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
727            None
728        );
729
730        assert_eq!(
731            manager.remove_block_demand(BlockFeedOwner::PoolEvents),
732            None
733        );
734        assert_eq!(
735            manager.remove_block_demand(BlockFeedOwner::Explicit),
736            Some(backend)
737        );
738    }
739
740    #[rstest]
741    #[case(BlockFeedBackend::Rpc)]
742    #[case(BlockFeedBackend::HyperSync)]
743    fn block_feed_pool_demand_survives_explicit_unsubscribe(#[case] backend: BlockFeedBackend) {
744        let mut manager = DefiDataSubscriptionManager::new();
745
746        assert_eq!(
747            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
748            Some(backend)
749        );
750        manager.block_feed_started(backend);
751        assert_eq!(
752            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
753            None
754        );
755
756        assert_eq!(manager.remove_block_demand(BlockFeedOwner::Explicit), None);
757        assert_eq!(
758            manager.remove_block_demand(BlockFeedOwner::PoolEvents),
759            Some(backend)
760        );
761    }
762
763    #[rstest]
764    #[case(BlockFeedBackend::Rpc)]
765    #[case(BlockFeedBackend::HyperSync)]
766    fn block_feed_pool_demand_spans_dexes_addresses_and_events(#[case] backend: BlockFeedBackend) {
767        let mut manager = DefiDataSubscriptionManager::new();
768        let pool1 = address!("1111111111111111111111111111111111111111");
769        let pool2 = address!("2222222222222222222222222222222222222222");
770        let pool3 = address!("3333333333333333333333333333333333333333");
771
772        for dex in [DexType::UniswapV3, DexType::PancakeSwapV3] {
773            manager.register_dex_for_subscriptions(
774                dex,
775                "Swap(address,address,int256,int256,uint160,uint128,int24)",
776                "Mint(address,address,int24,int24,uint128,uint256,uint256)",
777                "Burn(address,int24,int24,uint128,uint256,uint256)",
778                "Collect(address,address,int24,int24,uint128,uint128)",
779                Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
780            );
781        }
782
783        manager.subscribe_swaps(DexType::UniswapV3, pool1);
784        manager.subscribe_mints(DexType::UniswapV3, pool2);
785        manager.subscribe_flashes(DexType::PancakeSwapV3, pool3);
786
787        assert!(manager.has_pool_event_subscriptions());
788        assert_eq!(
789            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
790            Some(backend)
791        );
792        manager.block_feed_started(backend);
793
794        manager.unsubscribe_swaps(DexType::UniswapV3, pool1);
795        assert!(manager.has_pool_event_subscriptions());
796        assert_eq!(
797            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
798            None
799        );
800
801        manager.unsubscribe_mints(DexType::UniswapV3, pool2);
802        assert!(manager.has_pool_event_subscriptions());
803        assert_eq!(
804            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
805            None
806        );
807
808        manager.unsubscribe_flashes(DexType::PancakeSwapV3, pool3);
809        assert!(!manager.has_pool_event_subscriptions());
810        assert_eq!(
811            manager.remove_block_demand(BlockFeedOwner::PoolEvents),
812            Some(backend)
813        );
814    }
815
816    #[rstest]
817    #[case(BlockFeedBackend::Rpc)]
818    #[case(BlockFeedBackend::HyperSync)]
819    fn block_feed_disconnect_clears_owners_and_backend(#[case] backend: BlockFeedBackend) {
820        let mut manager = DefiDataSubscriptionManager::new();
821
822        assert_eq!(
823            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
824            Some(backend)
825        );
826        manager.block_feed_started(backend);
827        assert_eq!(
828            manager.add_block_demand(BlockFeedOwner::PoolEvents, backend),
829            None
830        );
831
832        manager.clear_block_demand();
833
834        assert!(!manager.block_demand_explicit);
835        assert!(!manager.block_demand_pool_events);
836        assert_eq!(manager.block_feed_backend, None);
837        assert_eq!(
838            manager.add_block_demand(BlockFeedOwner::Explicit, backend),
839            Some(backend)
840        );
841    }
842
843    #[rstest]
844    fn block_feed_rpc_fallback_stops_hypersync_backend() {
845        let mut manager = DefiDataSubscriptionManager::new();
846
847        assert_eq!(
848            manager.add_block_demand(BlockFeedOwner::Explicit, BlockFeedBackend::Rpc),
849            Some(BlockFeedBackend::Rpc)
850        );
851        manager.block_feed_started(BlockFeedBackend::HyperSync);
852
853        assert_eq!(
854            manager.remove_block_demand(BlockFeedOwner::Explicit),
855            Some(BlockFeedBackend::HyperSync)
856        );
857    }
858
859    #[rstest]
860    fn test_new_creates_empty_manager(manager: DefiDataSubscriptionManager) {
861        assert_eq!(
862            manager
863                .get_subscribed_dex_contract_addresses(&DexType::UniswapV3)
864                .len(),
865            0
866        );
867        assert_eq!(
868            manager
869                .get_subscribed_dex_event_signatures(&DexType::UniswapV3)
870                .len(),
871            0
872        );
873        assert!(
874            manager
875                .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
876                .is_none()
877        );
878        assert!(
879            manager
880                .get_dex_pool_mint_event_signature(&DexType::UniswapV3)
881                .is_none()
882        );
883        assert!(
884            manager
885                .get_dex_pool_burn_event_signature(&DexType::UniswapV3)
886                .is_none()
887        );
888    }
889
890    #[rstest]
891    fn test_register_dex_for_subscriptions(registered_manager: DefiDataSubscriptionManager) {
892        // Should have all four event signatures
893        let signatures =
894            registered_manager.get_subscribed_dex_event_signatures(&DexType::UniswapV3);
895        assert_eq!(signatures.len(), 5);
896
897        // Each signature should be properly encoded
898        assert!(
899            registered_manager
900                .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
901                .is_some()
902        );
903        assert!(
904            registered_manager
905                .get_dex_pool_mint_event_signature(&DexType::UniswapV3)
906                .is_some()
907        );
908        assert!(
909            registered_manager
910                .get_dex_pool_burn_event_signature(&DexType::UniswapV3)
911                .is_some()
912        );
913    }
914
915    #[rstest]
916    fn test_subscribe_and_get_addresses(mut registered_manager: DefiDataSubscriptionManager) {
917        let pool_address = address!("1234567890123456789012345678901234567890");
918
919        // Subscribe to swap events
920        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
921
922        let addresses =
923            registered_manager.get_subscribed_dex_contract_addresses(&DexType::UniswapV3);
924        assert_eq!(addresses.len(), 1);
925        assert_eq!(addresses[0], pool_address);
926    }
927
928    #[rstest]
929    fn test_subscribe_to_unregistered_dex(mut manager: DefiDataSubscriptionManager) {
930        let pool_address = address!("1234567890123456789012345678901234567890");
931
932        // Try to subscribe without registering - should log warning but not panic
933        manager.subscribe_swaps(DexType::UniswapV3, pool_address);
934        manager.subscribe_mints(DexType::UniswapV3, pool_address);
935        manager.subscribe_burns(DexType::UniswapV3, pool_address);
936
937        // Should return empty results
938        let addresses = manager.get_subscribed_dex_contract_addresses(&DexType::UniswapV3);
939        assert_eq!(addresses.len(), 0);
940    }
941
942    #[rstest]
943    fn test_unsubscribe_removes_address(mut registered_manager: DefiDataSubscriptionManager) {
944        let pool_address = address!("1234567890123456789012345678901234567890");
945
946        // Subscribe
947        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
948
949        // Verify subscription
950        assert_eq!(
951            registered_manager
952                .get_subscribed_dex_contract_addresses(&DexType::UniswapV3)
953                .len(),
954            1
955        );
956
957        // Unsubscribe
958        registered_manager.unsubscribe_swaps(DexType::UniswapV3, pool_address);
959
960        // Verify removal
961        assert_eq!(
962            registered_manager
963                .get_subscribed_dex_contract_addresses(&DexType::UniswapV3)
964                .len(),
965            0
966        );
967    }
968
969    #[rstest]
970    fn test_get_event_signatures(registered_manager: DefiDataSubscriptionManager) {
971        let swap_sig = registered_manager.get_dex_pool_swap_event_signature(&DexType::UniswapV3);
972        let mint_sig = registered_manager.get_dex_pool_mint_event_signature(&DexType::UniswapV3);
973        let burn_sig = registered_manager.get_dex_pool_burn_event_signature(&DexType::UniswapV3);
974
975        // All should be Some and start with 0x
976        assert!(swap_sig.is_some() && swap_sig.unwrap().starts_with("0x"));
977        assert!(mint_sig.is_some() && mint_sig.unwrap().starts_with("0x"));
978        assert!(burn_sig.is_some() && burn_sig.unwrap().starts_with("0x"));
979    }
980
981    #[rstest]
982    fn test_active_event_signatures_only_include_subscribed_event_types(
983        mut registered_manager: DefiDataSubscriptionManager,
984    ) {
985        let pool_address = address!("1234567890123456789012345678901234567890");
986        let swap_sig = registered_manager
987            .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
988            .unwrap();
989        let collect_sig = registered_manager
990            .get_dex_pool_collect_event_signature(&DexType::UniswapV3)
991            .unwrap();
992
993        assert!(
994            registered_manager
995                .get_active_subscribed_dex_event_signatures(&DexType::UniswapV3)
996                .is_empty()
997        );
998
999        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
1000        assert_eq!(
1001            registered_manager.get_active_subscribed_dex_event_signatures(&DexType::UniswapV3),
1002            vec![swap_sig]
1003        );
1004
1005        registered_manager.subscribe_collects(DexType::UniswapV3, pool_address);
1006        let active_signatures =
1007            registered_manager.get_active_subscribed_dex_event_signatures(&DexType::UniswapV3);
1008
1009        assert_eq!(active_signatures.len(), 2);
1010        assert!(active_signatures.contains(&collect_sig));
1011    }
1012
1013    #[rstest]
1014    fn test_fee_protocol_events_are_active_only_when_subscribed(
1015        mut registered_manager: DefiDataSubscriptionManager,
1016    ) {
1017        let pool_address = address!("1234567890123456789012345678901234567890");
1018        registered_manager.register_dex_fee_protocol_events(
1019            DexType::UniswapV3,
1020            Some("SetFeeProtocol(uint8,uint8,uint8,uint8)"),
1021            Some("CollectProtocol(address,address,uint128,uint128)"),
1022        );
1023
1024        let update_sig = registered_manager
1025            .get_dex_pool_fee_protocol_update_event_signature(&DexType::UniswapV3)
1026            .unwrap();
1027        let collect_sig = registered_manager
1028            .get_dex_pool_fee_protocol_collect_event_signature(&DexType::UniswapV3)
1029            .unwrap();
1030
1031        registered_manager.subscribe_fee_protocol_updates(DexType::UniswapV3, pool_address);
1032        registered_manager.subscribe_fee_protocol_collects(DexType::UniswapV3, pool_address);
1033
1034        let active_signatures =
1035            registered_manager.get_active_subscribed_dex_event_signatures(&DexType::UniswapV3);
1036        let addresses =
1037            registered_manager.get_subscribed_dex_contract_addresses(&DexType::UniswapV3);
1038
1039        assert_eq!(addresses.len(), 1);
1040        assert!(addresses.contains(&pool_address));
1041        assert!(active_signatures.contains(&update_sig));
1042        assert!(active_signatures.contains(&collect_sig));
1043    }
1044
1045    #[rstest]
1046    fn test_same_event_demand_releases_with_final_owner(
1047        mut registered_manager: DefiDataSubscriptionManager,
1048    ) {
1049        let pool_address = address!("1234567890123456789012345678901234567890");
1050        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
1051        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
1052
1053        registered_manager.unsubscribe_swaps(DexType::UniswapV3, pool_address);
1054        let after_first =
1055            registered_manager.get_subscribed_pool_swap_addresses(&DexType::UniswapV3);
1056        registered_manager.unsubscribe_swaps(DexType::UniswapV3, pool_address);
1057
1058        assert_eq!(after_first, vec![pool_address]);
1059        assert!(
1060            registered_manager
1061                .get_subscribed_pool_swap_addresses(&DexType::UniswapV3)
1062                .is_empty()
1063        );
1064        assert!(!registered_manager.has_pool_event_subscriptions());
1065    }
1066
1067    #[rstest]
1068    fn test_unsubscribe_without_demand_is_ignored(
1069        mut registered_manager: DefiDataSubscriptionManager,
1070    ) {
1071        let pool_address = address!("1234567890123456789012345678901234567890");
1072        registered_manager.unsubscribe_swaps(DexType::UniswapV3, pool_address);
1073        registered_manager.subscribe_swaps(DexType::UniswapV3, pool_address);
1074
1075        assert_eq!(
1076            registered_manager.get_subscribed_pool_swap_addresses(&DexType::UniswapV3),
1077            vec![pool_address]
1078        );
1079    }
1080
1081    #[derive(Clone, Copy, Debug)]
1082    enum NarrowShape {
1083        Swaps,
1084        LiquidityUpdates,
1085        FeeCollects,
1086        FlashEvents,
1087    }
1088
1089    impl NarrowShape {
1090        fn subscribe(self, manager: &mut DefiDataSubscriptionManager, address: Address) {
1091            match self {
1092                Self::Swaps => manager.subscribe_swaps(DexType::UniswapV3, address),
1093                Self::LiquidityUpdates => {
1094                    manager.subscribe_mints(DexType::UniswapV3, address);
1095                    manager.subscribe_burns(DexType::UniswapV3, address);
1096                }
1097                Self::FeeCollects => manager.subscribe_collects(DexType::UniswapV3, address),
1098                Self::FlashEvents => manager.subscribe_flashes(DexType::UniswapV3, address),
1099            }
1100        }
1101
1102        fn unsubscribe(self, manager: &mut DefiDataSubscriptionManager, address: Address) {
1103            match self {
1104                Self::Swaps => manager.unsubscribe_swaps(DexType::UniswapV3, address),
1105                Self::LiquidityUpdates => {
1106                    manager.unsubscribe_mints(DexType::UniswapV3, address);
1107                    manager.unsubscribe_burns(DexType::UniswapV3, address);
1108                }
1109                Self::FeeCollects => manager.unsubscribe_collects(DexType::UniswapV3, address),
1110                Self::FlashEvents => manager.unsubscribe_flashes(DexType::UniswapV3, address),
1111            }
1112        }
1113
1114        fn signatures(self, manager: &DefiDataSubscriptionManager) -> Vec<String> {
1115            let dex = DexType::UniswapV3;
1116
1117            let signatures = match self {
1118                Self::Swaps => vec![manager.get_dex_pool_swap_event_signature(&dex)],
1119                Self::LiquidityUpdates => vec![
1120                    manager.get_dex_pool_mint_event_signature(&dex),
1121                    manager.get_dex_pool_burn_event_signature(&dex),
1122                ],
1123                Self::FeeCollects => vec![manager.get_dex_pool_collect_event_signature(&dex)],
1124                Self::FlashEvents => vec![manager.get_dex_pool_flash_event_signature(&dex)],
1125            };
1126
1127            signatures.into_iter().map(Option::unwrap).collect()
1128        }
1129    }
1130
1131    fn sorted(mut values: Vec<String>) -> Vec<String> {
1132        values.sort();
1133        values
1134    }
1135
1136    #[rstest]
1137    fn test_complete_pool_overlaps_narrow_shape(
1138        mut registered_manager: DefiDataSubscriptionManager,
1139        #[values(
1140            NarrowShape::Swaps,
1141            NarrowShape::LiquidityUpdates,
1142            NarrowShape::FeeCollects,
1143            NarrowShape::FlashEvents
1144        )]
1145        narrow: NarrowShape,
1146        #[values(true, false)] pool_first: bool,
1147    ) {
1148        let dex = DexType::UniswapV3;
1149        let pool_address = address!("1234567890123456789012345678901234567890");
1150        registered_manager.register_dex_fee_protocol_events(
1151            dex,
1152            Some("SetFeeProtocol(uint8,uint8,uint8,uint8)"),
1153            Some("CollectProtocol(address,address,uint128,uint128)"),
1154        );
1155        let all_signatures = sorted(registered_manager.get_subscribed_dex_event_signatures(&dex));
1156        let narrow_signatures = sorted(narrow.signatures(&registered_manager));
1157        registered_manager.subscribe_pool(dex, pool_address);
1158        narrow.subscribe(&mut registered_manager, pool_address);
1159
1160        if pool_first {
1161            registered_manager.unsubscribe_pool(dex, pool_address);
1162        } else {
1163            narrow.unsubscribe(&mut registered_manager, pool_address);
1164        }
1165
1166        let addresses_after_first = registered_manager.get_subscribed_dex_contract_addresses(&dex);
1167        let signatures_after_first =
1168            sorted(registered_manager.get_active_subscribed_dex_event_signatures(&dex));
1169
1170        if pool_first {
1171            narrow.unsubscribe(&mut registered_manager, pool_address);
1172        } else {
1173            registered_manager.unsubscribe_pool(dex, pool_address);
1174        }
1175
1176        assert_eq!(all_signatures.len(), 7);
1177        assert_eq!(addresses_after_first, vec![pool_address]);
1178
1179        if pool_first {
1180            assert_eq!(signatures_after_first, narrow_signatures);
1181        } else {
1182            assert_eq!(signatures_after_first, all_signatures);
1183        }
1184
1185        assert!(
1186            registered_manager
1187                .get_subscribed_dex_contract_addresses(&dex)
1188                .is_empty()
1189        );
1190        assert!(
1191            registered_manager
1192                .get_active_subscribed_dex_event_signatures(&dex)
1193                .is_empty()
1194        );
1195        assert!(!registered_manager.has_pool_event_subscriptions());
1196    }
1197
1198    #[rstest]
1199    fn test_get_combined_addresses_from_all_events(
1200        mut registered_manager: DefiDataSubscriptionManager,
1201    ) {
1202        let pool1 = address!("1111111111111111111111111111111111111111");
1203        let pool2 = address!("2222222222222222222222222222222222222222");
1204        let pool3 = address!("3333333333333333333333333333333333333333");
1205
1206        // Subscribe different pools to different events
1207        registered_manager.subscribe_swaps(DexType::UniswapV3, pool1);
1208        registered_manager.subscribe_mints(DexType::UniswapV3, pool2);
1209        registered_manager.subscribe_burns(DexType::UniswapV3, pool3);
1210
1211        // Should get all unique addresses
1212        let addresses =
1213            registered_manager.get_subscribed_dex_contract_addresses(&DexType::UniswapV3);
1214        assert_eq!(addresses.len(), 3);
1215        assert!(addresses.contains(&pool1));
1216        assert!(addresses.contains(&pool2));
1217        assert!(addresses.contains(&pool3));
1218    }
1219
1220    #[rstest]
1221    fn test_event_signature_encoding(registered_manager: DefiDataSubscriptionManager) {
1222        // Known event signature and its expected keccak256 hash
1223        // Swap(address,address,int256,int256,uint160,uint128,int24) for UniswapV3
1224        let swap_sig = registered_manager
1225            .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
1226            .unwrap();
1227
1228        // Should be properly formatted hex string
1229        assert!(swap_sig.starts_with("0x"));
1230        assert_eq!(swap_sig.len(), 66); // 0x + 64 hex chars (32 bytes)
1231
1232        // Verify it's valid hex
1233        let hex_part = &swap_sig[2..];
1234        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
1235    }
1236
1237    #[rstest]
1238    #[case(DexType::UniswapV3)]
1239    #[case(DexType::UniswapV2)]
1240    fn test_complete_subscription_workflow(#[case] dex_type: DexType) {
1241        let mut manager = DefiDataSubscriptionManager::new();
1242        let pool1 = address!("1111111111111111111111111111111111111111");
1243        let pool2 = address!("2222222222222222222222222222222222222222");
1244
1245        // Step 1: Register DEX
1246        manager.register_dex_for_subscriptions(
1247            dex_type,
1248            "Swap(address,uint256,uint256)",
1249            "Mint(address,uint256)",
1250            "Burn(address,uint256)",
1251            "Collect(address,uint256,uint256)",
1252            Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
1253        );
1254
1255        // Step 2: Subscribe to events
1256        manager.subscribe_swaps(dex_type, pool1);
1257        manager.subscribe_swaps(dex_type, pool2);
1258        manager.subscribe_mints(dex_type, pool1);
1259        manager.subscribe_burns(dex_type, pool2);
1260
1261        // Step 3: Verify subscriptions
1262        let addresses = manager.get_subscribed_dex_contract_addresses(&dex_type);
1263        assert_eq!(addresses.len(), 2);
1264        assert!(addresses.contains(&pool1));
1265        assert!(addresses.contains(&pool2));
1266
1267        // Step 4: Get event signatures
1268        let signatures = manager.get_subscribed_dex_event_signatures(&dex_type);
1269        assert_eq!(signatures.len(), 5);
1270
1271        // Step 5: Unsubscribe from some events
1272        manager.unsubscribe_swaps(dex_type, pool1);
1273        manager.unsubscribe_burns(dex_type, pool2);
1274
1275        // Step 6: Verify remaining subscriptions (only pool1 mint remains)
1276        let remaining = manager.get_subscribed_dex_contract_addresses(&dex_type);
1277        assert!(remaining.contains(&pool1)); // Still has mint subscription
1278        assert!(remaining.contains(&pool2)); // Still has swap subscription
1279    }
1280
1281    #[rstest]
1282    fn test_register_with_raw_signatures() {
1283        let mut manager = DefiDataSubscriptionManager::new();
1284
1285        // Register with raw event signatures
1286        manager.register_dex_for_subscriptions(
1287            DexType::UniswapV3,
1288            "Swap(address,address,int256,int256,uint160,uint128,int24)",
1289            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
1290            "Burn(address,int24,int24,uint128,uint256,uint256)",
1291            "Collect(address,address,int24,int24,uint128,uint128)",
1292            Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
1293        );
1294
1295        // Known keccak256 hashes for UniswapV3 events
1296        let swap_sig = manager
1297            .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
1298            .unwrap();
1299        let mint_sig = manager
1300            .get_dex_pool_mint_event_signature(&DexType::UniswapV3)
1301            .unwrap();
1302        let burn_sig = manager
1303            .get_dex_pool_burn_event_signature(&DexType::UniswapV3)
1304            .unwrap();
1305
1306        // Verify the exact hash values
1307        assert_eq!(
1308            swap_sig,
1309            "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67"
1310        );
1311        assert_eq!(
1312            mint_sig,
1313            "0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde"
1314        );
1315        assert_eq!(
1316            burn_sig,
1317            "0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c"
1318        );
1319    }
1320
1321    #[rstest]
1322    fn test_register_with_pre_encoded_signatures() {
1323        let mut manager = DefiDataSubscriptionManager::new();
1324
1325        // Register with pre-encoded keccak256 hashes (with 0x prefix)
1326        manager.register_dex_for_subscriptions(
1327            DexType::UniswapV3,
1328            "Swap(address,address,int256,int256,uint160,uint128,int24)",
1329            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
1330            "Burn(address,int24,int24,uint128,uint256,uint256)",
1331            "Collect(address,address,int24,int24,uint128,uint128)",
1332            Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
1333        );
1334
1335        // Should store them unchanged (normalized to lowercase)
1336        let swap_sig = manager
1337            .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
1338            .unwrap();
1339        let mint_sig = manager
1340            .get_dex_pool_mint_event_signature(&DexType::UniswapV3)
1341            .unwrap();
1342        let burn_sig = manager
1343            .get_dex_pool_burn_event_signature(&DexType::UniswapV3)
1344            .unwrap();
1345
1346        assert_eq!(
1347            swap_sig,
1348            "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67"
1349        );
1350        assert_eq!(
1351            mint_sig,
1352            "0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde"
1353        );
1354        assert_eq!(
1355            burn_sig,
1356            "0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c"
1357        );
1358    }
1359
1360    #[rstest]
1361    fn test_register_with_pre_encoded_signatures_no_prefix() {
1362        let mut manager = DefiDataSubscriptionManager::new();
1363
1364        // Register with pre-encoded hashes without 0x prefix
1365        manager.register_dex_for_subscriptions(
1366            DexType::UniswapV3,
1367            "Swap(address,address,int256,int256,uint160,uint128,int24)",
1368            "Mint(address,address,int24,int24,uint128,uint256,uint256)",
1369            "Burn(address,int24,int24,uint128,uint256,uint256)",
1370            "Collect(address,address,int24,int24,uint128,uint128)",
1371            Some("Flash(address,address,uint256,uint256,uint256,uint256)"),
1372        );
1373
1374        // Should add 0x prefix and normalize to lowercase
1375        let swap_sig = manager
1376            .get_dex_pool_swap_event_signature(&DexType::UniswapV3)
1377            .unwrap();
1378        let mint_sig = manager
1379            .get_dex_pool_mint_event_signature(&DexType::UniswapV3)
1380            .unwrap();
1381        let burn_sig = manager
1382            .get_dex_pool_burn_event_signature(&DexType::UniswapV3)
1383            .unwrap();
1384
1385        assert_eq!(
1386            swap_sig,
1387            "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67"
1388        );
1389        assert_eq!(
1390            mint_sig,
1391            "0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde"
1392        );
1393        assert_eq!(
1394            burn_sig,
1395            "0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c"
1396        );
1397    }
1398}