use super::{AvailHeader, Error};
use primitive_types::H256;
use serde::{Deserialize, Deserializer};
use subxt_core::config::substrate::ConsensusEngineId;
use subxt_rpcs::{RpcClient, rpc_params};
#[derive(Debug, Clone, Deserialize)]
pub struct LegacyBlock {
pub block: Block,
pub justifications: Option<Vec<BlockJustification>>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Block {
pub header: AvailHeader,
#[serde(deserialize_with = "from_string_to_vec")]
pub extrinsics: Vec<Vec<u8>>,
}
fn from_string_to_vec<'de, D>(deserializer: D) -> Result<Vec<Vec<u8>>, D::Error>
where
D: Deserializer<'de>,
{
let buf = Vec::<String>::deserialize(deserializer)?;
let result: Result<Vec<Vec<u8>>, _> = buf
.into_iter()
.map(|x| const_hex::decode(x.trim_start_matches("0x")))
.collect();
match result {
Ok(res) => Ok(res),
Err(err) => Err(serde::de::Error::custom(err)),
}
}
pub type BlockJustification = (ConsensusEngineId, EncodedJustification);
pub type EncodedJustification = Vec<u8>;
pub async fn get_block(client: &RpcClient, at: Option<H256>) -> Result<Option<LegacyBlock>, Error> {
let params = rpc_params![at];
let res: Option<LegacyBlock> = client.request("chain_getBlock", params).await?;
let Some(value) = res else {
return Ok(None);
};
Ok(Some(value))
}
pub async fn get_block_hash(client: &RpcClient, block_height: Option<u32>) -> Result<Option<H256>, Error> {
let params = rpc_params![block_height];
let value = client.request("chain_getBlockHash", params).await?;
Ok(value)
}
pub async fn get_header(client: &RpcClient, at: Option<H256>) -> Result<Option<AvailHeader>, Error> {
let params = rpc_params![at];
let value = client.request("chain_getHeader", params).await?;
Ok(value)
}
pub async fn get_finalized_head(client: &RpcClient) -> Result<H256, Error> {
let value = client.request("chain_getFinalizedHead", rpc_params![]).await?;
Ok(value)
}