Skip to main content

evm_fork_cache_hypersync/
hypersync_source.rs

1use async_trait::async_trait;
2use futures::StreamExt;
3use hypersync_client::{Client, HeightStreamEvent, net_types::Query};
4use tokio::sync::mpsc;
5use tokio_stream::wrappers::ReceiverStream;
6
7use crate::{ChainDataSource, ChainHeightStream, SourceError, SourcePage};
8
9/// Production chain-data boundary backed by Envio's native Rust client.
10#[derive(Clone)]
11pub struct HyperSyncDataSource {
12    chain_id: u64,
13    client: Client,
14}
15
16impl HyperSyncDataSource {
17    /// Configure a HyperSync client for one chain.
18    ///
19    /// # Errors
20    ///
21    /// Returns [`SourceError::Request`] when the Envio client builder rejects
22    /// the chain/token configuration.
23    pub fn new(chain_id: u64, api_token: impl ToString) -> Result<Self, SourceError> {
24        let client = Client::builder()
25            .chain_id(chain_id)
26            .api_token(api_token)
27            .build()
28            .map_err(|error| SourceError::request(error.to_string()))?;
29        Ok(Self { chain_id, client })
30    }
31
32    /// Configured EVM chain id.
33    pub fn chain_id(&self) -> u64 {
34        self.chain_id
35    }
36
37    /// Subscribe to reconnecting HyperSync archive-height notifications.
38    pub fn stream_height(&self) -> mpsc::Receiver<HeightStreamEvent> {
39        self.client.stream_height()
40    }
41}
42
43#[async_trait]
44impl ChainDataSource for HyperSyncDataSource {
45    async fn height(&self) -> Result<u64, SourceError> {
46        self.client
47            .get_height()
48            .await
49            .map_err(|error| SourceError::request(error.to_string()))
50    }
51
52    async fn query(&self, query: Query) -> Result<SourcePage, SourceError> {
53        let response = self
54            .client
55            .get(&query)
56            .await
57            .map_err(|error| SourceError::request(error.to_string()))?;
58        Ok(SourcePage::new(
59            response.next_block,
60            response.data.blocks.into_iter().flatten().collect(),
61            response.data.logs.into_iter().flatten().collect(),
62        )
63        .with_archive_height(response.archive_height)
64        .with_rollback_guard(response.rollback_guard))
65    }
66
67    fn height_stream(&self) -> Option<ChainHeightStream> {
68        let updates = ReceiverStream::new(self.stream_height()).filter_map(|event| async move {
69            match event {
70                HeightStreamEvent::Height(height) => Some(height),
71                HeightStreamEvent::Connected | HeightStreamEvent::Reconnecting { .. } => None,
72            }
73        });
74        Some(Box::pin(updates))
75    }
76}