|
| 1 | +use crate::config::Provider; |
| 2 | +use alloy::{primitives::TxHash, providers::Provider as _}; |
| 3 | +use metrics::{counter, histogram}; |
| 4 | +use std::time::Instant; |
| 5 | +use tokio::{sync::mpsc, task::JoinHandle}; |
| 6 | +use tracing::{debug, error}; |
| 7 | + |
| 8 | +/// Collects metrics on transactions sent by the Builder |
| 9 | +#[derive(Debug, Clone)] |
| 10 | +pub struct MetricsTask { |
| 11 | + /// Ethereum Provider |
| 12 | + pub host_provider: Provider, |
| 13 | +} |
| 14 | + |
| 15 | +impl MetricsTask { |
| 16 | + /// Given a transaction hash, record metrics on the result of the transaction mining |
| 17 | + pub async fn log_tx(&self, pending_tx_hash: TxHash) { |
| 18 | + // start timer when tx hash is received |
| 19 | + let start: Instant = Instant::now(); |
| 20 | + |
| 21 | + // wait for the tx to mine, get its receipt |
| 22 | + let receipt_result = |
| 23 | + self.host_provider.clone().get_transaction_receipt(pending_tx_hash).await; |
| 24 | + |
| 25 | + match receipt_result { |
| 26 | + Ok(maybe_receipt) => { |
| 27 | + match maybe_receipt { |
| 28 | + Some(receipt) => { |
| 29 | + // record how long it took to mine the transaction |
| 30 | + // potential improvement: use the block timestamp to calculate the time elapsed |
| 31 | + histogram!("metrics.tx_mine_time") |
| 32 | + .record(start.elapsed().as_millis() as f64); |
| 33 | + |
| 34 | + // log whether the transaction reverted |
| 35 | + if receipt.status() { |
| 36 | + counter!("metrics.tx_reverted").increment(1); |
| 37 | + debug!(tx_hash = %pending_tx_hash, "tx reverted"); |
| 38 | + } else { |
| 39 | + counter!("metrics.tx_succeeded").increment(1); |
| 40 | + debug!(tx_hash = %pending_tx_hash, "tx succeeded"); |
| 41 | + } |
| 42 | + } |
| 43 | + None => { |
| 44 | + counter!("metrics.no_receipt").increment(1); |
| 45 | + error!("no receipt found for tx hash"); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + Err(e) => { |
| 50 | + counter!("metrics.rpc_error").increment(1); |
| 51 | + error!(error = ?e, "rpc error"); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + /// Spawns the task which collects metrics on pending transactions |
| 57 | + pub fn spawn(self) -> (mpsc::UnboundedSender<TxHash>, JoinHandle<()>) { |
| 58 | + let (sender, mut inbound) = mpsc::unbounded_channel(); |
| 59 | + let handle = tokio::spawn(async move { |
| 60 | + debug!("metrics task spawned"); |
| 61 | + loop { |
| 62 | + if let Some(pending_tx_hash) = inbound.recv().await { |
| 63 | + let this = self.clone(); |
| 64 | + tokio::spawn(async move { |
| 65 | + debug!("received tx hash"); |
| 66 | + let that = this.clone(); |
| 67 | + that.log_tx(pending_tx_hash).await; |
| 68 | + debug!("logged tx metrics"); |
| 69 | + }); |
| 70 | + } else { |
| 71 | + tracing::debug!("upstream task gone"); |
| 72 | + break; |
| 73 | + } |
| 74 | + } |
| 75 | + }); |
| 76 | + |
| 77 | + (sender, handle) |
| 78 | + } |
| 79 | +} |
0 commit comments