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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use codec::Codec;
use core::fmt::Debug;
pub use dock_staking_rewards::runtime_api::StakingRewardsApi as StakingRewardsRuntimeApi;
use jsonrpsee::{
core::{async_trait, 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, MaybeDisplay, MaybeFromStr},
};
use std::sync::Arc;
#[rpc(server, client)]
pub trait StakingRewardsApi<BlockHash, Balance> {
#[method(name = "staking_rewards_yearlyEmission")]
async fn yearly_emission(
&self,
total_staked: Balance,
total_issuance: Balance,
at: Option<BlockHash>,
) -> RpcResult<Balance>;
#[method(name = "staking_rewards_maxYearlyEmission")]
async fn max_yearly_emission(&self, at: Option<BlockHash>) -> RpcResult<Balance>;
}
#[derive(Debug, Clone)]
struct RuntimeError<T>(T);
impl<T: Debug> From<RuntimeError<T>> for JsonRpseeError {
fn from(error: RuntimeError<T>) -> Self {
let data = format!("{:?}", error);
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
1,
"Runtime error",
Some(data),
)))
}
}
pub struct StakingRewards<C, P> {
client: Arc<C>,
_marker: std::marker::PhantomData<P>,
}
impl<C, P> StakingRewards<C, P> {
pub fn new(client: Arc<C>) -> Self {
StakingRewards {
client,
_marker: Default::default(),
}
}
}
#[async_trait]
impl<C, Block, Balance> StakingRewardsApiServer<<Block as BlockT>::Hash, Balance>
for StakingRewards<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: StakingRewardsRuntimeApi<Block, Balance>,
Balance: Codec + MaybeDisplay + MaybeFromStr + Send + 'static,
{
async fn yearly_emission(
&self,
total_staked: Balance,
total_issuance: Balance,
at: Option<<Block as BlockT>::Hash>,
) -> RpcResult<Balance> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));
api.yearly_emission(&at, total_staked, total_issuance)
.map_err(RuntimeError)
.map_err(Into::into)
}
async fn max_yearly_emission(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<Balance> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));
api.max_yearly_emission(&at)
.map_err(RuntimeError)
.map_err(Into::into)
}
}