Skip to content

Commit

Permalink
feat(providers): ws_with_auth
Browse files Browse the repository at this point in the history
  • Loading branch information
yash-atreya committed Mar 18, 2024
1 parent 6efda72 commit 8e0af98
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
3 changes: 0 additions & 3 deletions examples/providers/examples/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ async fn main() -> Result<()> {
let rpc_url = "wss://eth-mainnet.g.alchemy.com/v2/your-api-key";

let ws_transport = WsConnect::new(rpc_url);
// To use auth
// let auth = alloy_transport::Authorization::bearer("token");
// let ws_transport = WsConnect::with_auth(rpc_url, Some(auth));

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

Expand Down
46 changes: 46 additions & 0 deletions examples/providers/examples/ws_with_auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! Example of using the WS provider with auth to subscribe to new blocks.
use alloy_network::Ethereum;
use alloy_provider::{Provider, RootProvider};
use alloy_rpc_client::{RpcClient, WsConnect};
use alloy_transport::Authorization;
use eyre::Result;
use futures_util::StreamExt;

#[tokio::main]
async fn main() -> Result<()> {
let rpc_url = "wss://your-ws-endpoint.com/";

let auth = Authorization::basic("username", "password");
let auth_bearer = Authorization::bearer("bearer-token");

let ws_transport_basic = WsConnect::with_auth(rpc_url, Some(auth));

let ws_transport_bearer = WsConnect::with_auth(rpc_url, Some(auth_bearer));

let rpc_client_basic = RpcClient::connect_pubsub(ws_transport_basic).await?;

let rpc_client_bearer = RpcClient::connect_pubsub(ws_transport_bearer).await?;

let provider_basic = RootProvider::<Ethereum, _>::new(rpc_client_basic);

let provider_bearer = RootProvider::<Ethereum, _>::new(rpc_client_bearer);

let sub_basic = provider_basic.subscribe_blocks();
let sub_bearer = provider_bearer.subscribe_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...");

while let Some(block) = stream_basic.next().await {
println!("From basic {:?}", block.header.number);
}

while let Some(block) = stream_bearer.next().await {
println!("From bearer {:?}", block.header.number);
}

Ok(())
}

0 comments on commit 8e0af98

Please sign in to comment.