Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

feat: add ws subscribe example #2638

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions book/events/logs-and-filtering.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@

```rust
{{#include ../../examples/events/examples/filtering.rs}}
{{#include ../../examples/events/examples/subscribe.rs}}
```
2 changes: 1 addition & 1 deletion examples/events/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ rust-version.workspace = true
edition.workspace = true

[dev-dependencies]
ethers = { workspace = true, features = ["rustls"] }
ethers = { workspace = true, features = ["rustls", "ws"] }

tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }

Expand Down
29 changes: 29 additions & 0 deletions examples/events/examples/subscribe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use ethers::prelude::*;
use eyre::Result;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

const WSS_URL: &str = "wss://mainnet.infura.io/ws/v3/c60b0bb42f8a4c6481ecd229eddaca27";

#[derive(Clone, Debug, Serialize, Deserialize, EthEvent)]
pub struct Transfer {
#[ethevent(indexed)]
pub from: Address,
#[ethevent(indexed)]
pub to: Address,
pub tokens: U256,
}

/// This example shows how to subscribe to events using the Ws transport for a specific event
#[tokio::main]
async fn main() -> Result<()> {
let provider = Provider::<Ws>::connect(WSS_URL).await?;
let provider = Arc::new(provider);
let event = Transfer::new::<_, Provider<Ws>>(Filter::new(), Arc::clone(&provider));
let mut transfers = event.subscribe().await?.take(5);
while let Some(log) = transfers.next().await {
println!("Transfer: {:?}", log);
}

Ok(())
}