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

Commit

Permalink
feat: add ws subscribe
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Oct 16, 2023
1 parent 9d01a98 commit bbb5e40
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
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?;
while let Some(log) = transfers.next().await {
println!("Transfer: {:?}", log);
}

Ok(())
}

0 comments on commit bbb5e40

Please sign in to comment.