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

Jepsen/mdbook #2297

Merged
merged 7 commits into from
Apr 25, 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
13 changes: 7 additions & 6 deletions book/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@
- [Events](./contracts/events.md)
- [Events with meta](./contracts/events-with-meta.md)
- [Methods](contracts/methods.md)
- [Events]()
- [Logs and filtering]()
- [Events](./events/events.md)
- [Logs and filtering](events/logs-and-filtering.md)
- [Solidity topics]()
- [Subscriptions]()
- [Watch blocks]()
- [Subscribe events by type]()
- [Subscribe logs]()
- [Subscriptions](./subscriptions/subscriptions.md)
- [Watch blocks](./subscriptions/watch-blocks.md)
- [Subscribe events by type](./subscriptions/events-by-type.md)
- [Subscribe logs](./subscriptions/logs.md)
- [Mulitple subscriptions](./subscriptions/multiple-subscriptions.md)
- [Queries]()
- [Blocks]()
- [Contracts]()
Expand Down
105 changes: 105 additions & 0 deletions book/events/events.md
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)},
```
5 changes: 5 additions & 0 deletions book/events/logs-and-filtering.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Logs and filtering

```rust
{{#include ../../examples/events/examples/filtering.rs}}
```
5 changes: 5 additions & 0 deletions book/subscriptions/events-by-type.md
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}}
```
39 changes: 39 additions & 0 deletions book/subscriptions/logs.md
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}}
```
58 changes: 58 additions & 0 deletions book/subscriptions/multiple-subscriptions.md
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.
60 changes: 60 additions & 0 deletions book/subscriptions/subscriptions.md
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,};
0xJepsen marked this conversation as resolved.
Show resolved Hide resolved
```

### 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.
37 changes: 37 additions & 0 deletions book/subscriptions/watch-blocks.md
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}}
```