Skip to content

Commit

Permalink
feat: add rpc specific error type
Browse files Browse the repository at this point in the history
  • Loading branch information
cernicc committed Jun 6, 2024
1 parent 55644b5 commit f157bb3
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 21 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cli/polka-storage-provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ clap = { workspace = true, features = ["derive"] }
cli-primitives = { workspace = true }
jsonrpsee = { workspace = true, features = ["server"] }
serde = { workspace = true }
serde_json = { workspace = true }
subxt = { workspace = true }
subxt-signer = { workspace = true }
tokio = { workspace = true, features = ["full"] }
Expand Down
4 changes: 2 additions & 2 deletions cli/polka-storage-provider/src/commands/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use cli_primitives::Result;
use url::Url;

use crate::{
polkadot,
rpc::{start_rpc, RpcServerState},
substrate,
};

const SERVER_DEFAULT_BIND_ADDR: &str = "127.0.0.1:8000";
Expand All @@ -25,7 +25,7 @@ pub(crate) struct RunCommand {

impl RunCommand {
pub async fn handle(&self) -> Result<()> {
let substrate_client = polkadot::init_client(self.node_rpc_address.as_str()).await?;
let substrate_client = substrate::init_client(self.node_rpc_address.as_str()).await?;

let state = Arc::new(RpcServerState {
start_time: Utc::now(),
Expand Down
2 changes: 1 addition & 1 deletion cli/polka-storage-provider/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

mod cli;
pub(crate) mod commands;
mod polkadot;
mod rpc;
mod substrate;

pub(crate) use cli::Cli;
use cli_primitives::Result;
Expand Down
15 changes: 8 additions & 7 deletions cli/polka-storage-provider/src/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
use std::{future::Future, net::SocketAddr, sync::Arc};

use chrono::Utc;
use error::ServerError;
use jsonrpsee::{
server::{Server, ServerHandle},
types::{ErrorObjectOwned, Params},
types::Params,
RpcModule,
};
use methods::create_module;
use serde::{Deserialize, Serialize};
use tracing::info;

use crate::polkadot;
use crate::substrate;

pub mod error;
pub mod methods;

/// Type to be used by [`RpcMethod::handle`].
pub type Ctx = Arc<RpcServerState>;

/// A definition of an RPC method handler which:
/// - can be [registered](RpcMethodExt::register) with an [`RpcModule`].
/// A definition of an RPC method handler which can be registered with an [`RpcModule`].
pub trait RpcMethod {
/// Method name.
const NAME: &'static str;
/// See [`ApiVersion`].
const API_VERSION: ApiVersion;
/// Return value of this method.
/// Successful response type.
type Ok: Serialize;

/// Logic for this method.
fn handle(
ctx: Ctx,
params: Params,
) -> impl Future<Output = Result<Self::Ok, ErrorObjectOwned>> + Send;
) -> impl Future<Output = Result<Self::Ok, ServerError>> + Send;

/// Register this method with an [`RpcModule`].
fn register_async(module: &mut RpcModule<RpcServerState>) -> &mut jsonrpsee::MethodCallback
Expand Down Expand Up @@ -61,7 +62,7 @@ pub enum ApiVersion {

pub struct RpcServerState {
pub start_time: chrono::DateTime<Utc>,
pub substrate_client: polkadot::Client,
pub substrate_client: substrate::Client,
}

pub async fn start_rpc(
Expand Down
32 changes: 32 additions & 0 deletions cli/polka-storage-provider/src/rpc/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::fmt::Display;

use jsonrpsee::types::{error::INTERNAL_ERROR_CODE, ErrorObjectOwned};
use serde_json::Value;

pub struct ServerError {
inner: ErrorObjectOwned,
}

impl From<ServerError> for ErrorObjectOwned {
fn from(err: ServerError) -> Self {
err.inner
}
}

impl ServerError {
pub fn new(code: i32, message: impl Display, data: impl Into<Option<Value>>) -> Self {
Self {
inner: ErrorObjectOwned::owned(code, message.to_string(), data.into()),
}
}

pub fn internal_error(message: impl Display, data: impl Into<Option<Value>>) -> Self {
Self::new(INTERNAL_ERROR_CODE, message, data)
}
}

impl From<subxt::Error> for ServerError {
fn from(err: subxt::Error) -> Self {
Self::internal_error(err, None)
}
}
6 changes: 3 additions & 3 deletions cli/polka-storage-provider/src/rpc/methods/common.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use chrono::{DateTime, Utc};
use jsonrpsee::types::{ErrorObjectOwned, Params};
use jsonrpsee::types::Params;
use serde::{Deserialize, Serialize};

use crate::rpc::{ApiVersion, Ctx, RpcMethod};
use crate::rpc::{error::ServerError, ApiVersion, Ctx, RpcMethod};

#[derive(Debug)]
pub struct Info;
Expand All @@ -14,7 +14,7 @@ impl RpcMethod for Info {

type Ok = InfoResult;

async fn handle(ctx: Ctx, _params: Params<'_>) -> Result<Self::Ok, ErrorObjectOwned> {
async fn handle(ctx: Ctx, _params: Params<'_>) -> Result<Self::Ok, ServerError> {
Ok(InfoResult {
start_time: ctx.start_time,
})
Expand Down
10 changes: 5 additions & 5 deletions cli/polka-storage-provider/src/rpc/methods/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use jsonrpsee::types::{ErrorObjectOwned, Params};
use jsonrpsee::types::Params;
use serde::{Deserialize, Serialize};
use subxt_signer::sr25519::dev;

use crate::{
polkadot::get_balance,
rpc::{ApiVersion, Ctx, RpcMethod},
rpc::{error::ServerError, ApiVersion, Ctx, RpcMethod},
substrate::get_balance,
};

/// This RPC method exposes getting the system balances for the particular
Expand All @@ -16,11 +16,11 @@ impl RpcMethod for WalletBalance {

type Ok = Option<WalletBalanceResult>;

async fn handle(ctx: Ctx, _params: Params<'_>) -> Result<Self::Ok, ErrorObjectOwned> {
async fn handle(ctx: Ctx, _params: Params<'_>) -> Result<Self::Ok, ServerError> {
// TODO(@cernicc,05/06/2024): Implement correctly. dev alice is used as a show case for now.
let account = dev::alice().public_key().into();
// TODO(@cernicc,05/06/2024): Handle error.
let balance = get_balance(&ctx.substrate_client, &account).await.unwrap();
let balance = get_balance(&ctx.substrate_client, &account).await?;

Ok(balance.map(|balance| WalletBalanceResult {
free: balance.data.free.to_string(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use polkadot::runtime_types::{frame_system::AccountInfo, pallet_balances::types::AccountData};
use subxt::{utils::AccountId32, OnlineClient, PolkadotConfig};
use subxt::{utils::AccountId32, Error, OnlineClient, PolkadotConfig};
use tracing::info;

#[subxt::subxt(runtime_metadata_path = "artifacts/metadata.scale")]
Expand All @@ -13,7 +13,7 @@ type Config = PolkadotConfig;
pub type Client = OnlineClient<Config>;

/// Initialize a Polkadot client.
pub async fn init_client(url: impl AsRef<str>) -> Result<Client, cli_primitives::Error> {
pub async fn init_client(url: impl AsRef<str>) -> Result<Client, Error> {
let inner = OnlineClient::<Config>::from_url(url).await?;
info!("Connection with parachain established.");
Ok(inner)
Expand All @@ -22,7 +22,7 @@ pub async fn init_client(url: impl AsRef<str>) -> Result<Client, cli_primitives:
pub async fn get_balance(
client: &Client,
account: &AccountId32,
) -> Result<Option<AccountInfo<u32, AccountData<u128>>>, cli_primitives::Error> {
) -> Result<Option<AccountInfo<u32, AccountData<u128>>>, Error> {
let storage_query = polkadot::storage().system().account(account);

let result = client
Expand Down

0 comments on commit f157bb3

Please sign in to comment.