use std::sync::Arc;
use codec::{Decode, Encode};
use crate::{error::Error, utils::PhantomDataSendSync, Config, Metadata};
use super::{
rpc_params,
types::{self, ChainHeadEvent, FollowEvent},
RpcClient, RpcClientT, Subscription,
};
pub struct Rpc<T: Config> {
client: RpcClient,
_marker: PhantomDataSendSync<T>,
}
impl<T: Config> Clone for Rpc<T> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
_marker: PhantomDataSendSync::new(),
}
}
}
impl<T: Config> std::ops::Deref for Rpc<T> {
type Target = RpcClient;
fn deref(&self) -> &Self::Target {
&self.client
}
}
impl<T: Config> Rpc<T> {
pub fn new<R: RpcClientT>(client: Arc<R>) -> Self {
Self {
client: RpcClient::new(client),
_marker: PhantomDataSendSync::new(),
}
}
pub async fn storage(
&self,
key: &[u8],
hash: Option<T::Hash>,
) -> Result<Option<types::StorageData>, Error> {
let params = rpc_params![to_hex(key), hash];
let data = self.client.request("state_getStorage", params).await?;
Ok(data)
}
pub async fn storage_keys_paged(
&self,
key: &[u8],
count: u32,
start_key: Option<&[u8]>,
hash: Option<T::Hash>,
) -> Result<Vec<types::StorageKey>, Error> {
let start_key = start_key.map(to_hex);
let params = rpc_params![to_hex(key), count, start_key, hash];
let data = self.client.request("state_getKeysPaged", params).await?;
Ok(data)
}
pub async fn query_storage(
&self,
keys: impl IntoIterator<Item = &[u8]>,
from: T::Hash,
to: Option<T::Hash>,
) -> Result<Vec<types::StorageChangeSet<T::Hash>>, Error> {
let keys: Vec<String> = keys.into_iter().map(to_hex).collect();
let params = rpc_params![keys, from, to];
self.client
.request("state_queryStorage", params)
.await
.map_err(Into::into)
}
pub async fn query_storage_at(
&self,
keys: impl IntoIterator<Item = &[u8]>,
at: Option<T::Hash>,
) -> Result<Vec<types::StorageChangeSet<T::Hash>>, Error> {
let keys: Vec<String> = keys.into_iter().map(to_hex).collect();
let params = rpc_params![keys, at];
self.client
.request("state_queryStorageAt", params)
.await
.map_err(Into::into)
}
pub async fn genesis_hash(&self) -> Result<T::Hash, Error> {
let block_zero = 0u32;
let params = rpc_params![block_zero];
let genesis_hash: Option<T::Hash> =
self.client.request("chain_getBlockHash", params).await?;
genesis_hash.ok_or_else(|| "Genesis hash not found".into())
}
pub async fn metadata_legacy(&self, at: Option<T::Hash>) -> Result<Metadata, Error> {
let bytes: types::Bytes = self
.client
.request("state_getMetadata", rpc_params![at])
.await?;
let metadata = Metadata::decode(&mut &bytes[..])?;
Ok(metadata)
}
pub async fn system_properties(&self) -> Result<types::SystemProperties, Error> {
self.client
.request("system_properties", rpc_params![])
.await
}
pub async fn system_health(&self) -> Result<types::Health, Error> {
self.client.request("system_health", rpc_params![]).await
}
pub async fn system_chain(&self) -> Result<String, Error> {
self.client.request("system_chain", rpc_params![]).await
}
pub async fn system_name(&self) -> Result<String, Error> {
self.client.request("system_name", rpc_params![]).await
}
pub async fn system_version(&self) -> Result<String, Error> {
self.client.request("system_version", rpc_params![]).await
}
pub async fn header(&self, hash: Option<T::Hash>) -> Result<Option<T::Header>, Error> {
let params = rpc_params![hash];
let header = self.client.request("chain_getHeader", params).await?;
Ok(header)
}
pub async fn block_hash(
&self,
block_number: Option<types::BlockNumber>,
) -> Result<Option<T::Hash>, Error> {
let params = rpc_params![block_number];
let block_hash = self.client.request("chain_getBlockHash", params).await?;
Ok(block_hash)
}
pub async fn finalized_head(&self) -> Result<T::Hash, Error> {
let hash = self
.client
.request("chain_getFinalizedHead", rpc_params![])
.await?;
Ok(hash)
}
pub async fn block(
&self,
hash: Option<T::Hash>,
) -> Result<Option<types::ChainBlockResponse<T>>, Error> {
let params = rpc_params![hash];
let block = self.client.request("chain_getBlock", params).await?;
Ok(block)
}
pub async fn block_stats(
&self,
block_hash: T::Hash,
) -> Result<Option<types::BlockStats>, Error> {
let params = rpc_params![block_hash];
let stats = self.client.request("dev_getBlockStats", params).await?;
Ok(stats)
}
pub async fn read_proof(
&self,
keys: impl IntoIterator<Item = &[u8]>,
hash: Option<T::Hash>,
) -> Result<types::ReadProof<T::Hash>, Error> {
let keys: Vec<String> = keys.into_iter().map(to_hex).collect();
let params = rpc_params![keys, hash];
let proof = self.client.request("state_getReadProof", params).await?;
Ok(proof)
}
pub async fn runtime_version(
&self,
at: Option<T::Hash>,
) -> Result<types::RuntimeVersion, Error> {
let params = rpc_params![at];
let version = self
.client
.request("state_getRuntimeVersion", params)
.await?;
Ok(version)
}
pub async fn subscribe_best_block_headers(&self) -> Result<Subscription<T::Header>, Error> {
let subscription = self
.client
.subscribe(
"chain_subscribeNewHeads",
rpc_params![],
"chain_unsubscribeNewHeads",
)
.await?;
Ok(subscription)
}
pub async fn subscribe_all_block_headers(&self) -> Result<Subscription<T::Header>, Error> {
let subscription = self
.client
.subscribe(
"chain_subscribeAllHeads",
rpc_params![],
"chain_unsubscribeAllHeads",
)
.await?;
Ok(subscription)
}
pub async fn subscribe_finalized_block_headers(
&self,
) -> Result<Subscription<T::Header>, Error> {
let subscription = self
.client
.subscribe(
"chain_subscribeFinalizedHeads",
rpc_params![],
"chain_unsubscribeFinalizedHeads",
)
.await?;
Ok(subscription)
}
pub async fn subscribe_runtime_version(
&self,
) -> Result<Subscription<types::RuntimeVersion>, Error> {
let subscription = self
.client
.subscribe(
"state_subscribeRuntimeVersion",
rpc_params![],
"state_unsubscribeRuntimeVersion",
)
.await?;
Ok(subscription)
}
pub async fn submit_extrinsic<X: Encode>(&self, extrinsic: X) -> Result<T::Hash, Error> {
let bytes: types::Bytes = extrinsic.encode().into();
let params = rpc_params![bytes];
let xt_hash = self
.client
.request("author_submitExtrinsic", params)
.await?;
Ok(xt_hash)
}
pub async fn state_call_raw(
&self,
function: &str,
call_parameters: Option<&[u8]>,
at: Option<T::Hash>,
) -> Result<types::Bytes, Error> {
let call_parameters = call_parameters.unwrap_or_default();
let bytes: types::Bytes = self
.client
.request(
"state_call",
rpc_params![function, to_hex(call_parameters), at],
)
.await?;
Ok(bytes)
}
pub async fn state_call<Res: Decode>(
&self,
function: &str,
call_parameters: Option<&[u8]>,
at: Option<T::Hash>,
) -> Result<Res, Error> {
let bytes = self.state_call_raw(function, call_parameters, at).await?;
let cursor = &mut &bytes[..];
let res: Res = Decode::decode(cursor)?;
Ok(res)
}
pub async fn metadata_at_version(&self, version: u32) -> Result<Metadata, Error> {
let param = version.encode();
let opaque: Option<frame_metadata::OpaqueMetadata> = self
.state_call("Metadata_metadata_at_version", Some(¶m), None)
.await?;
let bytes = opaque.ok_or(Error::Other("Metadata version not found".into()))?;
let metadata: Metadata = Decode::decode(&mut &bytes.0[..])?;
Ok(metadata)
}
pub async fn metadata(&self) -> Result<Metadata, Error> {
let bytes: frame_metadata::OpaqueMetadata =
self.state_call("Metadata_metadata", None, None).await?;
let metadata: Metadata = Decode::decode(&mut &bytes.0[..])?;
Ok(metadata)
}
pub async fn watch_extrinsic<X: Encode>(
&self,
extrinsic: X,
) -> Result<Subscription<types::SubstrateTxStatus<T::Hash, T::Hash>>, Error> {
let bytes: types::Bytes = extrinsic.encode().into();
let params = rpc_params![bytes];
let subscription = self
.client
.subscribe(
"author_submitAndWatchExtrinsic",
params,
"author_unwatchExtrinsic",
)
.await?;
Ok(subscription)
}
pub async fn insert_key(
&self,
key_type: String,
suri: String,
public: types::Bytes,
) -> Result<(), Error> {
let params = rpc_params![key_type, suri, public];
self.client.request("author_insertKey", params).await?;
Ok(())
}
pub async fn rotate_keys(&self) -> Result<types::Bytes, Error> {
self.client
.request("author_rotateKeys", rpc_params![])
.await
}
pub async fn has_session_keys(&self, session_keys: types::Bytes) -> Result<bool, Error> {
let params = rpc_params![session_keys];
self.client.request("author_hasSessionKeys", params).await
}
pub async fn has_key(&self, public_key: types::Bytes, key_type: String) -> Result<bool, Error> {
let params = rpc_params![public_key, key_type];
self.client.request("author_hasKey", params).await
}
pub async fn dry_run(
&self,
encoded_signed: &[u8],
at: Option<T::Hash>,
) -> Result<types::DryRunResultBytes, Error> {
let params = rpc_params![to_hex(encoded_signed), at];
let result_bytes: types::Bytes = self.client.request("system_dryRun", params).await?;
Ok(types::DryRunResultBytes(result_bytes.0))
}
pub async fn chainhead_unstable_follow(
&self,
runtime_updates: bool,
) -> Result<Subscription<FollowEvent<T::Hash>>, Error> {
let subscription = self
.client
.subscribe(
"chainHead_unstable_follow",
rpc_params![runtime_updates],
"chainHead_unstable_unfollow",
)
.await?;
Ok(subscription)
}
pub async fn chainhead_unstable_body(
&self,
subscription_id: String,
hash: T::Hash,
) -> Result<Subscription<ChainHeadEvent<String>>, Error> {
let subscription = self
.client
.subscribe(
"chainHead_unstable_body",
rpc_params![subscription_id, hash],
"chainHead_unstable_stopBody",
)
.await?;
Ok(subscription)
}
pub async fn chainhead_unstable_header(
&self,
subscription_id: String,
hash: T::Hash,
) -> Result<Option<String>, Error> {
let header = self
.client
.request(
"chainHead_unstable_header",
rpc_params![subscription_id, hash],
)
.await?;
Ok(header)
}
pub async fn chainhead_unstable_storage(
&self,
subscription_id: String,
hash: T::Hash,
key: &[u8],
child_key: Option<&[u8]>,
) -> Result<Subscription<ChainHeadEvent<Option<String>>>, Error> {
let subscription = self
.client
.subscribe(
"chainHead_unstable_storage",
rpc_params![subscription_id, hash, to_hex(key), child_key.map(to_hex)],
"chainHead_unstable_stopStorage",
)
.await?;
Ok(subscription)
}
pub async fn chainhead_unstable_call(
&self,
subscription_id: String,
hash: T::Hash,
function: String,
call_parameters: &[u8],
) -> Result<Subscription<ChainHeadEvent<String>>, Error> {
let subscription = self
.client
.subscribe(
"chainHead_unstable_call",
rpc_params![subscription_id, hash, function, to_hex(call_parameters)],
"chainHead_unstable_stopCall",
)
.await?;
Ok(subscription)
}
pub async fn chainhead_unstable_unpin(
&self,
subscription_id: String,
hash: T::Hash,
) -> Result<(), Error> {
self.client
.request(
"chainHead_unstable_unpin",
rpc_params![subscription_id, hash],
)
.await?;
Ok(())
}
pub async fn chainhead_unstable_genesishash(&self) -> Result<T::Hash, Error> {
let hash = self
.client
.request("chainHead_unstable_genesisHash", rpc_params![])
.await?;
Ok(hash)
}
}
fn to_hex(bytes: impl AsRef<[u8]>) -> String {
format!("0x{}", hex::encode(bytes.as_ref()))
}