From 6215b15fdf2dd83efb8d0061ad2c38ccc314f45d Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 11 Dec 2025 17:56:47 +0000 Subject: [PATCH] Add a method to return the block header at a given block --- subxt/src/client.rs | 19 +++++++++++++++++++ subxt/src/error.rs | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/subxt/src/client.rs b/subxt/src/client.rs index fdbf9a942d..c8847b42f9 100644 --- a/subxt/src/client.rs +++ b/subxt/src/client.rs @@ -4,6 +4,7 @@ mod online_client; use crate::config::{Config, HashFor}; use crate::constants::ConstantsClient; use crate::custom_values::CustomValuesClient; +use crate::error::BlockError; use crate::events::EventsClient; use crate::extrinsics::ExtrinsicsClient; use crate::runtime_apis::RuntimeApisClient; @@ -105,4 +106,22 @@ where pub fn block_hash(&self) -> HashFor { self.client.block_hash() } + + /// The header for this block. + pub async fn block_header(&self) -> Result { + let block_hash = self.block_hash(); + let header = self + .client + .backend() + .block_header(block_hash) + .await + .map_err(|e| BlockError::CouldNotDownloadBlockHeader { + block_hash: block_hash.into(), + reason: e, + })? + .ok_or_else(|| BlockError::BlockNotFound { + block_hash: block_hash.into(), + })?; + Ok(header) + } } diff --git a/subxt/src/error.rs b/subxt/src/error.rs index ecfcc8263a..1548a61f27 100644 --- a/subxt/src/error.rs +++ b/subxt/src/error.rs @@ -40,6 +40,8 @@ pub enum Error { #[error(transparent)] ExtrinsicDecodeErrorAt(#[from] ExtrinsicDecodeErrorAt), #[error(transparent)] + BlockError(#[from] BlockError), + #[error(transparent)] ConstantError(#[from] ConstantError), #[error(transparent)] CustomValueError(#[from] CustomValueError), @@ -147,6 +149,7 @@ impl Error { Error::OnlineClientError(e) => e.backend_error(), Error::RuntimeApiError(e) => e.backend_error(), Error::EventsError(e) => e.backend_error(), + Error::BlockError(e) => e.backend_error(), Error::ExtrinsicError(e) => e.backend_error(), Error::ViewFunctionError(e) => e.backend_error(), Error::TransactionProgressError(e) => e.backend_error(), @@ -384,6 +387,28 @@ impl OnlineClientAtBlockError { } } +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +#[allow(missing_docs)] +pub enum BlockError { + #[error("Could not find the block with hash {block_hash}")] + BlockNotFound { block_hash: Hex }, + #[error("Could not download the block header with hash {block_hash}: {reason}")] + CouldNotDownloadBlockHeader { + block_hash: Hex, + reason: BackendError, + }, +} + +impl BlockError { + fn backend_error(&self) -> Option<&BackendError> { + match self { + BlockError::CouldNotDownloadBlockHeader { reason, .. } => Some(reason), + _ => None, + } + } +} + #[derive(Debug, thiserror::Error)] #[non_exhaustive] #[allow(missing_docs)]