-
Notifications
You must be signed in to change notification settings - Fork 0
feat(utils): BlockWatcher
#108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c940c05
feat(utils): `BlockWatcher`
Evalir 2a9df76
feat: add helper type for subscribing to block number upates
Evalir 4fb7646
chore: do not use tokio streams, handle loop
Evalir 27e6144
chore: code review changes
Evalir bb99abf
chore: comments
Evalir File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| //! Host chain block watcher that subscribes to new blocks and tracks the | ||
| //! current host block number. | ||
|
|
||
| use alloy::{ | ||
| network::Ethereum, | ||
| providers::{Provider, RootProvider}, | ||
| transports::TransportError, | ||
| }; | ||
| use tokio::{ | ||
| sync::{broadcast::error::RecvError, watch}, | ||
| task::JoinHandle, | ||
| }; | ||
| use tracing::{debug, error, trace}; | ||
|
|
||
| /// Host chain block watcher that subscribes to new blocks and broadcasts | ||
| /// updates via a watch channel. | ||
| #[derive(Debug)] | ||
| pub struct BlockWatcher { | ||
| /// Watch channel responsible for broadcasting block number updates. | ||
| block_number: watch::Sender<u64>, | ||
|
|
||
| /// Host chain provider. | ||
| host_provider: RootProvider<Ethereum>, | ||
| } | ||
|
|
||
| impl BlockWatcher { | ||
| /// Creates a new [`BlockWatcher`] with the given provider and initial | ||
| /// block number. | ||
| pub fn new(host_provider: RootProvider<Ethereum>, initial: u64) -> Self { | ||
| Self { | ||
| block_number: watch::channel(initial).0, | ||
| host_provider, | ||
| } | ||
| } | ||
|
|
||
| /// Creates a new [`BlockWatcher`], fetching the current block number first. | ||
| pub async fn with_current_block( | ||
| host_provider: RootProvider<Ethereum>, | ||
| ) -> Result<Self, TransportError> { | ||
| let block_number = host_provider.get_block_number().await?; | ||
| Ok(Self::new(host_provider, block_number)) | ||
| } | ||
|
|
||
| /// Subscribe to block number updates. | ||
| pub fn subscribe(&self) -> SharedBlockNumber { | ||
| self.block_number.subscribe().into() | ||
| } | ||
|
|
||
| /// Spawns the block watcher task. | ||
| pub fn spawn(self) -> (SharedBlockNumber, JoinHandle<()>) { | ||
| (self.subscribe(), tokio::spawn(self.task_future())) | ||
| } | ||
|
|
||
| async fn task_future(self) { | ||
| let mut sub = match self.host_provider.subscribe_blocks().await { | ||
| Ok(sub) => sub, | ||
| Err(error) => { | ||
| error!(%error); | ||
| return; | ||
| } | ||
| }; | ||
|
|
||
| debug!("subscribed to host chain blocks"); | ||
|
|
||
| loop { | ||
| match sub.recv().await { | ||
| Ok(header) => { | ||
| let block_number = header.number; | ||
| self.block_number.send_replace(block_number); | ||
| trace!(block_number, "updated host block number"); | ||
| } | ||
| Err(RecvError::Lagged(missed)) => { | ||
Evalir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| debug!(%missed, "block subscription lagged"); | ||
| } | ||
| Err(RecvError::Closed) => { | ||
| debug!("block subscription closed"); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// A shared block number, wrapped in a [`tokio::sync::watch`] Receiver. | ||
| /// | ||
| /// The block number is periodically updated by a [`BlockWatcher`] task, and | ||
| /// can be read or awaited for changes. This allows multiple tasks to observe | ||
| /// block number updates. | ||
| #[derive(Debug, Clone)] | ||
| pub struct SharedBlockNumber(watch::Receiver<u64>); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what does this type provide that
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It makes using the |
||
|
|
||
| impl From<watch::Receiver<u64>> for SharedBlockNumber { | ||
| fn from(inner: watch::Receiver<u64>) -> Self { | ||
| Self(inner) | ||
| } | ||
| } | ||
|
|
||
| impl SharedBlockNumber { | ||
| /// Get the current block number. | ||
| pub fn get(&self) -> u64 { | ||
| *self.0.borrow() | ||
| } | ||
|
|
||
| /// Wait for the block number to change, then return the new value. | ||
| /// | ||
| /// This is implemented using [`Receiver::changed`]. | ||
| /// | ||
| /// [`Receiver::changed`]: tokio::sync::watch::Receiver::changed | ||
| pub async fn changed(&mut self) -> Result<u64, watch::error::RecvError> { | ||
| self.0.changed().await?; | ||
| Ok(*self.0.borrow_and_update()) | ||
| } | ||
|
|
||
| /// Wait for the block number to reach at least `target`. | ||
| /// | ||
| /// Returns the block number once it is >= `target`. | ||
| pub async fn wait_until(&mut self, target: u64) -> Result<u64, watch::error::RecvError> { | ||
| self.0.wait_for(|&n| n >= target).await.map(|r| *r) | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.