forked from alloy-rs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws_with_auth.rs
More file actions
53 lines (42 loc) · 1.86 KB
/
Copy pathws_with_auth.rs
File metadata and controls
53 lines (42 loc) · 1.86 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Example of using the WS provider with auth to subscribe to new blocks.
use alloy::{
providers::{Provider, ProviderBuilder, WsConnect},
transports::Authorization,
};
use eyre::Result;
use futures_util::StreamExt;
#[tokio::main]
async fn main() -> Result<()> {
// Create authorization methods.
let auth = Authorization::basic("username", "password");
let auth_bearer = Authorization::bearer("bearer-token");
// Create the WS connection object with authentication.
let rpc_url = "wss://your-ws-endpoint.com/";
let ws_basic = WsConnect::with_auth(rpc_url, Some(auth));
let ws_bearer = WsConnect::with_auth(rpc_url, Some(auth_bearer));
// Create the provider.
let provider_basic = ProviderBuilder::new().on_ws(ws_basic).await?;
let provider_bearer = ProviderBuilder::new().on_ws(ws_bearer).await?;
// Subscribe to new blocks.
let sub_basic = provider_basic.subscribe_blocks();
let sub_bearer = provider_bearer.subscribe_blocks();
// Wait and take the next 4 blocks.
let mut stream_basic = sub_basic.await?.into_stream().take(4);
let mut stream_bearer = sub_bearer.await?.into_stream().take(4);
println!("Awaiting blocks...");
// Take the basic stream and print the block number upon receiving a new block.
let basic_handle = tokio::spawn(async move {
while let Some(block) = stream_basic.next().await {
println!("Latest block number (basic): {}", block.header.number);
}
});
// Take the bearer stream and print the block number upon receiving a new block.
let bearer_handle = tokio::spawn(async move {
while let Some(block) = stream_bearer.next().await {
println!("Latest block number (bearer): {}", block.header.number);
}
});
// Wait for both tasks to complete.
let _ = tokio::try_join!(basic_handle, bearer_handle)?;
Ok(())
}