2021-12-19 04:28:38 +00:00
|
|
|
#![allow(clippy::return_self_not_must_use)]
|
|
|
|
|
2021-06-05 17:08:33 +00:00
|
|
|
use crate::{JsonRpcClient, Middleware, PinBoxFut, Provider, ProviderError};
|
|
|
|
use ethers_core::types::{Transaction, TxHash, U256};
|
2021-10-29 12:29:35 +00:00
|
|
|
use futures_core::{stream::Stream, Future};
|
|
|
|
use futures_util::{stream, stream::FuturesUnordered, FutureExt, StreamExt};
|
2020-06-15 08:46:07 +00:00
|
|
|
use pin_project::pin_project;
|
2020-12-24 20:23:05 +00:00
|
|
|
use serde::{de::DeserializeOwned, Serialize};
|
2020-06-15 08:46:07 +00:00
|
|
|
use std::{
|
2021-10-29 12:29:35 +00:00
|
|
|
collections::VecDeque,
|
2020-12-24 20:23:05 +00:00
|
|
|
fmt::Debug,
|
2020-06-15 08:46:07 +00:00
|
|
|
pin::Pin,
|
|
|
|
task::{Context, Poll},
|
|
|
|
time::Duration,
|
|
|
|
vec::IntoIter,
|
|
|
|
};
|
2020-06-21 07:17:11 +00:00
|
|
|
|
2021-08-23 09:56:44 +00:00
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
|
|
use futures_timer::Delay;
|
|
|
|
#[cfg(target_arch = "wasm32")]
|
|
|
|
use wasm_timer::Delay;
|
|
|
|
|
2020-06-21 07:17:11 +00:00
|
|
|
// https://github.com/tomusdrw/rust-web3/blob/befcb2fb8f3ca0a43e3081f68886fa327e64c8e6/src/api/eth_filter.rs#L20
|
2020-06-21 08:09:19 +00:00
|
|
|
pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Send + Unpin {
|
2020-06-21 07:17:11 +00:00
|
|
|
stream::unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
|
|
|
|
}
|
2020-06-15 08:46:07 +00:00
|
|
|
|
2020-06-22 08:44:08 +00:00
|
|
|
/// The default polling interval for filters and pending transactions
|
|
|
|
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(7000);
|
2020-06-15 08:46:07 +00:00
|
|
|
|
2022-08-03 16:21:55 +00:00
|
|
|
/// The polling interval to use for local endpoints, See [`crate::is_local_endpoint()`]
|
|
|
|
pub const DEFAULT_LOCAL_POLL_INTERVAL: Duration = Duration::from_millis(100);
|
|
|
|
|
2020-09-23 08:04:54 +00:00
|
|
|
enum FilterWatcherState<'a, R> {
|
2020-06-15 08:46:07 +00:00
|
|
|
WaitForInterval,
|
2020-09-23 08:04:54 +00:00
|
|
|
GetFilterChanges(PinBoxFut<'a, Vec<R>>),
|
2020-06-15 08:46:07 +00:00
|
|
|
NextItem(IntoIter<R>),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[must_use = "filters do nothing unless you stream them"]
|
2021-03-31 08:21:20 +00:00
|
|
|
/// Streams data from an installed filter via `eth_getFilterChanges`
|
2022-06-29 22:26:37 +00:00
|
|
|
#[pin_project]
|
2020-09-23 08:04:54 +00:00
|
|
|
pub struct FilterWatcher<'a, P, R> {
|
|
|
|
/// The filter's installed id on the ethereum node
|
|
|
|
pub id: U256,
|
2020-06-15 08:46:07 +00:00
|
|
|
|
2020-09-23 08:04:54 +00:00
|
|
|
provider: &'a Provider<P>,
|
2020-06-15 08:46:07 +00:00
|
|
|
|
|
|
|
// The polling interval
|
2020-06-21 07:17:11 +00:00
|
|
|
interval: Box<dyn Stream<Item = ()> + Send + Unpin>,
|
2022-06-29 22:26:37 +00:00
|
|
|
/// statemachine driven by the Stream impl
|
2020-09-23 08:04:54 +00:00
|
|
|
state: FilterWatcherState<'a, R>,
|
2020-06-15 08:46:07 +00:00
|
|
|
}
|
|
|
|
|
2020-09-23 08:04:54 +00:00
|
|
|
impl<'a, P, R> FilterWatcher<'a, P, R>
|
2020-06-15 08:46:07 +00:00
|
|
|
where
|
2020-09-23 08:04:54 +00:00
|
|
|
P: JsonRpcClient,
|
2020-11-30 09:33:06 +00:00
|
|
|
R: Send + Sync + DeserializeOwned,
|
2020-06-15 08:46:07 +00:00
|
|
|
{
|
|
|
|
/// Creates a new watcher with the provided factory and filter id.
|
2020-09-23 08:04:54 +00:00
|
|
|
pub fn new<T: Into<U256>>(id: T, provider: &'a Provider<P>) -> Self {
|
2020-06-15 08:46:07 +00:00
|
|
|
Self {
|
|
|
|
id: id.into(),
|
2020-06-22 08:44:08 +00:00
|
|
|
interval: Box::new(interval(DEFAULT_POLL_INTERVAL)),
|
2020-06-15 08:46:07 +00:00
|
|
|
state: FilterWatcherState::WaitForInterval,
|
2020-09-23 08:04:54 +00:00
|
|
|
provider,
|
2020-06-15 08:46:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-23 08:04:54 +00:00
|
|
|
/// Sets the stream's polling interval
|
|
|
|
pub fn interval(mut self, duration: Duration) -> Self {
|
2020-06-22 08:44:08 +00:00
|
|
|
self.interval = Box::new(interval(duration));
|
2020-06-15 08:46:07 +00:00
|
|
|
self
|
|
|
|
}
|
2020-09-23 08:04:54 +00:00
|
|
|
|
|
|
|
/// Alias for Box::pin, must be called in order to pin the stream and be able
|
|
|
|
/// to call `next` on it.
|
|
|
|
pub fn stream(self) -> Pin<Box<Self>> {
|
|
|
|
Box::pin(self)
|
|
|
|
}
|
2020-06-15 08:46:07 +00:00
|
|
|
}
|
|
|
|
|
2022-06-29 22:26:37 +00:00
|
|
|
// Advances the filter's state machine
|
2020-09-23 08:04:54 +00:00
|
|
|
impl<'a, P, R> Stream for FilterWatcher<'a, P, R>
|
2020-06-15 08:46:07 +00:00
|
|
|
where
|
2020-09-23 08:04:54 +00:00
|
|
|
P: JsonRpcClient,
|
2020-12-24 20:23:05 +00:00
|
|
|
R: Serialize + Send + Sync + DeserializeOwned + Debug + 'a,
|
2020-06-15 08:46:07 +00:00
|
|
|
{
|
|
|
|
type Item = R;
|
|
|
|
|
2020-09-23 08:04:54 +00:00
|
|
|
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
2022-06-29 22:26:37 +00:00
|
|
|
let mut this = self.project();
|
2020-09-23 08:04:54 +00:00
|
|
|
let id = *this.id;
|
2020-06-15 08:46:07 +00:00
|
|
|
|
2022-06-29 22:26:37 +00:00
|
|
|
loop {
|
|
|
|
*this.state = match &mut this.state {
|
|
|
|
FilterWatcherState::WaitForInterval => {
|
|
|
|
// Wait the polling period
|
|
|
|
let _ready = futures_util::ready!(this.interval.poll_next_unpin(cx));
|
|
|
|
let fut = Box::pin(this.provider.get_filter_changes(id));
|
|
|
|
FilterWatcherState::GetFilterChanges(fut)
|
2020-06-21 07:17:11 +00:00
|
|
|
}
|
2022-06-29 22:26:37 +00:00
|
|
|
FilterWatcherState::GetFilterChanges(fut) => {
|
|
|
|
// NOTE: If the provider returns an error, this will return an empty
|
|
|
|
// vector. Should we make this return a Result instead? Ideally if we're
|
|
|
|
// in a streamed loop we wouldn't want the loop to terminate if an error
|
|
|
|
// is encountered (since it might be a temporary error).
|
|
|
|
let items: Vec<R> =
|
|
|
|
futures_util::ready!(fut.as_mut().poll(cx)).unwrap_or_default();
|
|
|
|
FilterWatcherState::NextItem(items.into_iter())
|
|
|
|
}
|
|
|
|
// Consume 1 element from the vector. If more elements are in the vector,
|
|
|
|
// the next call will immediately go to this branch instead of trying to get
|
|
|
|
// filter changes again. Once the whole vector is consumed, it will poll again
|
|
|
|
// for new logs
|
|
|
|
FilterWatcherState::NextItem(iter) => {
|
|
|
|
if let item @ Some(_) = iter.next() {
|
|
|
|
return Poll::Ready(item)
|
|
|
|
}
|
|
|
|
FilterWatcherState::WaitForInterval
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2020-06-15 08:46:07 +00:00
|
|
|
}
|
|
|
|
}
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
impl<'a, P> FilterWatcher<'a, P, TxHash>
|
|
|
|
where
|
|
|
|
P: JsonRpcClient,
|
|
|
|
{
|
2021-10-29 12:29:35 +00:00
|
|
|
/// Returns a stream that yields the `Transaction`s for the transaction hashes this stream
|
|
|
|
/// yields.
|
2021-06-05 17:08:33 +00:00
|
|
|
///
|
|
|
|
/// This internally calls `Provider::get_transaction` with every new transaction.
|
|
|
|
/// No more than n futures will be buffered at any point in time, and less than n may also be
|
|
|
|
/// buffered depending on the state of each future.
|
|
|
|
pub fn transactions_unordered(self, n: usize) -> TransactionStream<'a, P, Self> {
|
|
|
|
TransactionStream::new(self.provider, self, n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Errors `TransactionStream` can throw
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum GetTransactionError {
|
|
|
|
#[error("Failed to get transaction `{0}`: {1}")]
|
|
|
|
ProviderError(TxHash, ProviderError),
|
|
|
|
/// `get_transaction` resulted in a `None`
|
|
|
|
#[error("Transaction `{0}` not found")]
|
|
|
|
NotFound(TxHash),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<GetTransactionError> for ProviderError {
|
|
|
|
fn from(err: GetTransactionError) -> Self {
|
|
|
|
match err {
|
|
|
|
GetTransactionError::ProviderError(_, err) => err,
|
|
|
|
err @ GetTransactionError::NotFound(_) => ProviderError::CustomError(err.to_string()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-23 14:29:51 +00:00
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
|
|
type TransactionFut<'a> = Pin<Box<dyn Future<Output = TransactionResult> + Send + 'a>>;
|
|
|
|
#[cfg(target_arch = "wasm32")]
|
2021-06-05 17:08:33 +00:00
|
|
|
type TransactionFut<'a> = Pin<Box<dyn Future<Output = TransactionResult> + 'a>>;
|
|
|
|
|
|
|
|
type TransactionResult = Result<Transaction, GetTransactionError>;
|
|
|
|
|
|
|
|
/// Drains a stream of transaction hashes and yields entire `Transaction`.
|
|
|
|
#[must_use = "streams do nothing unless polled"]
|
|
|
|
pub struct TransactionStream<'a, P, St> {
|
|
|
|
/// Currently running futures pending completion.
|
|
|
|
pending: FuturesUnordered<TransactionFut<'a>>,
|
|
|
|
/// Temporary buffered transaction that get started as soon as another future finishes.
|
|
|
|
buffered: VecDeque<TxHash>,
|
|
|
|
/// The provider that gets the transaction
|
|
|
|
provider: &'a Provider<P>,
|
|
|
|
/// A stream of transaction hashes.
|
|
|
|
stream: St,
|
|
|
|
/// max allowed futures to execute at once.
|
|
|
|
max_concurrent: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, P: JsonRpcClient, St> TransactionStream<'a, P, St> {
|
|
|
|
/// Create a new `TransactionStream` instance
|
|
|
|
pub fn new(provider: &'a Provider<P>, stream: St, max_concurrent: usize) -> Self {
|
|
|
|
Self {
|
|
|
|
pending: Default::default(),
|
|
|
|
buffered: Default::default(),
|
|
|
|
provider,
|
|
|
|
stream,
|
|
|
|
max_concurrent,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Push a future into the set
|
|
|
|
fn push_tx(&mut self, tx: TxHash) {
|
2021-10-29 12:29:35 +00:00
|
|
|
let fut = self.provider.get_transaction(tx).then(move |res| match res {
|
|
|
|
Ok(Some(tx)) => futures_util::future::ok(tx),
|
|
|
|
Ok(None) => futures_util::future::err(GetTransactionError::NotFound(tx)),
|
|
|
|
Err(err) => futures_util::future::err(GetTransactionError::ProviderError(tx, err)),
|
|
|
|
});
|
2021-06-05 17:08:33 +00:00
|
|
|
self.pending.push(Box::pin(fut));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, P, St> Stream for TransactionStream<'a, P, St>
|
|
|
|
where
|
|
|
|
P: JsonRpcClient,
|
|
|
|
St: Stream<Item = TxHash> + Unpin + 'a,
|
|
|
|
{
|
|
|
|
type Item = TransactionResult;
|
|
|
|
|
|
|
|
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
|
|
let this = self.get_mut();
|
|
|
|
|
|
|
|
// drain buffered transactions first
|
|
|
|
while this.pending.len() < this.max_concurrent {
|
|
|
|
if let Some(tx) = this.buffered.pop_front() {
|
|
|
|
this.push_tx(tx);
|
|
|
|
} else {
|
2021-10-29 12:29:35 +00:00
|
|
|
break
|
2021-06-05 17:08:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut stream_done = false;
|
|
|
|
loop {
|
|
|
|
match Stream::poll_next(Pin::new(&mut this.stream), cx) {
|
|
|
|
Poll::Ready(Some(tx)) => {
|
|
|
|
if this.pending.len() < this.max_concurrent {
|
|
|
|
this.push_tx(tx);
|
|
|
|
} else {
|
|
|
|
this.buffered.push_back(tx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Poll::Ready(None) => {
|
|
|
|
stream_done = true;
|
2021-10-29 12:29:35 +00:00
|
|
|
break
|
2021-06-05 17:08:33 +00:00
|
|
|
}
|
|
|
|
_ => break,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// poll running futures
|
|
|
|
if let tx @ Poll::Ready(Some(_)) = this.pending.poll_next_unpin(cx) {
|
2021-10-29 12:29:35 +00:00
|
|
|
return tx
|
2021-06-05 17:08:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if stream_done && this.pending.is_empty() {
|
|
|
|
// all done
|
2021-10-29 12:29:35 +00:00
|
|
|
return Poll::Ready(None)
|
2021-06-05 17:08:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Poll::Pending
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
2021-08-23 09:56:44 +00:00
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
2021-06-05 17:08:33 +00:00
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use crate::{Http, Ws};
|
|
|
|
use ethers_core::{
|
|
|
|
types::{TransactionReceipt, TransactionRequest},
|
2022-06-01 15:22:39 +00:00
|
|
|
utils::Anvil,
|
2021-06-05 17:08:33 +00:00
|
|
|
};
|
|
|
|
use futures_util::{FutureExt, StreamExt};
|
2021-10-29 12:29:35 +00:00
|
|
|
use std::{collections::HashSet, convert::TryFrom};
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn can_stream_pending_transactions() {
|
|
|
|
let num_txs = 5;
|
2022-06-01 15:22:39 +00:00
|
|
|
let geth = Anvil::new().block_time(2u64).spawn();
|
2021-06-05 17:08:33 +00:00
|
|
|
let provider = Provider::<Http>::try_from(geth.endpoint())
|
|
|
|
.unwrap()
|
|
|
|
.interval(Duration::from_millis(1000));
|
|
|
|
let ws = Ws::connect(geth.ws_endpoint()).await.unwrap();
|
|
|
|
let ws_provider = Provider::new(ws);
|
|
|
|
|
|
|
|
let accounts = provider.get_accounts().await.unwrap();
|
2021-10-29 12:29:35 +00:00
|
|
|
let tx = TransactionRequest::new().from(accounts[0]).to(accounts[0]).value(1e18 as u64);
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
let mut sending = futures_util::future::join_all(
|
2022-06-07 15:44:02 +00:00
|
|
|
std::iter::repeat(tx.clone())
|
|
|
|
.take(num_txs)
|
|
|
|
.enumerate()
|
|
|
|
.map(|(nonce, tx)| tx.nonce(nonce))
|
|
|
|
.map(|tx| async {
|
|
|
|
provider.send_transaction(tx, None).await.unwrap().await.unwrap().unwrap()
|
|
|
|
}),
|
2021-06-05 17:08:33 +00:00
|
|
|
)
|
|
|
|
.fuse();
|
|
|
|
|
|
|
|
let mut watch_tx_stream = provider
|
|
|
|
.watch_pending_transactions()
|
|
|
|
.await
|
|
|
|
.unwrap()
|
|
|
|
.transactions_unordered(num_txs)
|
|
|
|
.fuse();
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
let mut sub_tx_stream =
|
|
|
|
ws_provider.subscribe_pending_txs().await.unwrap().transactions_unordered(2).fuse();
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
let mut sent: Option<Vec<TransactionReceipt>> = None;
|
|
|
|
let mut watch_received: Vec<Transaction> = Vec::with_capacity(num_txs);
|
|
|
|
let mut sub_received: Vec<Transaction> = Vec::with_capacity(num_txs);
|
|
|
|
|
|
|
|
loop {
|
|
|
|
futures_util::select! {
|
|
|
|
txs = sending => {
|
|
|
|
sent = Some(txs)
|
|
|
|
},
|
|
|
|
tx = watch_tx_stream.next() => watch_received.push(tx.unwrap().unwrap()),
|
|
|
|
tx = sub_tx_stream.next() => sub_received.push(tx.unwrap().unwrap()),
|
|
|
|
};
|
|
|
|
if watch_received.len() == num_txs && sub_received.len() == num_txs {
|
|
|
|
if let Some(ref sent) = sent {
|
|
|
|
assert_eq!(sent.len(), watch_received.len());
|
2021-10-29 12:29:35 +00:00
|
|
|
let sent_txs =
|
|
|
|
sent.iter().map(|tx| tx.transaction_hash).collect::<HashSet<_>>();
|
2021-06-05 17:08:33 +00:00
|
|
|
assert_eq!(sent_txs, watch_received.iter().map(|tx| tx.hash).collect());
|
|
|
|
assert_eq!(sent_txs, sub_received.iter().map(|tx| tx.hash).collect());
|
2021-10-29 12:29:35 +00:00
|
|
|
break
|
2021-06-05 17:08:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn can_stream_transactions() {
|
2022-06-01 15:22:39 +00:00
|
|
|
let anvil = Anvil::new().block_time(2u64).spawn();
|
|
|
|
let provider =
|
|
|
|
Provider::<Http>::try_from(anvil.endpoint()).unwrap().with_sender(anvil.addresses()[0]);
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
let accounts = provider.get_accounts().await.unwrap();
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
let tx = TransactionRequest::new().from(accounts[0]).to(accounts[0]).value(1e18 as u64);
|
2022-06-01 15:22:39 +00:00
|
|
|
let txs = vec![tx.clone().nonce(0u64), tx.clone().nonce(1u64), tx.clone().nonce(2u64)];
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
let txs =
|
2022-06-01 15:22:39 +00:00
|
|
|
futures_util::future::join_all(txs.into_iter().map(|tx| async {
|
2021-10-29 12:29:35 +00:00
|
|
|
provider.send_transaction(tx, None).await.unwrap().await.unwrap()
|
2021-06-05 17:08:33 +00:00
|
|
|
}))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let stream = TransactionStream::new(
|
|
|
|
&provider,
|
2021-07-06 08:06:18 +00:00
|
|
|
stream::iter(txs.iter().cloned().map(|tx| tx.unwrap().transaction_hash)),
|
2021-06-05 17:08:33 +00:00
|
|
|
10,
|
|
|
|
);
|
2021-10-29 12:29:35 +00:00
|
|
|
let res =
|
|
|
|
stream.collect::<Vec<_>>().await.into_iter().collect::<Result<Vec<_>, _>>().unwrap();
|
2021-06-05 17:08:33 +00:00
|
|
|
|
|
|
|
assert_eq!(res.len(), txs.len());
|
|
|
|
assert_eq!(
|
|
|
|
res.into_iter().map(|tx| tx.hash).collect::<HashSet<_>>(),
|
2021-10-29 12:29:35 +00:00
|
|
|
txs.into_iter().map(|tx| tx.unwrap().transaction_hash).collect()
|
2021-06-05 17:08:33 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|