// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of substrate-subxt.
//
// subxt is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// subxt is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with substrate-subxt. If not, see .
// jsonrpsee subscriptions are interminable.
// Allows `while let status = subscription.next().await {}`
// Related: https://github.com/paritytech/substrate-subxt/issues/66
#![allow(irrefutable_let_patterns)]
use std::sync::Arc;
use codec::{
Decode,
Encode,
Error as CodecError,
};
use core::{
convert::TryInto,
marker::PhantomData,
};
use frame_metadata::RuntimeMetadataPrefixed;
use jsonrpsee_http_client::HttpClient;
use jsonrpsee_types::{
error::Error as RpcError,
jsonrpc::{
to_value as to_json_value,
DeserializeOwned,
Params,
},
traits::{
Client,
SubscriptionClient,
},
};
use jsonrpsee_ws_client::{
WsClient,
WsSubscription as Subscription,
};
use serde::{
Deserialize,
Serialize,
};
use sp_core::{
storage::{
StorageChangeSet,
StorageData,
StorageKey,
},
Bytes,
};
use sp_rpc::{
list::ListOrValue,
number::NumberOrHex,
};
use sp_runtime::{
generic::{
Block,
SignedBlock,
},
traits::Hash,
};
use sp_version::RuntimeVersion;
use crate::{
error::Error,
events::{
EventsDecoder,
RawEvent,
},
frame::{
system::System,
Event,
},
metadata::Metadata,
runtimes::Runtime,
subscription::{
EventStorageSubscription,
EventSubscription,
FinalizedEventStorageSubscription,
SystemEvents,
},
};
pub type ChainBlock =
SignedBlock::Header, ::Extrinsic>>;
/// Wrapper for NumberOrHex to allow custom From impls
#[derive(Serialize)]
pub struct BlockNumber(NumberOrHex);
impl From for BlockNumber {
fn from(x: NumberOrHex) -> Self {
BlockNumber(x)
}
}
impl From for BlockNumber {
fn from(x: u32) -> Self {
NumberOrHex::Number(x.into()).into()
}
}
/// System properties for a Substrate-based runtime
#[derive(serde::Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct SystemProperties {
/// The address format
pub ss58_format: u8,
/// The number of digits after the decimal point in the native token
pub token_decimals: u8,
/// The symbol of the native token
pub token_symbol: String,
}
/// Possible transaction status events.
///
/// # Note
///
/// This is copied from `sp-transaction-pool` to avoid a dependency on that crate. Therefore it
/// must be kept compatible with that type from the target substrate version.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TransactionStatus {
/// Transaction is part of the future queue.
Future,
/// Transaction is part of the ready queue.
Ready,
/// The transaction has been broadcast to the given peers.
Broadcast(Vec),
/// Transaction has been included in block with given hash.
InBlock(BlockHash),
/// The block this transaction was included in has been retracted.
Retracted(BlockHash),
/// Maximum number of finality watchers has been reached,
/// old watchers are being removed.
FinalityTimeout(BlockHash),
/// Transaction has been finalized by a finality-gadget, e.g GRANDPA
Finalized(BlockHash),
/// Transaction has been replaced in the pool, by another transaction
/// that provides the same tags. (e.g. same (sender, nonce)).
Usurped(Hash),
/// Transaction has been dropped from the pool because of the limit.
Dropped,
/// Transaction is no longer valid in the current state.
Invalid,
}
#[cfg(any(feature = "client", test))]
use substrate_subxt_client::SubxtClient;
/// Rpc client wrapper.
/// This is workaround because adding generic types causes the macros to fail.
#[derive(Clone)]
pub enum RpcClient {
/// JSONRPC client WebSocket transport.
WebSocket(WsClient),
/// JSONRPC client HTTP transport.
// NOTE: Arc because `HttpClient` is not clone.
Http(Arc),
#[cfg(any(feature = "client", test))]
/// Embedded substrate node.
Subxt(SubxtClient),
}
impl RpcClient {
/// Start a JSON-RPC request.
pub async fn request(
&self,
method: &str,
params: Params,
) -> Result {
match self {
Self::WebSocket(inner) => {
inner.request(method, params).await.map_err(Into::into)
}
Self::Http(inner) => inner.request(method, params).await.map_err(Into::into),
#[cfg(any(feature = "client", test))]
Self::Subxt(inner) => inner.request(method, params).await.map_err(Into::into),
}
}
/// Start a JSON-RPC Subscription.
pub async fn subscribe(
&self,
subscribe_method: &str,
params: Params,
unsubscribe_method: &str,
) -> Result, Error> {
match self {
Self::WebSocket(inner) => {
inner
.subscribe(subscribe_method, params, unsubscribe_method)
.await
.map_err(Into::into)
}
Self::Http(_) => {
Err(RpcError::Custom(
"Subscriptions not supported on HTTP transport".to_owned(),
)
.into())
}
#[cfg(any(feature = "client", test))]
Self::Subxt(inner) => {
inner
.subscribe(subscribe_method, params, unsubscribe_method)
.await
.map_err(Into::into)
}
}
}
}
impl From for RpcClient {
fn from(client: WsClient) -> Self {
RpcClient::WebSocket(client)
}
}
impl From for RpcClient {
fn from(client: HttpClient) -> Self {
RpcClient::Http(Arc::new(client))
}
}
#[cfg(any(feature = "client", test))]
impl From for RpcClient {
fn from(client: SubxtClient) -> Self {
RpcClient::Subxt(client)
}
}
/// ReadProof struct returned by the RPC
///
/// # Note
///
/// This is copied from `sc-rpc-api` to avoid a dependency on that crate. Therefore it
/// must be kept compatible with that type from the target substrate version.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReadProof {
/// Block hash used to generate the proof
pub at: Hash,
/// A proof used to prove that storage entries are included in the storage trie
pub proof: Vec,
}
/// Client for substrate rpc interfaces
pub struct Rpc {
client: RpcClient,
marker: PhantomData,
accept_weak_inclusion: bool,
}
impl Clone for Rpc {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
marker: PhantomData,
accept_weak_inclusion: self.accept_weak_inclusion,
}
}
}
impl Rpc {
pub fn new(client: RpcClient) -> Self {
Self {
client,
marker: PhantomData,
accept_weak_inclusion: false,
}
}
/// Configure the Rpc to accept non-finalized blocks
/// in `submit_and_watch_extrinsic`
pub fn accept_weak_inclusion(&mut self) {
self.accept_weak_inclusion = true;
}
/// Fetch a storage key
pub async fn storage(
&self,
key: &StorageKey,
hash: Option,
) -> Result