1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use ethers_core::types::{transaction::eip2718::TypedTransaction, BlockId};
use ethers_providers::{FromErr, Middleware, PendingTransaction};
use async_trait::async_trait;
use std::fmt::Debug;
use thiserror::Error;
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait Policy: Sync + Send + Debug {
type Error: Sync + Send + Debug;
async fn ensure_can_send(&self, tx: TypedTransaction) -> Result<TypedTransaction, Self::Error>;
}
#[derive(Debug, Clone, Copy)]
pub struct AllowEverything;
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Policy for AllowEverything {
type Error = ();
async fn ensure_can_send(&self, tx: TypedTransaction) -> Result<TypedTransaction, Self::Error> {
Ok(tx)
}
}
#[derive(Debug, Clone, Copy)]
pub struct RejectEverything;
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Policy for RejectEverything {
type Error = ();
async fn ensure_can_send(&self, _: TypedTransaction) -> Result<TypedTransaction, Self::Error> {
Err(())
}
}
#[derive(Clone, Debug)]
pub struct PolicyMiddleware<M, P> {
pub(crate) inner: M,
pub(crate) policy: P,
}
impl<M: Middleware, P: Policy> FromErr<M::Error> for PolicyMiddlewareError<M, P> {
fn from(src: M::Error) -> PolicyMiddlewareError<M, P> {
PolicyMiddlewareError::MiddlewareError(src)
}
}
impl<M, P> PolicyMiddleware<M, P>
where
M: Middleware,
P: Policy,
{
pub fn new(inner: M, policy: P) -> Self {
Self { inner, policy }
}
}
#[derive(Error, Debug)]
pub enum PolicyMiddlewareError<M: Middleware, P: Policy> {
#[error("{0:?}")]
PolicyError(P::Error),
#[error(transparent)]
MiddlewareError(M::Error),
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<M, P> Middleware for PolicyMiddleware<M, P>
where
M: Middleware,
P: Policy,
{
type Error = PolicyMiddlewareError<M, P>;
type Provider = M::Provider;
type Inner = M;
fn inner(&self) -> &M {
&self.inner
}
async fn send_transaction<T: Into<TypedTransaction> + Send + Sync>(
&self,
tx: T,
block: Option<BlockId>,
) -> Result<PendingTransaction<'_, Self::Provider>, Self::Error> {
let tx = self
.policy
.ensure_can_send(tx.into())
.await
.map_err(PolicyMiddlewareError::PolicyError)?;
self.inner.send_transaction(tx, block).await.map_err(PolicyMiddlewareError::MiddlewareError)
}
}