generated from substrate-developer-hub/substrate-node-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
66 lines (58 loc) · 1.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
pub use pallet_template_runtime_api::TemplateApi as TemplateRuntimeApi;
use jsonrpsee::{
core::{Error as JsonRpseeError, 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};
use std::sync::Arc;
#[derive(serde::Deserialize, serde::Serialize)]
pub struct Custom {
code: u32,
sum: u32,
}
#[cfg(test)]
mod tests;
#[rpc(client, server)]
pub trait TemplateApi<BlockHash> {
#[method(name = "template_getValue")]
fn get_value(&self, at: Option<BlockHash>) -> RpcResult<Custom>;
}
/// A struct that implements the `TemplateApi`.
pub struct TemplatePallet<C, Block> {
// If you have more generics, no need to TemplatePallet<C, M, N, P, ...>
// just use a tuple like TemplatePallet<C, (M, N, P, ...)>
client: Arc<C>,
_marker: std::marker::PhantomData<Block>,
}
impl<C, Block> TemplatePallet<C, Block> {
/// Create new `TemplatePallet` instance with the given reference to the client.
pub fn new(client: Arc<C>) -> Self {
Self { client, _marker: Default::default() }
}
}
impl<C, Block> TemplateApiServer<<Block as BlockT>::Hash> for TemplatePallet<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: TemplateRuntimeApi<Block>,
{
fn get_value(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<Custom> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||self.client.info().best_hash));
let value = api.get_value(&at).map_err(runtime_error_into_rpc_err);
Ok(Custom{ code: 200, sum: value.unwrap()})
}
}
const RUNTIME_ERROR: i32 = 1;
/// Converts a runtime trap into an RPC error.
fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError {
CallError::Custom(ErrorObject::owned(
RUNTIME_ERROR,
"Runtime error",
Some(format!("{:?}", err)),
))
.into()
}