alloy_provider/fillers/mod.rs
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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
//! Transaction Fillers
//!
//! Fillers decorate a [`Provider`], filling transaction details before they
//! are sent to the network. Fillers are used to set the nonce, gas price, gas
//! limit, and other transaction details, and are called before any other layer.
//!
//! [`Provider`]: crate::Provider
mod chain_id;
pub use chain_id::ChainIdFiller;
mod wallet;
pub use wallet::WalletFiller;
mod nonce;
pub use nonce::{CachedNonceManager, NonceFiller, NonceManager, SimpleNonceManager};
mod gas;
pub use gas::{BlobGasFiller, GasFillable, GasFiller};
mod join_fill;
pub use join_fill::JoinFill;
use tracing::error;
use crate::{
provider::SendableTx, Identity, PendingTransactionBuilder, Provider, ProviderLayer,
RootProvider,
};
use alloy_json_rpc::RpcError;
use alloy_network::{AnyNetwork, Ethereum, Network};
use alloy_transport::{Transport, TransportResult};
use async_trait::async_trait;
use futures_utils_wasm::impl_future;
use std::marker::PhantomData;
/// The recommended filler, a preconfigured set of layers handling gas estimation, nonce
/// management, and chain-id fetching.
pub type RecommendedFiller =
JoinFill<JoinFill<JoinFill<Identity, GasFiller>, NonceFiller>, ChainIdFiller>;
/// The control flow for a filler.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FillerControlFlow {
/// The filler is missing a required property.
///
/// To allow joining fillers while preserving their associated missing
/// lists, this variant contains a list of `(name, missing)` tuples. When
/// absorbing another control flow, if both are missing, the missing lists
/// are combined.
Missing(Vec<(&'static str, Vec<&'static str>)>),
/// The filler is ready to fill in the transaction request.
Ready,
/// The filler has filled in all properties that it can fill.
Finished,
}
impl FillerControlFlow {
/// Absorb the control flow of another filler.
///
/// # Behavior:
/// - If either is finished, return the unfinished one
/// - If either is ready, return ready.
/// - If both are missing, return missing.
pub fn absorb(self, other: Self) -> Self {
if other.is_finished() {
return self;
}
if self.is_finished() {
return other;
}
if other.is_ready() || self.is_ready() {
return Self::Ready;
}
if let (Self::Missing(mut a), Self::Missing(b)) = (self, other) {
a.extend(b);
return Self::Missing(a);
}
unreachable!()
}
/// Creates a new `Missing` control flow.
pub fn missing(name: &'static str, missing: Vec<&'static str>) -> Self {
Self::Missing(vec![(name, missing)])
}
/// Returns true if the filler is missing a required property.
pub fn as_missing(&self) -> Option<&[(&'static str, Vec<&'static str>)]> {
match self {
Self::Missing(missing) => Some(missing),
_ => None,
}
}
/// Returns `true` if the filler is missing information required to fill in
/// the transaction request.
pub const fn is_missing(&self) -> bool {
matches!(self, Self::Missing(_))
}
/// Returns `true` if the filler is ready to fill in the transaction
/// request.
pub const fn is_ready(&self) -> bool {
matches!(self, Self::Ready)
}
/// Returns `true` if the filler is finished filling in the transaction
/// request.
pub const fn is_finished(&self) -> bool {
matches!(self, Self::Finished)
}
}
/// A layer that can fill in a `TransactionRequest` with additional information.
///
/// ## Lifecycle Notes
///
/// The [`FillerControlFlow`] determines the lifecycle of a filler. Fillers
/// may be in one of three states:
/// - **Missing**: The filler is missing a required property to fill in the transaction request.
/// [`TxFiller::status`] should return [`FillerControlFlow::Missing`]. with a list of the missing
/// properties.
/// - **Ready**: The filler is ready to fill in the transaction request. [`TxFiller::status`] should
/// return [`FillerControlFlow::Ready`].
/// - **Finished**: The filler has filled in all properties that it can fill. [`TxFiller::status`]
/// should return [`FillerControlFlow::Finished`].
#[doc(alias = "TransactionFiller")]
pub trait TxFiller<N: Network = Ethereum>: Clone + Send + Sync + std::fmt::Debug {
/// The properties that this filler retrieves from the RPC. to fill in the
/// TransactionRequest.
type Fillable: Send + Sync + 'static;
/// Joins this filler with another filler to compose multiple fillers.
fn join_with<T>(self, other: T) -> JoinFill<Self, T>
where
T: TxFiller<N>,
{
JoinFill::new(self, other)
}
/// Return a control-flow enum indicating whether the filler is ready to
/// fill in the transaction request, or if it is missing required
/// properties.
fn status(&self, tx: &N::TransactionRequest) -> FillerControlFlow;
/// Returns `true` if the filler is should continue filling.
fn continue_filling(&self, tx: &SendableTx<N>) -> bool {
tx.as_builder().is_some_and(|tx| self.status(tx).is_ready())
}
/// Returns `true` if the filler is ready to fill in the transaction request.
fn ready(&self, tx: &N::TransactionRequest) -> bool {
self.status(tx).is_ready()
}
/// Returns `true` if the filler is finished filling in the transaction request.
fn finished(&self, tx: &N::TransactionRequest) -> bool {
self.status(tx).is_finished()
}
/// Performs any synchronous filling. This should be called before
/// [`TxFiller::prepare`] and [`TxFiller::fill`] to fill in any properties
/// that can be filled synchronously.
fn fill_sync(&self, tx: &mut SendableTx<N>);
/// Prepares fillable properties, potentially by making an RPC request.
fn prepare<P, T>(
&self,
provider: &P,
tx: &N::TransactionRequest,
) -> impl_future!(<Output = TransportResult<Self::Fillable>>)
where
P: Provider<T, N>,
T: Transport + Clone;
/// Fills in the transaction request with the fillable properties.
fn fill(
&self,
fillable: Self::Fillable,
tx: SendableTx<N>,
) -> impl_future!(<Output = TransportResult<SendableTx<N>>>);
/// Prepares and fills the transaction request with the fillable properties.
fn prepare_and_fill<P, T>(
&self,
provider: &P,
tx: SendableTx<N>,
) -> impl_future!(<Output = TransportResult<SendableTx<N>>>)
where
P: Provider<T, N>,
T: Transport + Clone,
{
async move {
if tx.is_envelope() {
return Ok(tx);
}
let fillable =
self.prepare(provider, tx.as_builder().expect("checked by is_envelope")).await?;
self.fill(fillable, tx).await
}
}
}
/// A [`Provider`] that applies one or more [`TxFiller`]s.
///
/// Fills arbitrary properties in a transaction request by composing multiple
/// fill layers. This struct should always be the outermost layer in a provider
/// stack, and this is enforced when using [`ProviderBuilder::filler`] to
/// construct this layer.
///
/// Users should NOT use this struct directly. Instead, use
/// [`ProviderBuilder::filler`] to construct and apply it to a stack.
///
/// [`ProviderBuilder::filler`]: crate::ProviderBuilder::filler
#[derive(Clone, Debug)]
pub struct FillProvider<F, P, T, N>
where
F: TxFiller<N>,
P: Provider<T, N>,
T: Transport + Clone,
N: Network,
{
pub(crate) inner: P,
pub(crate) filler: F,
_pd: PhantomData<fn() -> (T, N)>,
}
impl<F, P, T, N> FillProvider<F, P, T, N>
where
F: TxFiller<N>,
P: Provider<T, N>,
T: Transport + Clone,
N: Network,
{
/// Creates a new `FillProvider` with the given filler and inner provider.
pub fn new(inner: P, filler: F) -> Self {
Self { inner, filler, _pd: PhantomData }
}
/// Joins a filler to this provider
pub fn join_with<Other: TxFiller<N>>(
self,
other: Other,
) -> FillProvider<JoinFill<F, Other>, P, T, N> {
self.filler.join_with(other).layer(self.inner)
}
async fn fill_inner(&self, mut tx: SendableTx<N>) -> TransportResult<SendableTx<N>> {
let mut count = 0;
while self.filler.continue_filling(&tx) {
self.filler.fill_sync(&mut tx);
tx = self.filler.prepare_and_fill(&self.inner, tx).await?;
count += 1;
if count >= 20 {
const ERROR: &str = "Tx filler loop detected. This indicates a bug in some filler implementation. Please file an issue containing this message.";
error!(
?tx, ?self.filler,
ERROR
);
panic!("{}, {:?}, {:?}", ERROR, &tx, &self.filler);
}
}
Ok(tx)
}
/// Fills the transaction request, using the configured fillers
pub async fn fill(&self, tx: N::TransactionRequest) -> TransportResult<SendableTx<N>> {
self.fill_inner(SendableTx::Builder(tx)).await
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<F, P, T, N> Provider<T, N> for FillProvider<F, P, T, N>
where
F: TxFiller<N>,
P: Provider<T, N>,
T: Transport + Clone,
N: Network,
{
fn root(&self) -> &RootProvider<T, N> {
self.inner.root()
}
async fn send_transaction_internal(
&self,
mut tx: SendableTx<N>,
) -> TransportResult<PendingTransactionBuilder<T, N>> {
tx = self.fill_inner(tx).await?;
if let Some(builder) = tx.as_builder() {
if let FillerControlFlow::Missing(missing) = self.filler.status(builder) {
// TODO: improve this.
// blocked by #431
let message = format!("missing properties: {:?}", missing);
return Err(RpcError::local_usage_str(&message));
}
}
// Errors in tx building happen further down the stack.
self.inner.send_transaction_internal(tx).await
}
}
/// A trait which may be used to configure default fillers for [Network] implementations.
pub trait RecommendedFillers: Network {
/// Recommended fillers for this network.
type RecomendedFillers: TxFiller<Self>;
/// Returns the recommended filler for this provider.
fn recommended_fillers() -> Self::RecomendedFillers;
}
impl RecommendedFillers for Ethereum {
type RecomendedFillers =
JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>;
fn recommended_fillers() -> Self::RecomendedFillers {
JoinFill::new(
GasFiller,
JoinFill::new(
BlobGasFiller,
JoinFill::new(NonceFiller::default(), ChainIdFiller::default()),
),
)
}
}
impl RecommendedFillers for AnyNetwork {
type RecomendedFillers =
JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>;
fn recommended_fillers() -> Self::RecomendedFillers {
JoinFill::new(
GasFiller,
JoinFill::new(
BlobGasFiller,
JoinFill::new(NonceFiller::default(), ChainIdFiller::default()),
),
)
}
}