From 8e23a9fbcbf016aac224d2fafce488aebbb68ba0 Mon Sep 17 00:00:00 2001 From: guigou Date: Fri, 22 Nov 2024 11:28:18 +0100 Subject: [PATCH] add get_finalized_head method --- crates/pink-libs/subrpc/Cargo.toml | 2 +- crates/pink-libs/subrpc/src/lib.rs | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/pink-libs/subrpc/Cargo.toml b/crates/pink-libs/subrpc/Cargo.toml index 6d37d0629..b5639f7d7 100644 --- a/crates/pink-libs/subrpc/Cargo.toml +++ b/crates/pink-libs/subrpc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pink-subrpc" -version = "0.7.0" +version = "0.8.0" authors = ["Phala Network"] edition = "2021" license = "Apache-2.0" diff --git a/crates/pink-libs/subrpc/src/lib.rs b/crates/pink-libs/subrpc/src/lib.rs index 08dd81219..654dc6782 100644 --- a/crates/pink-libs/subrpc/src/lib.rs +++ b/crates/pink-libs/subrpc/src/lib.rs @@ -154,6 +154,24 @@ pub fn get_block_hash( Ok(H256(hash)) } +/// Gets the latest hash of the finalized header +pub fn get_finalized_head( + rpc_node: &str, +) -> core::result::Result { + let data = format!( + r#"{{"id":1, "jsonrpc":"2.0", "method": "chain_getFinalizedHead"}}"# + ) + .into_bytes(); + let resp_body = call_rpc(rpc_node, data)?; + let genesis_hash: GenesisHash = json::from_slice(&resp_body).or(Err(Error::InvalidBody))?; + // bypass prefix 0x + let genesis_hash_result = &genesis_hash.result[2..]; + let decoded_hash = hex::decode(genesis_hash_result).or(Err(Error::InvalidBody))?; + let hash: [u8; 32] = decoded_hash.try_into().or(Err(Error::InvalidBody))?; + Ok(H256(hash)) +} + + /// Gets revalant block header by given block hash /// Only work with chains define generic patterns like `Header` pub fn get_header( @@ -422,6 +440,13 @@ mod tests { ); } + #[test] + fn can_get_finalized_head() { + pink_chain_extension::mock_ext::mock_all_ext(); + let finalized_head = get_finalized_head("https://kusama-rpc.polkadot.io"); + assert!(finalized_head.is_ok(), "failed to query finalized_head"); + } + #[test] fn can_correctly_encode() { let genesis_hash: [u8; 32] =