Jelajahi Sumber

refactor: remove BlockStatus from API and related components for simplified block number retrieval

Daniel Chew 8 bulan lalu
induk
melakukan
118ea55c64

+ 2 - 7
apps/argus/src/api.rs

@@ -1,5 +1,5 @@
 use {
-    crate::chain::reader::{BlockStatus, PulseReader},
+    crate::chain::reader::PulseReader,
     anyhow::Result,
     axum::{
         body::Body,
@@ -81,9 +81,6 @@ pub struct BlockchainState {
     pub contract: Arc<dyn PulseReader>,
     /// The address of the provider that this server is operating for.
     pub provider_address: Address,
-    /// The BlockStatus of the block that is considered to be confirmed on the blockchain.
-    /// For eg., Finalized, Safe
-    pub confirmed_block_status: BlockStatus,
 }
 
 pub enum RestError {
@@ -159,7 +156,7 @@ mod test {
     use {
         crate::{
             api::{self, ApiState, BlockchainState},
-            chain::reader::{mock::MockPulseReader, BlockStatus},
+            chain::reader::mock::MockPulseReader,
         },
         axum::http::StatusCode,
         axum_test::{TestResponse, TestServer},
@@ -182,7 +179,6 @@ mod test {
             id: "ethereum".into(),
             contract: eth_read.clone(),
             provider_address: PROVIDER,
-            confirmed_block_status: BlockStatus::Latest,
         };
 
         let metrics_registry = Arc::new(RwLock::new(Registry::default()));
@@ -193,7 +189,6 @@ mod test {
             id: "avalanche".into(),
             contract: avax_read.clone(),
             provider_address: PROVIDER,
-            confirmed_block_status: BlockStatus::Latest,
         };
 
         let mut chains = HashMap::new();

+ 1 - 7
apps/argus/src/api/price_updates.rs

@@ -5,7 +5,6 @@ use {
         extract::{Path, Query, State},
         Json,
     },
-    tokio::try_join,
     utoipa::{IntoParams, ToSchema},
 };
 
@@ -47,12 +46,7 @@ pub async fn price_update(
 
     let maybe_request_fut = state.contract.get_request(sequence);
 
-    let current_block_number_fut = state
-        .contract
-        .get_block_number(state.confirmed_block_status);
-
-    let (maybe_request, _current_block_number) =
-        try_join!(maybe_request_fut, current_block_number_fut).map_err(|e| {
+    let maybe_request = maybe_request_fut.await.map_err(|e| {
             tracing::error!(chain_id = chain_id, "RPC request failed {}", e);
             RestError::TemporarilyUnavailable
         })?;

+ 1 - 2
apps/argus/src/api/ready.rs

@@ -4,7 +4,6 @@ use axum::{
 };
 
 pub async fn ready() -> Response {
-    // TODO: are there useful checks here? At the moment, everything important (specifically hash
-    // chain computation) occurs synchronously on startup.
+    // TODO: are there useful checks here? At the moment, everything important occurs synchronously on startup.
     (StatusCode::OK, "OK").into_response()
 }

+ 13 - 22
apps/argus/src/chain/ethereum.rs

@@ -1,10 +1,10 @@
 use {
     crate::{
         api::ChainId,
-        chain::reader::{self, BlockNumber, BlockStatus, PulseReader, RequestedWithCallbackEvent},
+        chain::reader::{self, BlockNumber, PulseReader, RequestedWithCallbackEvent},
         config::EthereumConfig,
     },
-    anyhow::{anyhow, Error, Result},
+    anyhow::{anyhow, Context, Result},
     axum::async_trait,
     ethers::{
         abi::RawLog,
@@ -14,7 +14,7 @@ use {
         prelude::JsonRpcClient,
         providers::{Http, Middleware, Provider},
         signers::{LocalWallet, Signer},
-        types::{BlockNumber as EthersBlockNumber, U256},
+        types::U256,
     },
     fortuna::eth_utils::{
         eth_gas_oracle::EthProviderOracle,
@@ -213,25 +213,17 @@ impl<T: JsonRpcClient + 'static> PulseReader for Pulse<Provider<T>> {
         }
     }
 
-    async fn get_block_number(&self, confirmed_block_status: BlockStatus) -> Result<BlockNumber> {
-        let block_number: EthersBlockNumber = confirmed_block_status.into();
+    async fn get_block_number(&self) -> Result<BlockNumber> {
         let block = self
             .client()
-            .get_block(block_number)
-            .await?
-            .ok_or_else(|| Error::msg("pending block confirmation"))?;
-
-        Ok(block
-            .number
-            .ok_or_else(|| Error::msg("pending confirmation"))?
-            .as_u64())
+            .get_block_number()
+            .await
+            .context("Failed to get block number")?;
+        Ok(block.as_u64())
     }
 
     async fn get_active_requests(&self, count: usize) -> Result<Vec<reader::Request>> {
-        let (requests, actual_count) = self
-            .get_first_active_requests(count.into())
-            .call()
-            .await?;
+        let (requests, actual_count) = self.get_first_active_requests(count.into()).call().await?;
 
         // Convert actual_count (U256) to usize safely
         let actual_count_usize = actual_count.as_u64() as usize;
@@ -306,11 +298,10 @@ impl<T: JsonRpcClient + 'static> Pulse<Provider<T>> {
         // The currentSequenceNumber is stored in the State struct at slot 0, offset 32 bytes
         // (after admin, pythFeeInWei, accruedFeesInWei, and pyth)
         let storage_slot = ethers::types::H256::zero();
-        let storage_value = self.client().get_storage_at(
-            self.address(),
-            storage_slot,
-            None,
-        ).await?;
+        let storage_value = self
+            .client()
+            .get_storage_at(self.address(), storage_slot, None)
+            .await?;
 
         // H256 is always 32 bytes, so we don't need to check the length
 

+ 7 - 33
apps/argus/src/chain/reader.rs

@@ -1,34 +1,11 @@
 use {
     anyhow::Result,
     axum::async_trait,
-    ethers::types::{Address, BlockNumber as EthersBlockNumber, U256},
+    ethers::types::{Address, U256},
 };
 
 pub type BlockNumber = u64;
 
-#[derive(
-    Copy, Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
-)]
-pub enum BlockStatus {
-    /// Latest block
-    #[default]
-    Latest,
-    /// Finalized block accepted as canonical
-    Finalized,
-    /// Safe head block
-    Safe,
-}
-
-impl From<BlockStatus> for EthersBlockNumber {
-    fn from(val: BlockStatus) -> Self {
-        match val {
-            BlockStatus::Latest => EthersBlockNumber::Latest,
-            BlockStatus::Finalized => EthersBlockNumber::Finalized,
-            BlockStatus::Safe => EthersBlockNumber::Safe,
-        }
-    }
-}
-
 #[derive(Clone)]
 pub struct RequestedWithCallbackEvent {
     pub sequence_number: u64,
@@ -43,7 +20,8 @@ pub trait PulseReader: Send + Sync {
     /// Get an in-flight request (if it exists)
     async fn get_request(&self, sequence_number: u64) -> Result<Option<Request>>;
 
-    async fn get_block_number(&self, confirmed_block_status: BlockStatus) -> Result<BlockNumber>;
+    /// Get the latest block number
+    async fn get_block_number(&self) -> Result<BlockNumber>;
 
     async fn get_price_update_requested_events(
         &self,
@@ -57,7 +35,8 @@ pub trait PulseReader: Send + Sync {
         from_block: BlockNumber,
         to_block: BlockNumber,
     ) -> Result<Vec<RequestedWithCallbackEvent>> {
-        self.get_price_update_requested_events(from_block, to_block).await
+        self.get_price_update_requested_events(from_block, to_block)
+            .await
     }
 
     /// Get active requests directly from contract storage
@@ -89,9 +68,7 @@ pub struct Request {
 #[cfg(test)]
 pub mod mock {
     use {
-        crate::chain::reader::{
-            BlockNumber, BlockStatus, PulseReader, Request, RequestedWithCallbackEvent,
-        },
+        crate::chain::reader::{BlockNumber, PulseReader, Request, RequestedWithCallbackEvent},
         anyhow::Result,
         axum::async_trait,
         ethers::types::{Address, U256},
@@ -164,10 +141,7 @@ pub mod mock {
                 .cloned())
         }
 
-        async fn get_block_number(
-            &self,
-            _confirmed_block_status: BlockStatus,
-        ) -> Result<BlockNumber> {
+        async fn get_block_number(&self) -> Result<BlockNumber> {
             Ok(*self.block_number.read().unwrap())
         }
 

+ 0 - 1
apps/argus/src/command/run.rs

@@ -235,7 +235,6 @@ async fn setup_chain_state(
         id: chain_id.clone(),
         contract,
         provider_address: *provider,
-        confirmed_block_status: chain_config.confirmed_block_status,
     };
     Ok(state)
 }

+ 1 - 6
apps/argus/src/config.rs

@@ -1,5 +1,5 @@
 use {
-    crate::{api::ChainId, chain::reader::BlockStatus},
+    crate::api::ChainId,
     anyhow::{anyhow, Result},
     clap::{crate_authors, crate_description, crate_name, crate_version, Args, Parser},
     ethers::types::Address,
@@ -115,11 +115,6 @@ pub struct EthereumConfig {
     /// Address of a Pyth Pulse contract to interact with.
     pub contract_addr: Address,
 
-    /// The BlockStatus of the block that is considered confirmed.
-    /// For example, Finalized, Safe, Latest
-    #[serde(default)]
-    pub confirmed_block_status: BlockStatus,
-
     /// Use the legacy transaction format (for networks without EIP 1559)
     #[serde(default)]
     pub legacy_tx: bool,

+ 1 - 1
apps/argus/src/keeper/request.rs

@@ -26,7 +26,7 @@ pub async fn get_latest_safe_block(chain_state: &BlockchainState) -> BlockNumber
     loop {
         match chain_state
             .contract
-            .get_block_number(chain_state.confirmed_block_status)
+            .get_block_number()
             .await
         {
             Ok(latest_confirmed_block) => {