Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
migrate jsonrpc to jsonrpsee
  • Loading branch information
zqhxuyuan committed May 21, 2022
commit 8fb4f54423c518115c3b19105ccf98c253c183ae
5 changes: 2 additions & 3 deletions oracle/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ description = "RPC module for orml-oracle."

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0" }
jsonrpc-core = "18.0.0"
jsonrpc-core-client = "18.0.0"
jsonrpc-derive = "18.0.0"
jsonrpsee = { version = "0.13.0", features = ["server", "macros"] }

sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
Expand Down
74 changes: 39 additions & 35 deletions oracle/rpc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
use std::sync::Arc;

use codec::Codec;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
use jsonrpsee::{
core::{async_trait, RpcResult},
proc_macros::rpc,
types::error::{CallError, ErrorObject},
};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::{generic::BlockId, traits::Block as BlockT};

pub use self::gen_client::Client as OracleClient;
pub use orml_oracle_rpc_runtime_api::OracleApi as OracleRuntimeApi;

#[rpc]
#[rpc(client, server)]
pub trait OracleApi<BlockHash, ProviderId, Key, Value> {
#[rpc(name = "oracle_getValue")]
fn get_value(&self, provider_id: ProviderId, key: Key, at: Option<BlockHash>) -> Result<Option<Value>>;
#[rpc(name = "oracle_getAllValues")]
fn get_all_values(&self, provider_id: ProviderId, at: Option<BlockHash>) -> Result<Vec<(Key, Option<Value>)>>;
#[method(name = "oracle_getValue")]
fn get_value(&self, provider_id: ProviderId, key: Key, at: Option<BlockHash>) -> RpcResult<Option<Value>>;
#[method(name = "oracle_getAllValues")]
fn get_all_values(&self, provider_id: ProviderId, at: Option<BlockHash>) -> RpcResult<Vec<(Key, Option<Value>)>>;
}

/// A struct that implements the [`OracleApi`].
pub struct Oracle<C, B> {
/// Provides RPC methods to query oracle value.
pub struct OracleRpc<C, B> {
/// Shared reference to the client.
client: Arc<C>,
_marker: std::marker::PhantomData<B>,
}

impl<C, B> Oracle<C, B> {
/// Create new `Oracle` with the given reference to the client.
impl<C, B> OracleRpc<C, B> {
/// Creates a new instance of the `OracleRpc` helper.
pub fn new(client: Arc<C>) -> Self {
Oracle {
Self {
client,
_marker: Default::default(),
}
Expand All @@ -38,18 +41,19 @@ pub enum Error {
RuntimeError,
}

impl From<Error> for i64 {
fn from(e: Error) -> i64 {
impl From<Error> for i32 {
fn from(e: Error) -> i32 {
match e {
Error::RuntimeError => 1,
}
}
}

impl<C, Block, ProviderId, Key, Value> OracleApi<<Block as BlockT>::Hash, ProviderId, Key, Value> for Oracle<C, Block>
#[async_trait]
impl<C, Block, ProviderId, Key, Value> OracleApiServer<<Block as BlockT>::Hash, ProviderId, Key, Value> for OracleRpc<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
C::Api: OracleRuntimeApi<Block, ProviderId, Key, Value>,
ProviderId: Codec,
Key: Codec,
Expand All @@ -60,33 +64,33 @@ where
provider_id: ProviderId,
key: Key,
at: Option<<Block as BlockT>::Hash>,
) -> Result<Option<Value>> {
) -> RpcResult<Option<Value>> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or(
// If the block hash is not supplied assume the best block.
self.client.info().best_hash,
));
api.get_value(&at, provider_id, key).map_err(|e| RpcError {
code: ErrorCode::ServerError(Error::RuntimeError.into()),
message: "Unable to get value.".into(),
data: Some(format!("{:?}", e).into()),
let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));

api.get_value(&at, provider_id, key).map_err(|e| {
CallError::Custom(ErrorObject::owned(
Error::RuntimeError.into(),
"Unable to get value.",
Some(e.to_string()),
)).into()
})
}

fn get_all_values(
&self,
provider_id: ProviderId,
at: Option<<Block as BlockT>::Hash>,
) -> Result<Vec<(Key, Option<Value>)>> {
) -> RpcResult<Vec<(Key, Option<Value>)>> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or(
// If the block hash is not supplied assume the best block.
self.client.info().best_hash,
));
api.get_all_values(&at, provider_id).map_err(|e| RpcError {
code: ErrorCode::ServerError(Error::RuntimeError.into()),
message: "Unable to get all values.".into(),
data: Some(format!("{:?}", e).into()),
let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));

api.get_all_values(&at, provider_id).map_err(|e| {
CallError::Custom(ErrorObject::owned(
Error::RuntimeError.into(),
"Unable to get all values.",
Some(e.to_string()),
)).into()
})
}
}
5 changes: 2 additions & 3 deletions tokens/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ edition = "2021"

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0" }
jsonrpc-core = "18.0.0"
jsonrpc-core-client = "18.0.0"
jsonrpc-derive = "18.0.0"
jsonrpsee = { version = "0.13.0", features = ["server", "macros"] }

frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }

orml-tokens-rpc-runtime-api = { version = "0.4.1-dev", path = "./runtime-api" }
60 changes: 33 additions & 27 deletions tokens/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
use std::sync::Arc;

use codec::Codec;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
proc_macros::rpc,
types::error::{CallError, ErrorCode, ErrorObject},
};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_rpc::number::NumberOrHex;
Expand All @@ -12,23 +15,23 @@ use sp_runtime::{
traits::{Block as BlockT, MaybeDisplay},
};

pub use self::gen_client::Client as TokensClient;
pub use orml_tokens_rpc_runtime_api::TokensApi as TokensRuntimeApi;

#[rpc]
#[rpc(client, server)]
pub trait TokensApi<BlockHash, CurrencyId, Balance> {
#[rpc(name = "tokens_queryExistentialDeposit")]
fn query_existential_deposit(&self, currency_id: CurrencyId, at: Option<BlockHash>) -> Result<NumberOrHex>;
#[method(name = "tokens_queryExistentialDeposit")]
fn query_existential_deposit(&self, currency_id: CurrencyId, at: Option<BlockHash>) -> RpcResult<NumberOrHex>;
}

/// A struct that implements the [`TokensApi`].
pub struct Tokens<C, P> {
/// Provides RPC methods to query existential deposit of currency.
pub struct TokensRpc<C, P> {
/// Shared reference to the client.
client: Arc<C>,
_marker: std::marker::PhantomData<P>,
}

impl<C, P> Tokens<C, P> {
/// Create new `Tokens` with the given reference to the client.
impl<C, P> TokensRpc<C, P> {
/// Creates a new instance of the `TokensRpc` helper.
pub fn new(client: Arc<C>) -> Self {
Self {
client,
Expand All @@ -43,43 +46,46 @@ pub enum Error {
RuntimeError,
}

impl From<Error> for i64 {
fn from(e: Error) -> i64 {
impl From<Error> for i32 {
fn from(e: Error) -> i32 {
match e {
Error::RuntimeError => 1,
}
}
}

impl<C, Block, CurrencyId, Balance> TokensApi<<Block as BlockT>::Hash, CurrencyId, Balance> for Tokens<C, Block>
#[async_trait]
impl<C, Block, CurrencyId, Balance> TokensApi<<Block as BlockT>::Hash, CurrencyId, Balance> for TokensRpc<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
C::Api: TokensRuntimeApi<Block, CurrencyId, Balance>,
Balance: Codec + MaybeDisplay + Copy + TryInto<NumberOrHex> + std::fmt::Debug,
Balance: Codec + MaybeDisplay + Copy + TryInto<NumberOrHex> + Send + Sync + 'static,
CurrencyId: Codec,
{
fn query_existential_deposit(
&self,
currency_id: CurrencyId,
at: Option<<Block as BlockT>::Hash>,
) -> Result<NumberOrHex> {
) -> RpcResult<NumberOrHex> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash));
let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));

let balance = api.query_existential_deposit(&at, currency_id).map_err(|e| RpcError {
code: ErrorCode::ServerError(Error::RuntimeError.into()),
message: "Unable to query existential_deposit.".into(),
data: Some(format!("{:?}", e).into()),
let balance = api.query_existential_deposit(&at, currency_id).map_err(|e| {
CallError::Custom(ErrorObject::owned(
Error::RuntimeError.into(),
"Unable to query existential deposit.",
Some(e.to_string()),
))
});

let try_into_rpc_balance = |value: Balance| {
value.try_into().map_err(|_| RpcError {
code: ErrorCode::InvalidParams,
message: format!("{} doesn't fit in NumberOrHex representation", value),
data: None,
value.try_into().map_err(|_| {
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
ErrorCode::InvalidParams.code(),
format!("{} doesn't fit in NumberOrHex representation", value),
None::<()>,
)))
})
};

Expand Down