forked from alloy-rs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe_blocks.rs
37 lines (29 loc) · 1.09 KB
/
subscribe_blocks.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//! Example of subscribing to blocks and watching block headers by polling.
use alloy::{
node_bindings::Anvil,
providers::{Provider, ProviderBuilder, WsConnect},
};
use eyre::Result;
use futures_util::{stream, StreamExt};
#[tokio::main]
async fn main() -> Result<()> {
// Spin up a local Anvil node.
// Ensure `anvil` is available in $PATH.
let anvil = Anvil::new().block_time(1).try_spawn()?;
// Create a provider.
let ws = WsConnect::new(anvil.ws_endpoint());
let provider = ProviderBuilder::new().on_ws(ws).await?;
// Subscribe to blocks.
let subscription = provider.subscribe_blocks().await?;
let mut stream = subscription.into_stream().take(2);
while let Some(block) = stream.next().await {
println!("Received block number: {}", block.header.number);
}
// Poll for block headers.
let poller = provider.watch_blocks().await?;
let mut stream = poller.into_stream().flat_map(stream::iter).take(2);
while let Some(block_hash) = stream.next().await {
println!("Polled for block header: {block_hash:?}");
}
Ok(())
}