Prestwich/event no lifetime (#2105)

* refactor(breaking): remove lifetime from Event

* fix: example updated to use new event
This commit is contained in:
James Prestwich 2023-02-13 20:14:38 -05:00 committed by GitHub
parent e970f58a8a
commit 0c16eb971d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 109 additions and 66 deletions

View File

@ -120,6 +120,7 @@
### Unreleased ### Unreleased
- Abigen now generates events with new `<B, M>` generic pattern [#2103](https://github.com/gakonst/ethers-rs/pull/2103)
- Fix Cargo.toml generation issue that could cause dependency conflicts [#1852](https://github.com/gakonst/ethers-rs/pull/1852) - Fix Cargo.toml generation issue that could cause dependency conflicts [#1852](https://github.com/gakonst/ethers-rs/pull/1852)
- Use corresponding rust structs for event fields if they're solidity structs [#1674](https://github.com/gakonst/ethers-rs/pull/1674) - Use corresponding rust structs for event fields if they're solidity structs [#1674](https://github.com/gakonst/ethers-rs/pull/1674)
- Add `ContractFilter` to filter contracts in `MultiAbigen` [#1564](https://github.com/gakonst/ethers-rs/pull/1564) - Add `ContractFilter` to filter contracts in `MultiAbigen` [#1564](https://github.com/gakonst/ethers-rs/pull/1564)
@ -300,6 +301,8 @@
### Unreleased ### Unreleased
- (Breaking) Make `Event` objects generic over borrow & remove lifetime
[#2105](https://github.com/gakonst/ethers-rs/pull/2105)
- Make `Factory` objects generic over the borrow trait, to allow non-arc mware - Make `Factory` objects generic over the borrow trait, to allow non-arc mware
[#2103](https://github.com/gakonst/ethers-rs/pull/2103) [#2103](https://github.com/gakonst/ethers-rs/pull/2103)
- Make `Contract` objects generic over the borrow trait, to allow non-arc mware - Make `Contract` objects generic over the borrow trait, to allow non-arc mware

View File

@ -127,7 +127,7 @@ impl Context {
quote! { quote! {
/// Returns an [`Event`](#ethers_contract::builders::Event) builder for all events of this contract /// Returns an [`Event`](#ethers_contract::builders::Event) builder for all events of this contract
pub fn events(&self) -> #ethers_contract::builders::Event<M, #ty> { pub fn events(&self) -> #ethers_contract::builders::Event<Arc<M>, M, #ty> {
self.0.event_with_filter(Default::default()) self.0.event_with_filter(Default::default())
} }
} }
@ -235,7 +235,7 @@ impl Context {
quote! { quote! {
#[doc = #doc_str] #[doc = #doc_str]
pub fn #function_name(&self) -> #ethers_contract::builders::Event<M, #struct_name> { pub fn #function_name(&self) -> #ethers_contract::builders::Event<Arc<M>, M, #struct_name> {
self.0.event() self.0.event()
} }
} }
@ -406,7 +406,7 @@ mod tests {
#[doc = "Gets the contract's `Transfer` event"] #[doc = "Gets the contract's `Transfer` event"]
pub fn transfer_event_filter( pub fn transfer_event_filter(
&self &self
) -> ::ethers_contract::builders::Event<M, TransferEventFilter> { ) -> ::ethers_contract::builders::Event<Arc<M>, M, TransferEventFilter> {
self.0.event() self.0.event()
} }
}); });
@ -425,7 +425,9 @@ mod tests {
let cx = test_context(); let cx = test_context();
assert_quote!(cx.expand_filter(&event), { assert_quote!(cx.expand_filter(&event), {
#[doc = "Gets the contract's `Transfer` event"] #[doc = "Gets the contract's `Transfer` event"]
pub fn transfer_filter(&self) -> ::ethers_contract::builders::Event<M, TransferFilter> { pub fn transfer_filter(
&self,
) -> ::ethers_contract::builders::Event<Arc<M>, M, TransferFilter> {
self.0.event() self.0.event()
} }
}); });

View File

@ -243,11 +243,12 @@ where
/// Returns an [`Event`](crate::builders::Event) builder for the provided event. /// Returns an [`Event`](crate::builders::Event) builder for the provided event.
/// This function operates in a static context, then it does not require a `self` /// This function operates in a static context, then it does not require a `self`
/// to reference to instantiate an [`Event`](crate::builders::Event) builder. /// to reference to instantiate an [`Event`](crate::builders::Event) builder.
pub fn event_of_type<D: EthEvent>(client: &M) -> Event<M, D> { pub fn event_of_type<D: EthEvent>(client: B) -> Event<B, M, D> {
Event { Event {
provider: client, provider: client,
filter: Filter::new().event(&D::abi_signature()), filter: Filter::new().event(&D::abi_signature()),
datatype: PhantomData, datatype: PhantomData,
_m: PhantomData,
} }
} }
} }
@ -262,27 +263,6 @@ where
Self { base_contract: abi.into(), client, address: address.into(), _m: PhantomData } Self { base_contract: abi.into(), client, address: address.into(), _m: PhantomData }
} }
/// Returns an [`Event`](crate::builders::Event) builder for the provided event.
pub fn event<D: EthEvent>(&self) -> Event<M, D> {
self.event_with_filter(Filter::new().event(&D::abi_signature()))
}
/// Returns an [`Event`](crate::builders::Event) builder with the provided filter.
pub fn event_with_filter<D: EthLogDecode>(&self, filter: Filter) -> Event<M, D> {
Event {
provider: self.client.borrow(),
filter: filter.address(ValueOrArray::Value(self.address)),
datatype: PhantomData,
}
}
/// Returns an [`Event`](crate::builders::Event) builder with the provided name.
pub fn event_for_name<D: EthLogDecode>(&self, name: &str) -> Result<Event<M, D>, Error> {
// get the event's full name
let event = self.base_contract.abi.event(name)?;
Ok(self.event_with_filter(Filter::new().event(&event.abi_signature())))
}
/// Returns a new contract instance using the provided client /// Returns a new contract instance using the provided client
/// ///
/// Clones `self` internally /// Clones `self` internally
@ -321,6 +301,28 @@ where
B: Clone + Borrow<M>, B: Clone + Borrow<M>,
M: Middleware, M: Middleware,
{ {
/// Returns an [`Event`](crate::builders::Event) builder with the provided filter.
pub fn event_with_filter<D: EthLogDecode>(&self, filter: Filter) -> Event<B, M, D> {
Event {
provider: self.client.clone(),
filter: filter.address(ValueOrArray::Value(self.address)),
datatype: PhantomData,
_m: PhantomData,
}
}
/// Returns an [`Event`](crate::builders::Event) builder for the provided event.
pub fn event<D: EthEvent>(&self) -> Event<B, M, D> {
self.event_with_filter(Filter::new().event(&D::abi_signature()))
}
/// Returns an [`Event`](crate::builders::Event) builder with the provided name.
pub fn event_for_name<D: EthLogDecode>(&self, name: &str) -> Result<Event<B, M, D>, Error> {
// get the event's full name
let event = self.base_contract.abi.event(name)?;
Ok(self.event_with_filter(Filter::new().event(&event.abi_signature())))
}
fn method_func<T: Tokenize, D: Detokenize>( fn method_func<T: Tokenize, D: Detokenize>(
&self, &self,
function: &Function, function: &Function,

View File

@ -2,11 +2,22 @@
use crate::{log::LogMeta, stream::EventStream, ContractError, EthLogDecode}; use crate::{log::LogMeta, stream::EventStream, ContractError, EthLogDecode};
use ethers_core::{ use ethers_core::{
abi::{Address, Detokenize, RawLog}, abi::{Address, Detokenize, Error as AbiError, RawLog},
types::{BlockNumber, Filter, Log, Topic, ValueOrArray, H256}, types::{BlockNumber, Filter, Log, Topic, ValueOrArray, H256},
}; };
use ethers_providers::{FilterWatcher, Middleware, PubsubClient, SubscriptionStream}; use ethers_providers::{FilterWatcher, Middleware, PubsubClient, SubscriptionStream};
use std::{borrow::Cow, marker::PhantomData}; use std::{
borrow::{Borrow, Cow},
marker::PhantomData,
};
/// Attempt to parse a log into a specific output type.
pub fn parse_log<D>(log: Log) -> std::result::Result<D, AbiError>
where
D: EthLogDecode,
{
D::decode_log(&RawLog { topics: log.topics, data: log.data.to_vec() })
}
/// A trait for implementing event bindings /// A trait for implementing event bindings
pub trait EthEvent: Detokenize + Send + Sync { pub trait EthEvent: Detokenize + Send + Sync {
@ -31,12 +42,14 @@ pub trait EthEvent: Detokenize + Send + Sync {
fn is_anonymous() -> bool; fn is_anonymous() -> bool;
/// Returns an Event builder for the ethereum event represented by this types ABI signature. /// Returns an Event builder for the ethereum event represented by this types ABI signature.
fn new<M: Middleware>(filter: Filter, provider: &M) -> Event<M, Self> fn new<B, M>(filter: Filter, provider: B) -> Event<B, M, Self>
where where
Self: Sized, Self: Sized,
B: Borrow<M>,
M: Middleware,
{ {
let filter = filter.event(&Self::abi_signature()); let filter = filter.event(&Self::abi_signature());
Event { filter, provider, datatype: PhantomData } Event { filter, provider, datatype: PhantomData, _m: PhantomData }
} }
} }
@ -53,16 +66,22 @@ impl<T: EthEvent> EthLogDecode for T {
/// Helper for managing the event filter before querying or streaming its logs /// Helper for managing the event filter before querying or streaming its logs
#[derive(Debug)] #[derive(Debug)]
#[must_use = "event filters do nothing unless you `query` or `stream` them"] #[must_use = "event filters do nothing unless you `query` or `stream` them"]
pub struct Event<'a, M, D> { pub struct Event<B, M, D> {
/// The event filter's state /// The event filter's state
pub filter: Filter, pub filter: Filter,
pub(crate) provider: &'a M, pub(crate) provider: B,
/// Stores the event datatype /// Stores the event datatype
pub(crate) datatype: PhantomData<D>, pub(crate) datatype: PhantomData<D>,
pub(crate) _m: PhantomData<M>,
} }
// TODO: Improve these functions // TODO: Improve these functions
impl<M, D: EthLogDecode> Event<'_, M, D> { impl<B, M, D> Event<B, M, D>
where
B: Borrow<M>,
M: Middleware,
D: EthLogDecode,
{
/// Sets the filter's `from` block /// Sets the filter's `from` block
#[allow(clippy::wrong_self_convention)] #[allow(clippy::wrong_self_convention)]
pub fn from_block<T: Into<BlockNumber>>(mut self, block: T) -> Self { pub fn from_block<T: Into<BlockNumber>>(mut self, block: T) -> Self {
@ -116,8 +135,9 @@ impl<M, D: EthLogDecode> Event<'_, M, D> {
} }
} }
impl<'a, M, D> Event<'a, M, D> impl<B, M, D> Event<B, M, D>
where where
B: Borrow<M>,
M: Middleware, M: Middleware,
D: EthLogDecode, D: EthLogDecode,
{ {
@ -161,40 +181,49 @@ where
/// # } /// # }
/// ``` /// ```
pub async fn stream( pub async fn stream(
&'a self, &self,
) -> Result< ) -> Result<
// Wraps the FilterWatcher with a mapping to the event // Wraps the FilterWatcher with a mapping to the event
EventStream<'a, FilterWatcher<'a, M::Provider, Log>, D, ContractError<M>>, EventStream<'_, FilterWatcher<'_, M::Provider, Log>, D, ContractError<M>>,
ContractError<M>, ContractError<M>,
> { > {
let filter = let filter = self
self.provider.watch(&self.filter).await.map_err(ContractError::MiddlewareError)?; .provider
Ok(EventStream::new(filter.id, filter, Box::new(move |log| self.parse_log(log)))) .borrow()
.watch(&self.filter)
.await
.map_err(ContractError::MiddlewareError)?;
Ok(EventStream::new(filter.id, filter, Box::new(move |log| Ok(parse_log(log)?))))
} }
/// As [`Self::stream`], but does not discard [`Log`] metadata. /// As [`Self::stream`], but does not discard [`Log`] metadata.
pub async fn stream_with_meta( pub async fn stream_with_meta(
&'a self, &self,
) -> Result< ) -> Result<
// Wraps the FilterWatcher with a mapping to the event // Wraps the FilterWatcher with a mapping to the event
EventStream<'a, FilterWatcher<'a, M::Provider, Log>, (D, LogMeta), ContractError<M>>, EventStream<'_, FilterWatcher<'_, M::Provider, Log>, (D, LogMeta), ContractError<M>>,
ContractError<M>, ContractError<M>,
> { > {
let filter = let filter = self
self.provider.watch(&self.filter).await.map_err(ContractError::MiddlewareError)?; .provider
.borrow()
.watch(&self.filter)
.await
.map_err(ContractError::MiddlewareError)?;
Ok(EventStream::new( Ok(EventStream::new(
filter.id, filter.id,
filter, filter,
Box::new(move |log| { Box::new(move |log| {
let meta = LogMeta::from(&log); let meta = LogMeta::from(&log);
Ok((self.parse_log(log)?, meta)) Ok((parse_log(log)?, meta))
}), }),
)) ))
} }
} }
impl<'a, M, D> Event<'a, M, D> impl<B, M, D> Event<B, M, D>
where where
B: Borrow<M>,
M: Middleware, M: Middleware,
<M as Middleware>::Provider: PubsubClient, <M as Middleware>::Provider: PubsubClient,
D: EthLogDecode, D: EthLogDecode,
@ -203,29 +232,31 @@ where
/// ///
/// See also [Self::stream()]. /// See also [Self::stream()].
pub async fn subscribe( pub async fn subscribe(
&'a self, &self,
) -> Result< ) -> Result<
// Wraps the SubscriptionStream with a mapping to the event // Wraps the SubscriptionStream with a mapping to the event
EventStream<'a, SubscriptionStream<'a, M::Provider, Log>, D, ContractError<M>>, EventStream<'_, SubscriptionStream<'_, M::Provider, Log>, D, ContractError<M>>,
ContractError<M>, ContractError<M>,
> { > {
let filter = self let filter = self
.provider .provider
.borrow()
.subscribe_logs(&self.filter) .subscribe_logs(&self.filter)
.await .await
.map_err(ContractError::MiddlewareError)?; .map_err(ContractError::MiddlewareError)?;
Ok(EventStream::new(filter.id, filter, Box::new(move |log| self.parse_log(log)))) Ok(EventStream::new(filter.id, filter, Box::new(move |log| Ok(parse_log(log)?))))
} }
pub async fn subscribe_with_meta( pub async fn subscribe_with_meta(
&'a self, &self,
) -> Result< ) -> Result<
// Wraps the SubscriptionStream with a mapping to the event // Wraps the SubscriptionStream with a mapping to the event
EventStream<'a, SubscriptionStream<'a, M::Provider, Log>, (D, LogMeta), ContractError<M>>, EventStream<'_, SubscriptionStream<'_, M::Provider, Log>, (D, LogMeta), ContractError<M>>,
ContractError<M>, ContractError<M>,
> { > {
let filter = self let filter = self
.provider .provider
.borrow()
.subscribe_logs(&self.filter) .subscribe_logs(&self.filter)
.await .await
.map_err(ContractError::MiddlewareError)?; .map_err(ContractError::MiddlewareError)?;
@ -234,25 +265,30 @@ where
filter, filter,
Box::new(move |log| { Box::new(move |log| {
let meta = LogMeta::from(&log); let meta = LogMeta::from(&log);
Ok((self.parse_log(log)?, meta)) Ok((parse_log(log)?, meta))
}), }),
)) ))
} }
} }
impl<M, D> Event<'_, M, D> impl<B, M, D> Event<B, M, D>
where where
B: Borrow<M>,
M: Middleware, M: Middleware,
D: EthLogDecode, D: EthLogDecode,
{ {
/// Queries the blockchain for the selected filter and returns a vector of matching /// Queries the blockchain for the selected filter and returns a vector of matching
/// event logs /// event logs
pub async fn query(&self) -> Result<Vec<D>, ContractError<M>> { pub async fn query(&self) -> Result<Vec<D>, ContractError<M>> {
let logs = let logs = self
self.provider.get_logs(&self.filter).await.map_err(ContractError::MiddlewareError)?; .provider
.borrow()
.get_logs(&self.filter)
.await
.map_err(ContractError::MiddlewareError)?;
let events = logs let events = logs
.into_iter() .into_iter()
.map(|log| self.parse_log(log)) .map(|log| Ok(parse_log(log)?))
.collect::<Result<Vec<_>, ContractError<M>>>()?; .collect::<Result<Vec<_>, ContractError<M>>>()?;
Ok(events) Ok(events)
} }
@ -260,20 +296,20 @@ where
/// Queries the blockchain for the selected filter and returns a vector of logs /// Queries the blockchain for the selected filter and returns a vector of logs
/// along with their metadata /// along with their metadata
pub async fn query_with_meta(&self) -> Result<Vec<(D, LogMeta)>, ContractError<M>> { pub async fn query_with_meta(&self) -> Result<Vec<(D, LogMeta)>, ContractError<M>> {
let logs = let logs = self
self.provider.get_logs(&self.filter).await.map_err(ContractError::MiddlewareError)?; .provider
.borrow()
.get_logs(&self.filter)
.await
.map_err(ContractError::MiddlewareError)?;
let events = logs let events = logs
.into_iter() .into_iter()
.map(|log| { .map(|log| {
let meta = LogMeta::from(&log); let meta = LogMeta::from(&log);
let event = self.parse_log(log)?; let event = parse_log(log)?;
Ok((event, meta)) Ok((event, meta))
}) })
.collect::<Result<_, ContractError<M>>>()?; .collect::<Result<_, ContractError<M>>>()?;
Ok(events) Ok(events)
} }
pub fn parse_log(&self, log: Log) -> Result<D, ContractError<M>> {
D::decode_log(&RawLog { topics: log.topics, data: log.data.to_vec() }).map_err(From::from)
}
} }

View File

@ -410,7 +410,7 @@ mod eth_tests {
let anvil = Anvil::new().spawn(); let anvil = Anvil::new().spawn();
let client = connect(&anvil, 0); let client = connect(&anvil, 0);
let event = ethers_contract::Contract::event_of_type::<AnswerUpdatedFilter>(&client); let event = ethers_contract::Contract::event_of_type::<AnswerUpdatedFilter>(client);
assert_eq!(event.filter, Filter::new().event(&AnswerUpdatedFilter::abi_signature())); assert_eq!(event.filter, Filter::new().event(&AnswerUpdatedFilter::abi_signature()));
} }

View File

@ -98,13 +98,13 @@ mod dsproxyfactory_mod {
.expect("method not found (this should never happen)") .expect("method not found (this should never happen)")
} }
///Gets the contract's `Created` event ///Gets the contract's `Created` event
pub fn created_filter(&self) -> Event<M, CreatedFilter> { pub fn created_filter(&self) -> Event<Arc<M>, M, CreatedFilter> {
self.0.event() self.0.event()
} }
/// Returns an [`Event`](ethers_contract::builders::Event) builder for all events of this /// Returns an [`Event`](ethers_contract::builders::Event) builder for all events of this
/// contract /// contract
pub fn events(&self) -> Event<M, CreatedFilter> { pub fn events(&self) -> Event<Arc<M>, M, CreatedFilter> {
self.0.event_with_filter(Default::default()) self.0.event_with_filter(Default::default())
} }
} }

View File

@ -26,7 +26,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Build an Event by type. We are not tied to a contract instance. We use builder functions to // Build an Event by type. We are not tied to a contract instance. We use builder functions to
// refine the event filter // refine the event filter
let event = Contract::event_of_type::<AnswerUpdatedFilter>(&client) let event = Contract::event_of_type::<AnswerUpdatedFilter>(client)
.from_block(16022082) .from_block(16022082)
.address(ValueOrArray::Array(vec![ .address(ValueOrArray::Array(vec![
PRICE_FEED_1.parse()?, PRICE_FEED_1.parse()?,