Sitelet https://github.com/isSerge/examples/commit/8e0af98f514779361d297ac70eeda8335de6c518
Skip to content

Commit 8e0af98

Browse files
committed
feat(providers): ws_with_auth
1 parent 6efda72 commit 8e0af98

2 files changed

Lines changed: 46 additions & 3 deletions

File tree

‎examples/providers/examples/ws.rs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ async fn main() -> Result<()> {
1111
let rpc_url = "wss://eth-mainnet.g.alchemy.com/v2/your-api-key";
1212

1313
let ws_transport = WsConnect::new(rpc_url);
14-
// To use auth
15-
// let auth = alloy_transport::Authorization::bearer("token");
16-
// let ws_transport = WsConnect::with_auth(rpc_url, Some(auth));
1714

1815
let rpc_client = RpcClient::connect_pubsub(ws_transport).await?;
1916

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//! Example of using the WS provider with auth to subscribe to new blocks.
2+
3+
use alloy_network::Ethereum;
4+
use alloy_provider::{Provider, RootProvider};
5+
use alloy_rpc_client::{RpcClient, WsConnect};
6+
use alloy_transport::Authorization;
7+
use eyre::Result;
8+
use futures_util::StreamExt;
9+
10+
#[tokio::main]
11+
async fn main() -> Result<()> {
12+
let rpc_url = "wss://your-ws-endpoint.com/";
13+
14+
let auth = Authorization::basic("username", "password");
15+
let auth_bearer = Authorization::bearer("bearer-token");
16+
17+
let ws_transport_basic = WsConnect::with_auth(rpc_url, Some(auth));
18+
19+
let ws_transport_bearer = WsConnect::with_auth(rpc_url, Some(auth_bearer));
20+
21+
let rpc_client_basic = RpcClient::connect_pubsub(ws_transport_basic).await?;
22+
23+
let rpc_client_bearer = RpcClient::connect_pubsub(ws_transport_bearer).await?;
24+
25+
let provider_basic = RootProvider::<Ethereum, _>::new(rpc_client_basic);
26+
27+
let provider_bearer = RootProvider::<Ethereum, _>::new(rpc_client_bearer);
28+
29+
let sub_basic = provider_basic.subscribe_blocks();
30+
let sub_bearer = provider_bearer.subscribe_blocks();
31+
32+
let mut stream_basic = sub_basic.await?.into_stream().take(4);
33+
let mut stream_bearer = sub_bearer.await?.into_stream().take(4);
34+
35+
println!("Awaiting blocks...");
36+
37+
while let Some(block) = stream_basic.next().await {
38+
println!("From basic {:?}", block.header.number);
39+
}
40+
41+
while let Some(block) = stream_bearer.next().await {
42+
println!("From bearer {:?}", block.header.number);
43+
}
44+
45+
Ok(())
46+
}

0 commit comments

Comments
 (0)