diff --git a/subxt/src/blocks/block_types.rs b/subxt/src/blocks/block_types.rs index 09e913ace4..1f20b29fb5 100644 --- a/subxt/src/blocks/block_types.rs +++ b/subxt/src/blocks/block_types.rs @@ -73,6 +73,12 @@ pub enum ChainHeadError { Other(String), } +impl From for ChainHeadError { + fn from(error: Error) -> Self { + ChainHeadError::Other(error.to_string()) + } +} + impl TryFrom> for Vec { type Error = ChainHeadError; @@ -92,6 +98,43 @@ impl TryFrom> for Vec { } } +impl ChainHeadBlock +where + T: Config, + C: OnlineClientT, +{ + /// Wrapper to fetch the block's body from the `chainHead_body` subscription. + async fn fetch_body( + &self, + subscription_id: String, + hash: T::Hash, + ) -> Result>, ChainHeadError> { + let mut sub = self + .client + .rpc() + .subscribe_chainhead_body(subscription_id, hash) + .await?; + + if let Some(event) = sub.next().await { + let event = event?; + + let bytes = Vec::::try_from(event)?; + + let extrinsics: Vec> = + Decode::decode(&mut &bytes[..]).map_err(Into::::into)?; + return Ok(extrinsics) + } + + Err(Error::Other("Failed to fetch the block body".into()).into()) + } + + /// Fetch the body (vector of extrinsics) of this block. + pub async fn body(&self) -> Result>, ChainHeadError> { + self.fetch_body(self.subscription_id.clone(), self.hash) + .await + } +} + /// A representation of a block. pub struct Block { header: T::Header,