Add a method to return the block header at a given block

This commit is contained in:
James Wilson
2025-12-11 17:56:47 +00:00
parent 02d0c12019
commit 6215b15fdf
2 changed files with 44 additions and 0 deletions
+19
View File
@@ -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<T> {
self.client.block_hash()
}
/// The header for this block.
pub async fn block_header(&self) -> Result<T::Header, BlockError> {
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)
}
}
+25
View File
@@ -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)]