forked from alloy-rs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws.rs
More file actions
32 lines (24 loc) · 927 Bytes
/
Copy pathws.rs
File metadata and controls
32 lines (24 loc) · 927 Bytes
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
//! Example of using the WS provider to subscribe to new blocks.
use alloy::providers::{Provider, ProviderBuilder, WsConnect};
use eyre::Result;
use futures_util::StreamExt;
#[tokio::main]
async fn main() -> Result<()> {
// Create the provider.
let rpc_url = "wss://eth-mainnet.g.alchemy.com/v2/your-api-key";
let ws = WsConnect::new(rpc_url);
let provider = ProviderBuilder::new().on_ws(ws).await?;
// Subscribe to new blocks.
let sub = provider.subscribe_blocks().await?;
// Wait and take the next 4 blocks.
let mut stream = sub.into_stream().take(4);
println!("Awaiting block headers...");
// Take the stream and print the block number upon receiving a new block.
let handle = tokio::spawn(async move {
while let Some(header) = stream.next().await {
println!("Latest block number: {}", header.number);
}
});
handle.await?;
Ok(())
}