Skip to content

Commit

Permalink
feat: HTTP with auth header
Browse files Browse the repository at this point in the history
  • Loading branch information
yash-atreya committed Oct 28, 2024
1 parent 6512656 commit 39104f4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ This repository contains the following examples:
- [x] Providers
- [x] [Builder](./examples/providers/examples/builder.rs)
- [x] [Builtin](./examples/providers/examples/builtin.rs)
- [x] [HTTP with authentication](./examples/providers/examples/http_with_auth.rs)
- [x] [HTTP](./examples/providers/examples/http.rs)
- [x] [IPC](./examples/providers/examples/ipc.rs)
- [x] [WS](./examples/providers/examples/ws.rs)
Expand Down
40 changes: 40 additions & 0 deletions examples/providers/examples/http_with_auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! Example of using the reqwest HTTP client with an AUTHORIZATION header to get the latest block
//! number.
use alloy::{
providers::{Provider, ProviderBuilder},
rpc::client::RpcClient,
transports::http::{
reqwest::{
header::{HeaderMap, HeaderValue, AUTHORIZATION},
Client,
},
Http,
},
};
use eyre::Result;

#[tokio::main]
async fn main() -> Result<()> {
// Set the AUTHORIZATION header.
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("deadbeef"));

// Create the reqwest::Client with the AUTHORIZATION header.
let client_with_auth = Client::builder().default_headers(headers).build()?;

// Create the HTTP transport.
let rpc_url = "https://eth.merkle.io".parse()?;
let http = Http::with_client(client_with_auth, rpc_url);
let rpc_client = RpcClient::new(http, false);

// Create a provider with the HTTP transport.
let provider = ProviderBuilder::new().on_client(rpc_client);

// Get latest block number.
let latest_block = provider.get_block_number().await?;

println!("Latest block number: {latest_block}");

Ok(())
}

0 comments on commit 39104f4

Please sign in to comment.