|
| 1 | +//! Bundler service responsible for polling and submitting bundles to the in-progress block. |
| 2 | +use std::time::{Duration, Instant}; |
| 3 | + |
| 4 | +pub use crate::config::BuilderConfig; |
| 5 | +use alloy_primitives::map::HashMap; |
| 6 | +use reqwest::Url; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | +use signet_types::SignetEthBundle; |
| 9 | +use tokio::{sync::mpsc, task::JoinHandle}; |
| 10 | +use tracing::debug; |
| 11 | + |
| 12 | +use oauth2::TokenResponse; |
| 13 | + |
| 14 | +use super::oauth::Authenticator; |
| 15 | + |
| 16 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 17 | +pub struct Bundle { |
| 18 | + pub id: String, |
| 19 | + pub bundle: SignetEthBundle, |
| 20 | +} |
| 21 | + |
| 22 | +/// Response from the tx-pool containing a list of bundles. |
| 23 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 24 | +pub struct TxPoolBundleResponse { |
| 25 | + pub bundles: Vec<Bundle>, |
| 26 | +} |
| 27 | + |
| 28 | +pub struct BundlePoller { |
| 29 | + pub config: BuilderConfig, |
| 30 | + pub authenticator: Authenticator, |
| 31 | + pub seen_uuids: HashMap<String, Instant>, |
| 32 | +} |
| 33 | + |
| 34 | +/// Implements a poller for the block builder to pull bundles from the tx cache. |
| 35 | +impl BundlePoller { |
| 36 | + /// Creates a new BundlePoller from the provided builder config. |
| 37 | + pub async fn new(config: &BuilderConfig, authenticator: Authenticator) -> Self { |
| 38 | + Self { |
| 39 | + config: config.clone(), |
| 40 | + authenticator, |
| 41 | + seen_uuids: HashMap::new(), |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + /// Fetches bundles from the transaction cache and returns the (oldest? random?) bundle in the cache. |
| 46 | + pub async fn check_bundle_cache(&mut self) -> eyre::Result<Vec<Bundle>> { |
| 47 | + let mut unique: Vec<Bundle> = Vec::new(); |
| 48 | + |
| 49 | + let bundle_url: Url = Url::parse(&self.config.tx_pool_url)?.join("bundles")?; |
| 50 | + let token = self.authenticator.fetch_oauth_token().await?; |
| 51 | + |
| 52 | + // Add the token to the request headers |
| 53 | + let result = reqwest::Client::new() |
| 54 | + .get(bundle_url) |
| 55 | + .bearer_auth(token.access_token().secret()) |
| 56 | + .send() |
| 57 | + .await? |
| 58 | + .error_for_status()?; |
| 59 | + |
| 60 | + let body = result.bytes().await?; |
| 61 | + let bundles: TxPoolBundleResponse = serde_json::from_slice(&body)?; |
| 62 | + |
| 63 | + bundles.bundles.iter().for_each(|bundle| { |
| 64 | + self.check_seen_bundles(bundle.clone(), &mut unique); |
| 65 | + }); |
| 66 | + |
| 67 | + Ok(unique) |
| 68 | + } |
| 69 | + |
| 70 | + /// Checks if the bundle has been seen before and if not, adds it to the unique bundles list. |
| 71 | + fn check_seen_bundles(&mut self, bundle: Bundle, unique: &mut Vec<Bundle>) { |
| 72 | + self.seen_uuids.entry(bundle.id.clone()).or_insert_with(|| { |
| 73 | + // add to the set of unique bundles |
| 74 | + unique.push(bundle.clone()); |
| 75 | + Instant::now() + Duration::from_secs(self.config.tx_pool_cache_duration) |
| 76 | + }); |
| 77 | + } |
| 78 | + |
| 79 | + /// Evicts expired bundles from the cache. |
| 80 | + fn evict(&mut self) { |
| 81 | + let expired_keys: Vec<String> = self |
| 82 | + .seen_uuids |
| 83 | + .iter() |
| 84 | + .filter_map(|(key, expiry)| { |
| 85 | + if expiry.elapsed().is_zero() { |
| 86 | + Some(key.clone()) |
| 87 | + } else { |
| 88 | + None |
| 89 | + } |
| 90 | + }) |
| 91 | + .collect(); |
| 92 | + |
| 93 | + for key in expired_keys { |
| 94 | + self.seen_uuids.remove(&key); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + pub fn spawn(mut self, bundle_channel: mpsc::UnboundedSender<Bundle>) -> JoinHandle<()> { |
| 99 | + let handle: JoinHandle<()> = tokio::spawn(async move { |
| 100 | + loop { |
| 101 | + let bundle_channel = bundle_channel.clone(); |
| 102 | + let bundles = self.check_bundle_cache().await; |
| 103 | + |
| 104 | + match bundles { |
| 105 | + Ok(bundles) => { |
| 106 | + for bundle in bundles { |
| 107 | + let result = bundle_channel.send(bundle); |
| 108 | + if result.is_err() { |
| 109 | + tracing::debug!("bundle_channel failed to send bundle"); |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + Err(err) => { |
| 114 | + debug!(?err, "error fetching bundles from tx-pool"); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // evict expired bundles once every loop |
| 119 | + self.evict(); |
| 120 | + |
| 121 | + tokio::time::sleep(Duration::from_secs(self.config.tx_pool_poll_interval)).await; |
| 122 | + } |
| 123 | + }); |
| 124 | + |
| 125 | + handle |
| 126 | + } |
| 127 | +} |
0 commit comments