This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 794
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* events * events * event contnent * subscriptions * remove DS-Store * clean up sections * Jame's Feedback
- Loading branch information
Showing
8 changed files
with
316 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
# Ethers-rs: Working with Events | ||
|
||
In this section we will discuss how to monitor, subscribe, and listen to events using the ethers-rs library. Events are an essential part of smart contract development, as they allow you to track specific occurrences on the blockchain, such as transactions, state changes, or function calls. | ||
|
||
## Overview | ||
|
||
ethers-rs provides a simple and efficient way to interact with events emitted by smart contracts. You can listen to events, filter them based on certain conditions, and subscribe to event streams for real-time updates. The key components you will work with are: | ||
|
||
1. Event: A struct representing an event emitted by a smart contract. | ||
2. EventWatcher: A struct that allows you to monitor and filter events. | ||
3. SubscriptionStream: A stream of events you can subscribe to for real-time updates. | ||
|
||
## Getting Started | ||
|
||
Before diving into event handling, ensure you have ethers-rs added to your project's dependencies in Cargo.toml: | ||
|
||
```toml | ||
[dependencies] | ||
ethers = { version = "2.0.0.", features = ["full"] } | ||
``` | ||
|
||
Now, let's import the necessary components from the ethers-rs library: | ||
|
||
```rust | ||
use ethers::{ | ||
prelude::contract::{Contract, EthEvent}, | ||
}; | ||
``` | ||
|
||
### Listening to Events | ||
|
||
To listen to events, you'll need to instantiate a Contract object and use the event method to create an Event struct. You'll also need to define a struct that implements the EthEvent trait, representing the specific event you want to listen to. | ||
|
||
Consider a simple smart contract that emits an event called ValueChanged: | ||
|
||
```solidity | ||
pragma solidity ^0.8.0; | ||
contract SimpleStorage { | ||
uint256 public value; | ||
event ValueChanged(uint256 newValue); | ||
function setValue(uint256 _value) public { | ||
value = _value; | ||
emit ValueChanged(_value); | ||
} | ||
} | ||
``` | ||
|
||
First, define a struct representing the ValueChanged event: | ||
|
||
```rust | ||
#[derive(Debug, Clone, EthEvent)] | ||
pub struct ValueChanged { | ||
pub new_value: U256, | ||
} | ||
``` | ||
|
||
Then, create an instance of the Contract object and listen for the ValueChanged event: | ||
|
||
```rust | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
let provider = Provider::<Http>::try_from("http://localhost:8545")?; | ||
let contract_address = "0xcontract_address_here".parse()?; | ||
let contract = Contract::from_json(provider, | ||
contract_address, | ||
include_bytes!("../contracts/abis/SimpleStorage.json"))?; | ||
|
||
let event = contract.event::<ValueChanged>()?; | ||
|
||
// Your code to handle the event goes here. | ||
|
||
Ok(()) | ||
|
||
} | ||
``` | ||
|
||
### Filtering Events | ||
|
||
You can filter events based on specific conditions using the EventWatcher struct. To create an EventWatcher, call the watcher method on your Event object: | ||
|
||
```rust | ||
let watcher = event.watcher().from_block(5).to_block(10); | ||
``` | ||
|
||
In this example, the EventWatcher will only monitor events from block 5 to block 10. | ||
|
||
### Subscribing to Events | ||
|
||
To receive real-time updates for an event, create a SubscriptionStream by calling the subscribe method on your EventWatcher: | ||
|
||
```rust | ||
let mut stream = watcher.subscribe().await?; | ||
``` | ||
|
||
You can now listen to events as they are emitted by the smart contract: | ||
|
||
```rust | ||
while let Some(event) = stream.next().await { | ||
match event { | ||
Ok(log) => {println!("New event: {:?}", log)}, | ||
Err(e) => {println!("Error: {:?}", e)}, | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Logs and filtering | ||
|
||
```rust | ||
{{#include ../../examples/events/examples/filtering.rs}} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Subscribe events by type | ||
|
||
```rust | ||
{{#include ../../examples/subscriptions/examples/subscribe_events_by_type.rs}} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Subscribing to Logs | ||
|
||
To subscribe to logs, create a Filter object that specifies the criteria for the logs you want to listen to. Then, pass the filter to the Provider's subscribe_logs method: | ||
|
||
```rust | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
let provider = Provider::<Http>::try_from("http://localhost:8545")?; | ||
|
||
let filter = Filter::new().address("0xcontract_address_here".parse()?); | ||
|
||
let mut stream = provider.subscribe_logs(filter).await?; | ||
|
||
// Your code to handle logs goes here. | ||
|
||
Ok(()) | ||
|
||
} | ||
``` | ||
|
||
You can now listen to logs that match your filter criteria: | ||
|
||
```rust | ||
while let Some(log) = stream.next().await { | ||
match log { | ||
Ok(log) => { | ||
println!("New log: {:?}", log); | ||
} | ||
Err(e) => { | ||
eprintln!("Error: {:?}", e); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Here is another example of subscribing to logs: | ||
|
||
```rust | ||
{{#include ../../examples/subscriptions/examples/subscribe_logs.rs}} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Mulitple Multiple Subscriptions | ||
|
||
You may need to handle multiple subscriptions simultaneously in your application. To manage multiple SubscriptionStreams, you can use the futures crate to efficiently process updates from all streams concurrently: | ||
|
||
```toml | ||
[dependencies] | ||
futures = "0.3" | ||
``` | ||
|
||
Then, import the necessary components: | ||
|
||
```rust | ||
use futures::{stream, StreamExt, TryStreamExt}; | ||
``` | ||
|
||
Create multiple subscription streams and merge them into a single stream using the stream::select_all function: | ||
|
||
```rust | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
// Create multiple subscription streams. | ||
let mut block_stream = provider.subscribe_blocks().await?; | ||
let mut log_stream = provider.subscribe_logs(filter).await?; | ||
let mut event_stream = watcher.subscribe().await?; | ||
|
||
// Merge the streams into a single stream. | ||
let mut combined_stream = stream::select_all(vec![ | ||
block_stream.map_ok(|block| EventType::Block(block)), | ||
log_stream.map_ok(|log| EventType::Log(log)), | ||
event_stream.map_ok(|event| EventType::Event(event)), | ||
]); | ||
|
||
// Your code to handle the events goes here. | ||
|
||
Ok(()) | ||
|
||
} | ||
``` | ||
|
||
Now, you can listen to updates from all the subscription streams concurrently: | ||
|
||
```rust | ||
while let Some(event) = combined_stream.next().await { | ||
match event { | ||
Ok(event) => match event { | ||
EventType::Block(block) => println!("New block: {:?}", block), | ||
EventType::Log(log) => println!("New log: {:?}", log), | ||
EventType::Event(event) => println!("New event: {:?}", event), | ||
}, | ||
Err(e) => { | ||
eprintln!("Error: {:?}", e); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
This approach allows you to efficiently handle multiple subscriptions in your application and react to various network activities in a unified manner. | ||
|
||
By leveraging the powerful subscription capabilities of ethers-rs, you can create responsive and dynamic applications that stay up-to-date with the latest events on the Ethereum network. The library's flexibility and ease of use make it an ideal choice for developers looking to build robust and performant applications that interact with smart contracts and the Ethereum blockchain. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
## Ethers-rs: Subscriptions | ||
|
||
Here we will discuss how to use `ethers-rs` to subscribe and listen to blocks, events, and logs. Subscriptions provide a way to receive real-time updates on various activities on the Ethereum blockchain, allowing you to monitor the network and react to changes as they happen. | ||
|
||
## Overview | ||
|
||
ethers-rs offers a convenient way to work with subscriptions, enabling you to listen to new blocks, transaction receipts, and logs. The main components you will work with are: | ||
|
||
1. Provider: The main struct used to interact with the Ethereum network. | ||
2. SubscriptionStream: A stream of updates you can subscribe to for real-time notifications. | ||
|
||
## Getting Started | ||
|
||
Before working with subscriptions, make sure you have ethers-rs added to your project's dependencies in Cargo.toml: | ||
|
||
```toml | ||
[dependencies] | ||
ethers = { version = "2.0.0", features = ["full"] } | ||
``` | ||
|
||
Next, import the necessary components from the ethers-rs library: | ||
|
||
```rust | ||
use ethers::{prelude::\*,types::H256,}; | ||
``` | ||
|
||
### Subscribing to Events | ||
|
||
As we discussed in the previous section on events, you can subscribe to specific events emitted by smart contracts using the EventWatcher struct. To create a SubscriptionStream, call the subscribe method on your EventWatcher: | ||
|
||
```rust | ||
let mut stream = watcher.subscribe().await?; | ||
``` | ||
|
||
Now, you can listen to events as they are emitted by the smart contract: | ||
|
||
```rust | ||
while let Some(event) = stream.next().await { | ||
match event { | ||
Ok(log) => { | ||
println!("New event: {:?}", log); | ||
} | ||
Err(e) => { | ||
eprintln!("Error: {:?}", e); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
By using the subscription features provided by ethers-rs, you can efficiently monitor and react to various activities on the Ethereum network. Subscriptions are a powerful tool for building responsive and dynamic applications that can interact with smart contracts and stay up-to-date with the latest network events. | ||
|
||
### Unsubscribing from Subscriptions | ||
|
||
In some cases, you may want to stop listening to a subscription. To do this, simply drop the SubscriptionStream: | ||
|
||
```rust | ||
drop(stream); | ||
``` | ||
|
||
This will stop the stream from receiving any further updates. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# Subscribing to New Blocks | ||
|
||
To subscribe to new blocks, create a Provider instance and call the subscribe_blocks method: | ||
|
||
```rust | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
let provider = Provider::<Http>::try_from("http://localhost:8545")?; | ||
|
||
let mut stream = provider.subscribe_blocks().await?; | ||
|
||
// Your code to handle new blocks goes here. | ||
|
||
Ok(()) | ||
|
||
} | ||
``` | ||
|
||
You can now listen to new blocks as they are mined: | ||
|
||
```rust | ||
while let Some(block) = stream.next().await { | ||
match block { | ||
Ok(block) => { | ||
println!("New block: {:?}", block); | ||
} | ||
Err(e) => { | ||
eprintln!("Error: {:?}", e); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Here is another example of subscribing to new blocks: | ||
|
||
```rust | ||
{{#include ../../examples/subscriptions/examples/subscribe_blocks.rs}} | ||
``` |