diff --git a/Cargo.toml b/Cargo.toml index 6689b57..a47c1ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,6 @@ hex = { package = "const-hex", version = "1", default-features = false, features ] } serde = { version = "1.0.197", features = ["derive"] } -tracing = "0.1.40" axum = "0.7.5" eyre = "0.6.12" @@ -61,5 +60,4 @@ tokio = { version = "1.36.0", features = ["full", "macros", "rt-multi-thread"] } async-trait = "0.1.80" oauth2 = "4.4.2" -tracing-subscriber = "0.3.19" chrono = "0.4.41" diff --git a/bin/builder.rs b/bin/builder.rs index 86cd191..0611245 100644 --- a/bin/builder.rs +++ b/bin/builder.rs @@ -8,6 +8,7 @@ use builder::{ }; use init4_bin_base::{deps::tracing, utils::from_env::FromEnv}; use signet_sim::SimCache; +use signet_types::constants::SignetSystemConstants; use std::sync::Arc; use tokio::select; use tracing::info_span; @@ -20,7 +21,7 @@ async fn main() -> eyre::Result<()> { let init_span_guard = info_span!("builder initialization"); let config = BuilderConfig::from_env()?.clone(); - let constants = config.load_pecorino_constants(); + let constants = SignetSystemConstants::pecorino(); let authenticator = Authenticator::new(&config)?; let (host_provider, sequencer_signer) = diff --git a/bin/submit_transaction.rs b/bin/submit_transaction.rs index 55e2dbe..1c46427 100644 --- a/bin/submit_transaction.rs +++ b/bin/submit_transaction.rs @@ -7,7 +7,10 @@ use alloy::{ }; use builder::config::HostProvider; use init4_bin_base::{ - deps::metrics::{counter, histogram}, + deps::{ + metrics::{counter, histogram}, + tracing, + }, init4, utils::from_env::FromEnv, }; @@ -45,11 +48,10 @@ impl Config { #[tokio::main] async fn main() { - init4(); - - tracing::trace!("connecting to provider"); + let _guard = init4(); let config = Config::from_env().unwrap(); + tracing::trace!("connecting to provider"); let provider = config.provider().await; let recipient_address = config.recipient_address; let sleep_time = config.sleep_time; diff --git a/src/config.rs b/src/config.rs index 3a1a6a9..69d31b2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,4 @@ -use crate::{ - constants, - signer::{LocalOrAws, SignerError}, -}; +use crate::signer::{LocalOrAws, SignerError}; use alloy::{ network::{Ethereum, EthereumWallet}, primitives::Address, @@ -16,7 +13,6 @@ use alloy::{ use eyre::Result; use init4_bin_base::utils::{calc::SlotCalculator, from_env::FromEnv}; use oauth2::url; -use signet_types::config::{HostConfig, PredeployTokens, RollupConfig, SignetSystemConstants}; use signet_zenith::Zenith; use std::borrow::Cow; @@ -210,30 +206,4 @@ impl BuilderConfig { pub const fn connect_zenith(&self, provider: HostProvider) -> ZenithInstance { Zenith::new(self.zenith_address, provider) } - - /// Loads the Signet system constants for Pecorino. - pub const fn load_pecorino_constants(&self) -> SignetSystemConstants { - let host = HostConfig::new( - self.host_chain_id, - constants::PECORINO_DEPLOY_HEIGHT, - self.zenith_address, - constants::HOST_ORDERS, - constants::HOST_PASSAGE, - constants::HOST_TRANSACTOR, - PredeployTokens::new(constants::HOST_USDC, constants::HOST_USDT, constants::HOST_WBTC), - ); - let rollup = RollupConfig::new( - self.ru_chain_id, - constants::ROLLUP_ORDERS, - constants::ROLLUP_PASSAGE, - constants::BASE_FEE_RECIPIENT, - PredeployTokens::new( - constants::ROLLUP_USDC, - constants::ROLLUP_USDT, - constants::ROLLUP_WBTC, - ), - ); - - SignetSystemConstants::new(host, rollup) - } } diff --git a/src/lib.rs b/src/lib.rs index 1f64552..b1f8c05 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,4 +35,3 @@ pub mod test_utils; // Anonymous import suppresses warnings about unused imports. use openssl as _; -use tracing_subscriber as _; diff --git a/src/service.rs b/src/service.rs index 446d737..cea3b62 100644 --- a/src/service.rs +++ b/src/service.rs @@ -4,6 +4,7 @@ use axum::{ response::{IntoResponse, Response}, routing::get, }; +use init4_bin_base::deps::tracing::error; use std::net::SocketAddr; /// Return a 404 Not Found response @@ -25,11 +26,11 @@ pub fn serve_builder(socket: impl Into) -> tokio::task::JoinHandle<( match tokio::net::TcpListener::bind(&addr).await { Ok(listener) => { if let Err(err) = axum::serve(listener, router).await { - tracing::error!(%err, "serve failed"); + error!(%err, "serve failed"); } } Err(err) => { - tracing::error!(%err, "failed to bind to the address"); + error!(%err, "failed to bind to the address"); } }; }) diff --git a/src/tasks/block.rs b/src/tasks/block.rs index fd5b9ea..29f583b 100644 --- a/src/tasks/block.rs +++ b/src/tasks/block.rs @@ -15,9 +15,12 @@ use alloy::{ }; use chrono::{DateTime, Utc}; use eyre::Report; -use init4_bin_base::utils::calc::SlotCalculator; +use init4_bin_base::{ + deps::tracing::{debug, error, info, warn}, + utils::calc::SlotCalculator, +}; use signet_sim::{BlockBuild, BuiltBlock, SimCache}; -use signet_types::config::SignetSystemConstants; +use signet_types::constants::SignetSystemConstants; use std::{ sync::{ Arc, @@ -118,7 +121,7 @@ impl Simulator { ); let block = block_build.build().await; - tracing::debug!(block = ?block, "finished block simulation"); + debug!(block = ?block, "finished block simulation"); Ok(block) } @@ -142,7 +145,7 @@ impl Simulator { bundle_receiver: mpsc::UnboundedReceiver, cache: SimCache, ) -> (JoinHandle<()>, JoinHandle<()>) { - tracing::debug!("starting up cache handler"); + debug!("starting up cache handler"); let basefee_price = Arc::new(AtomicU64::new(0_u64)); let basefee_reader = Arc::clone(&basefee_price); @@ -170,13 +173,13 @@ impl Simulator { /// /// - `price`: A shared `Arc` used to store the updated basefee value. async fn basefee_updater(self: Arc, price: Arc) { - tracing::debug!("starting basefee updater"); + debug!("starting basefee updater"); loop { // calculate start of next slot plus a small buffer let time_remaining = self.slot_calculator.slot_duration() - self.slot_calculator.current_timepoint_within_slot() + 1; - tracing::debug!(time_remaining = ?time_remaining, "basefee updater sleeping until next slot"); + debug!(time_remaining = ?time_remaining, "basefee updater sleeping until next slot"); // wait until that point in time sleep(Duration::from_secs(time_remaining)).await; @@ -199,15 +202,15 @@ impl Simulator { /// - `price`: A shared `Arc` used to store the updated basefee. async fn check_basefee(&self, price: &Arc) { let resp = self.ru_provider.get_block_by_number(Latest).await.inspect_err(|e| { - tracing::error!(error = %e, "RPC error during basefee update"); + error!(error = %e, "RPC error during basefee update"); }); if let Ok(Some(block)) = resp { let basefee = block.header.base_fee_per_gas.unwrap_or(0); price.store(basefee, Ordering::Relaxed); - tracing::debug!(basefee = basefee, "basefee updated"); + debug!(basefee = basefee, "basefee updated"); } else { - tracing::warn!("get basefee failed - an error likely occurred"); + warn!("get basefee failed - an error likely occurred"); } } @@ -229,7 +232,7 @@ impl Simulator { cache: SimCache, submit_sender: mpsc::UnboundedSender, ) -> JoinHandle<()> { - tracing::debug!("starting builder task"); + debug!("starting builder task"); tokio::spawn(async move { self.run_simulator(constants, cache, submit_sender).await }) } @@ -261,19 +264,19 @@ impl Simulator { let block_env = match self.next_block_env(finish_by).await { Ok(block) => block, Err(err) => { - tracing::error!(err = %err, "failed to configure next block"); + error!(err = %err, "failed to configure next block"); break; } }; - tracing::info!(block_env = ?block_env, "created block"); + info!(block_env = ?block_env, "created block"); match self.handle_build(constants, sim_cache, finish_by, block_env).await { Ok(block) => { - tracing::debug!(block = ?block, "built block"); + debug!(block = ?block, "built block"); let _ = submit_sender.send(block); } Err(e) => { - tracing::error!(err = %e, "failed to build block"); + error!(err = %e, "failed to build block"); continue; } } @@ -306,7 +309,7 @@ impl Simulator { let latest = match self.ru_provider.get_block_number().await { Ok(block_number) => block_number, Err(e) => { - tracing::error!(error = %e, "failed to get latest block number"); + error!(error = %e, "failed to get latest block number"); return None; } }; @@ -336,27 +339,27 @@ impl Simulator { let remaining = finish_by.duration_since(Instant::now()); let finish_time = SystemTime::now() + remaining; let deadline: DateTime = finish_time.into(); - tracing::debug!(deadline = %deadline, "preparing block env"); + debug!(deadline = %deadline, "preparing block env"); // Fetch the latest block number and increment it by 1 let latest_block_number = match self.ru_provider.get_block_number().await { Ok(num) => num, Err(err) => { - tracing::error!(error = %err, "RPC error during block build"); + error!(error = %err, "RPC error during block build"); return Err(SimulatorError::Rpc(Report::new(err))); } }; - tracing::debug!(next_block_num = latest_block_number + 1, "preparing block env"); + debug!(next_block_num = latest_block_number + 1, "preparing block env"); // Fetch the basefee from previous block to calculate gas for this block let basefee = match self.get_basefee().await? { Some(basefee) => basefee, None => { - tracing::warn!("get basefee failed - RPC error likely occurred"); + warn!("get basefee failed - RPC error likely occurred"); BASEFEE_DEFAULT } }; - tracing::debug!(basefee = basefee, "setting basefee"); + debug!(basefee = basefee, "setting basefee"); // Craft the Block environment to pass to the simulator let block_env = PecorinoBlockEnv::new( @@ -365,7 +368,7 @@ impl Simulator { deadline.timestamp() as u64, basefee, ); - tracing::debug!(block_env = ?block_env, "prepared block env"); + debug!(block_env = ?block_env, "prepared block env"); Ok(block_env) } @@ -380,7 +383,7 @@ impl Simulator { match self.ru_provider.get_block_by_number(Latest).await { Ok(maybe_block) => match maybe_block { Some(block) => { - tracing::debug!(basefee = ?block.header.base_fee_per_gas, "basefee found"); + debug!(basefee = ?block.header.base_fee_per_gas, "basefee found"); Ok(block.header.base_fee_per_gas) } None => Ok(None), @@ -414,13 +417,13 @@ async fn cache_updater( select! { maybe_tx = tx_receiver.recv() => { if let Some(tx) = maybe_tx { - tracing::debug!(tx = ?tx.hash(), "received transaction"); + debug!(tx = ?tx.hash(), "received transaction"); cache.add_item(tx, p); } } maybe_bundle = bundle_receiver.recv() => { if let Some(bundle) = maybe_bundle { - tracing::debug!(bundle = ?bundle.id, "received bundle"); + debug!(bundle = ?bundle.id, "received bundle"); cache.add_item(bundle.bundle, p); } } diff --git a/src/tasks/bundler.rs b/src/tasks/bundler.rs index 54f8828..192b8ad 100644 --- a/src/tasks/bundler.rs +++ b/src/tasks/bundler.rs @@ -1,5 +1,6 @@ //! Bundler service responsible for fetching bundles and sending them to the simulator. -use crate::tasks::oauth::SharedToken; +use crate::{config::BuilderConfig, tasks::oauth::SharedToken}; +use init4_bin_base::deps::tracing::{Instrument, debug, debug_span, error, trace, warn}; use oauth2::TokenResponse; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; @@ -7,9 +8,6 @@ use signet_bundle::SignetEthBundle; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; use tokio::task::JoinHandle; use tokio::time; -use tracing::{Instrument, debug, trace, warn}; - -pub use crate::config::BuilderConfig; /// Holds a bundle from the cache with a unique ID and a Zenith bundle. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -80,7 +78,7 @@ impl BundlePoller { async fn task_future(mut self, outbound: UnboundedSender) { loop { - let span = tracing::debug_span!("BundlePoller::loop", url = %self.config.tx_pool_url); + let span = debug_span!("BundlePoller::loop", url = %self.config.tx_pool_url); // Enter the span for the next check. let _guard = span.enter(); @@ -96,10 +94,10 @@ impl BundlePoller { match self.check_bundle_cache().instrument(span.clone()).await { Ok(bundles) => { - tracing::debug!(count = ?bundles.len(), "found bundles"); + debug!(count = ?bundles.len(), "found bundles"); for bundle in bundles.into_iter() { if let Err(err) = outbound.send(bundle) { - tracing::error!(err = ?err, "Failed to send bundle - channel is dropped"); + error!(err = ?err, "Failed to send bundle - channel is dropped"); } } } diff --git a/src/tasks/metrics.rs b/src/tasks/metrics.rs index 6b41196..f406b30 100644 --- a/src/tasks/metrics.rs +++ b/src/tasks/metrics.rs @@ -1,9 +1,11 @@ use crate::config::HostProvider; use alloy::{primitives::TxHash, providers::Provider as _}; -use init4_bin_base::deps::metrics::{counter, histogram}; +use init4_bin_base::deps::{ + metrics::{counter, histogram}, + tracing::{debug, error}, +}; use std::time::Instant; use tokio::{sync::mpsc, task::JoinHandle}; -use tracing::{debug, error}; /// Collects metrics on transactions sent by the Builder #[derive(Debug, Clone)] @@ -68,7 +70,7 @@ impl MetricsTask { debug!("logged tx metrics"); }); } else { - tracing::debug!("upstream task gone"); + debug!("upstream task gone"); break; } } diff --git a/src/tasks/oauth.rs b/src/tasks/oauth.rs index b402a88..ffe03b8 100644 --- a/src/tasks/oauth.rs +++ b/src/tasks/oauth.rs @@ -1,6 +1,7 @@ //! Service responsible for authenticating with the cache with Oauth tokens. //! This authenticator periodically fetches a new token every set amount of seconds. use crate::config::BuilderConfig; +use init4_bin_base::deps::tracing::{error, info}; use oauth2::{ AuthUrl, ClientId, ClientSecret, EmptyExtraTokenFields, StandardTokenResponse, TokenUrl, basic::{BasicClient, BasicTokenType}, @@ -93,13 +94,13 @@ impl Authenticator { let handle: JoinHandle<()> = tokio::spawn(async move { loop { - tracing::info!("Refreshing oauth token"); + info!("Refreshing oauth token"); match self.authenticate().await { Ok(_) => { - tracing::info!("Successfully refreshed oauth token"); + info!("Successfully refreshed oauth token"); } Err(e) => { - tracing::error!(%e, "Failed to refresh oauth token"); + error!(%e, "Failed to refresh oauth token"); } }; let _sleep = tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await; diff --git a/src/tasks/submit.rs b/src/tasks/submit.rs index ff5db52..34c665b 100644 --- a/src/tasks/submit.rs +++ b/src/tasks/submit.rs @@ -16,7 +16,10 @@ use alloy::{ transports::TransportError, }; use eyre::{bail, eyre}; -use init4_bin_base::deps::metrics::{counter, histogram}; +use init4_bin_base::deps::{ + metrics::{counter, histogram}, + tracing::{self, debug, error, info, instrument, trace, warn}, +}; use oauth2::TokenResponse; use signet_sim::BuiltBlock; use signet_types::{SignRequest, SignResponse}; @@ -26,7 +29,6 @@ use signet_zenith::{ }; use std::time::Instant; use tokio::{sync::mpsc, task::JoinHandle}; -use tracing::{debug, error, instrument, trace}; macro_rules! spawn_provider_send { ($provider:expr, $tx:expr) => { @@ -35,7 +37,7 @@ macro_rules! spawn_provider_send { let t = $tx.clone(); tokio::spawn(async move { p.send_tx_envelope(t).await.inspect_err(|e| { - tracing::warn!(%e, "error in transaction broadcast") + warn!(%e, "error in transaction broadcast") }) }) } @@ -75,7 +77,7 @@ pub struct SubmitTask { impl SubmitTask { #[instrument(skip(self))] async fn sup_quincey(&self, sig_request: &SignRequest) -> eyre::Result { - tracing::info!( + info!( host_block_number = %sig_request.host_block_number, ru_chain_id = %sig_request.ru_chain_id, "pinging quincey for signature" @@ -192,7 +194,7 @@ impl SubmitTask { resp: &SignResponse, tx: TransactionRequest, ) -> Result { - tracing::debug!( + debug!( host_block_number = %resp.req.host_block_number, gas_limit = %resp.req.gas_limit, "sending transaction to network" @@ -212,17 +214,17 @@ impl SubmitTask { // send the in-progress transaction over the outbound_tx_channel if self.outbound_tx_channel.send(*tx.tx_hash()).is_err() { - tracing::error!("receipts task gone"); + error!("receipts task gone"); } // question mark unwraps join error, which would be an internal panic // then if let checks for rpc error if let Err(e) = fut.await? { - tracing::error!(error = %e, "Primary tx broadcast failed. Skipping transaction."); + error!(error = %e, "Primary tx broadcast failed. Skipping transaction."); return Ok(ControlFlow::Skip); } - tracing::info!( + info!( tx_hash = %tx.tx_hash(), ru_chain_id = %resp.req.ru_chain_id, gas_limit = %resp.req.gas_limit, @@ -234,16 +236,16 @@ impl SubmitTask { #[instrument(skip_all, err)] async fn handle_inbound(&self, block: &BuiltBlock) -> eyre::Result { - tracing::info!(txns = block.tx_count(), "handling inbound block"); + info!(txns = block.tx_count(), "handling inbound block"); let sig_request = match self.construct_sig_request(block).await { Ok(sig_request) => sig_request, Err(e) => { - tracing::error!(error = %e, "error constructing signature request"); + error!(error = %e, "error constructing signature request"); return Ok(ControlFlow::Skip); } }; - tracing::debug!( + debug!( host_block_number = %sig_request.host_block_number, ru_chain_id = %sig_request.ru_chain_id, "constructed signature request for host block" @@ -253,23 +255,17 @@ impl SubmitTask { // quincey (politely) let signed = if let Some(signer) = &self.sequencer_signer { let sig = signer.sign_hash(&sig_request.signing_hash()).await?; - tracing::debug!( - sig = hex::encode(sig.as_bytes()), - "acquired signature from local signer" - ); + debug!(sig = hex::encode(sig.as_bytes()), "acquired signature from local signer"); SignResponse { req: sig_request, sig } } else { let resp: SignResponse = match self.sup_quincey(&sig_request).await { Ok(resp) => resp, Err(e) => { - tracing::error!(error = %e, "error acquiring signature from quincey"); + error!(error = %e, "error acquiring signature from quincey"); return Ok(ControlFlow::Retry); } }; - tracing::debug!( - sig = hex::encode(resp.sig.as_bytes()), - "acquired signature from quincey" - ); + debug!(sig = hex::encode(resp.sig.as_bytes()), "acquired signature from quincey"); counter!("builder.quincey_signature_acquired").increment(1); resp }; @@ -293,36 +289,34 @@ impl SubmitTask { counter!("builder.building_too_many_retries").increment(1); histogram!("builder.block_build_time") .record(building_start_time.elapsed().as_millis() as f64); - tracing::error!( - "error handling inbound block: too many retries" - ); + error!("error handling inbound block: too many retries"); break; } - tracing::error!("error handling inbound block: retrying"); + error!("error handling inbound block: retrying"); tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; } Ok(ControlFlow::Skip) => { histogram!("builder.block_build_time") .record(building_start_time.elapsed().as_millis() as f64); counter!("builder.skipped_blocks").increment(1); - tracing::info!("skipping block"); + info!("skipping block"); break; } Ok(ControlFlow::Done) => { histogram!("builder.block_build_time") .record(building_start_time.elapsed().as_millis() as f64); counter!("builder.submitted_successful_blocks").increment(1); - tracing::info!("block landed successfully"); + info!("block landed successfully"); break; } Err(e) => { - tracing::error!(error = %e, "error handling inbound block"); + error!(error = %e, "error handling inbound block"); break; } } } } else { - tracing::debug!("upstream task gone"); + debug!("upstream task gone"); break; } } diff --git a/src/tasks/tx_poller.rs b/src/tasks/tx_poller.rs index bbf2b53..a4655b5 100644 --- a/src/tasks/tx_poller.rs +++ b/src/tasks/tx_poller.rs @@ -2,11 +2,11 @@ use crate::config::BuilderConfig; use alloy::consensus::TxEnvelope; use eyre::Error; +use init4_bin_base::deps::tracing::{Instrument, debug, debug_span, trace}; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use serde_json::from_slice; use tokio::{sync::mpsc, task::JoinHandle, time}; -use tracing::{Instrument, debug, trace}; /// Models a response from the transaction pool. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -50,7 +50,7 @@ impl TxPoller { async fn task_future(mut self, outbound: mpsc::UnboundedSender) { loop { - let span = tracing::debug_span!("TxPoller::loop", url = %self.config.tx_pool_url); + let span = debug_span!("TxPoller::loop", url = %self.config.tx_pool_url); // Enter the span for the next check. let _guard = span.enter(); diff --git a/src/test_utils.rs b/src/test_utils.rs index 1102835..457eb17 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -11,12 +11,16 @@ use alloy::{ }; use chrono::{DateTime, Utc}; use eyre::Result; -use init4_bin_base::utils::calc::SlotCalculator; +use init4_bin_base::{ + deps::tracing_subscriber::{ + EnvFilter, Layer, fmt, layer::SubscriberExt, registry, util::SubscriberInitExt, + }, + utils::calc::SlotCalculator, +}; use std::{ str::FromStr, time::{Instant, SystemTime}, }; -use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::SubscriberInitExt}; /// Sets up a block builder with test values pub fn setup_test_config() -> Result { @@ -77,8 +81,8 @@ pub fn new_signed_tx( pub fn setup_logging() { // Initialize logging let filter = EnvFilter::from_default_env(); - let fmt = tracing_subscriber::fmt::layer().with_filter(filter); - let registry = tracing_subscriber::registry().with(fmt); + let fmt = fmt::layer().with_filter(filter); + let registry = registry().with(fmt); let _ = registry.try_init(); } diff --git a/tests/block_builder_test.rs b/tests/block_builder_test.rs index 739189e..8771873 100644 --- a/tests/block_builder_test.rs +++ b/tests/block_builder_test.rs @@ -15,6 +15,7 @@ mod tests { }; use init4_bin_base::utils::calc::SlotCalculator; use signet_sim::{SimCache, SimItem}; + use signet_types::constants::SignetSystemConstants; use std::{ sync::Arc, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, @@ -33,7 +34,7 @@ mod tests { // Make a test config let config = setup_test_config().unwrap(); - let constants = config.load_pecorino_constants(); + let constants = SignetSystemConstants::pecorino(); // Create an anvil instance for testing let anvil_instance = Anvil::new().chain_id(PECORINO_CHAIN_ID).spawn(); @@ -90,7 +91,7 @@ mod tests { // Make a test config let config = setup_test_config().unwrap(); - let constants = config.load_pecorino_constants(); + let constants = SignetSystemConstants::pecorino(); // Create an anvil instance for testing let anvil_instance = Anvil::new().chain_id(PECORINO_CHAIN_ID).spawn();