Skip to content

Commit

Permalink
Expose parachain-staking methods to RPC in all runtimes (#350)
Browse files Browse the repository at this point in the history
* exposed get_unclaimed_staking_rewards and get_staking_rates as rpc calls

* rollback on regenerating specs, fmt and fixes

* modify author of parachain-staking rpc modules

* bump down edition in new cargo.toml

* merge with main, bump spacewalk versions

* added untracked benchmarking file

* Revert "added untracked benchmarking file"

This reverts commit 0bec85d.

* fix import
  • Loading branch information
gianfra-t authored Nov 23, 2023
1 parent e7024c8 commit 46531bf
Show file tree
Hide file tree
Showing 18 changed files with 227 additions and 68 deletions.
32 changes: 32 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module-oracle-rpc = { git = "https://github.com/pendulum-chain/spacewalk", rev =
module-redeem-rpc = { git = "https://github.com/pendulum-chain/spacewalk", rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}
module-replace-rpc = { git = "https://github.com/pendulum-chain/spacewalk", rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}
module-vault-registry-rpc = { git = "https://github.com/pendulum-chain/spacewalk", rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}

module-pallet-staking-rpc = { path = "../pallets/parachain-staking/rpc" }
spacewalk-primitives = { git = "https://github.com/pendulum-chain/spacewalk", rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}

# Local
Expand Down
4 changes: 4 additions & 0 deletions node/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use zenlink_protocol_rpc::{ZenlinkProtocol, ZenlinkProtocolApiServer};

use module_issue_rpc::{Issue, IssueApiServer};
use module_oracle_rpc::{Oracle, OracleApiServer};
use module_pallet_staking_rpc::{ParachainStakingApiServer, Staking};
use module_redeem_rpc::{Redeem, RedeemApiServer};
use module_replace_rpc::{Replace, ReplaceApiServer};
use module_vault_registry_rpc::{VaultRegistry, VaultRegistryApiServer};
Expand Down Expand Up @@ -48,6 +49,7 @@ where
let FullDeps { client, pool, deny_unsafe } = deps;

module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(Staking::new(client.clone()).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(ZenlinkProtocol::new(client).into_rpc())?;
Ok(module)
Expand Down Expand Up @@ -78,6 +80,7 @@ where
let FullDeps { client, pool, deny_unsafe } = deps;

module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(Staking::new(client.clone()).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(Issue::new(client.clone()).into_rpc())?;
module.merge(Redeem::new(client.clone()).into_rpc())?;
Expand All @@ -100,6 +103,7 @@ where
let FullDeps { client, pool, deny_unsafe } = deps;

module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(Staking::new(client.clone()).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(Issue::new(client.clone()).into_rpc())?;
module.merge(Redeem::new(client.clone()).into_rpc())?;
Expand Down
1 change: 0 additions & 1 deletion pallets/orml-currencies-allowance-extension/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ pub mod pallet {
pub(super) type AllowedCurrencies<T: Config> =
StorageMap<_, Blake2_128Concat, CurrencyOf<T>, ()>;


#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub allowed_currencies: Vec<CurrencyOf<T>>,
Expand Down
3 changes: 3 additions & 0 deletions pallets/parachain-staking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ parity-scale-codec = {version = "3.1.5", default-features = false, features = ["
scale-info = {version = "2.1.1", default-features = false, features = ["derive"]}
serde = {version = "1.0.142", optional = true}
sp-api = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
module-pallet-staking-rpc-runtime-api = { path = "./rpc/runtime-api", default-features = false }


frame-support = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
frame-system = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
Expand All @@ -42,6 +44,7 @@ std = [
"frame-support/std",
"frame-system/std",
"log/std",
"module-pallet-staking-rpc-runtime-api/std",
"pallet-authorship/std",
"pallet-balances/std",
"pallet-session/std",
Expand Down
14 changes: 14 additions & 0 deletions pallets/parachain-staking/rpc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
authors = ["Pendulum"]
edition = "2021"
name = "module-pallet-staking-rpc"
version = "1.0.0"

[dependencies]
codec = {package = "parity-scale-codec", version = "3.0.0"}
jsonrpsee = {version = "0.16.0", features = ["server", "macros"]}
module-oracle-rpc-runtime-api = { git = "https://github.com/pendulum-chain/spacewalk", default-features = false, rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}
module-pallet-staking-rpc-runtime-api = {path = "runtime-api"}
sp-api = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40"}
sp-blockchain = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40"}
sp-runtime = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40"}
26 changes: 26 additions & 0 deletions pallets/parachain-staking/rpc/runtime-api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
authors = ["Pendulum"]
edition = "2021"
name = "module-pallet-staking-rpc-runtime-api"
version = "1.0.0"

[dependencies]
frame-support = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
sp-api = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
sp-std = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false}
parity-scale-codec = {version = "3.1.5", default-features = false, features = ["derive"]}
scale-info = {version = "2.1.1", default-features = false, features = ["derive"]}
module-oracle-rpc-runtime-api = { git = "https://github.com/pendulum-chain/spacewalk", default-features = false, rev = "d05b0015d15ca39cc780889bcc095335e9862a36"}
serde = {version = "1.0.142", default-features = false, optional = true, features = ["derive"]}

[features]
default = ["std"]
std = [
"serde",
"frame-support/std",
"scale-info/std",
"sp-api/std",
"sp-std/std",
"parity-scale-codec/std",
"module-oracle-rpc-runtime-api/std",
]
30 changes: 30 additions & 0 deletions pallets/parachain-staking/rpc/runtime-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! Runtime API definition for Parachain Staking.
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{scale_info::TypeInfo, sp_runtime::Perquintill};
use module_oracle_rpc_runtime_api::BalanceWrapper;
use parity_scale_codec::{Codec, Decode, Encode, MaxEncodedLen};
use sp_std::fmt::Debug;

#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};

#[derive(Decode, Encode, TypeInfo, MaxEncodedLen, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct StakingRates {
pub collator_staking_rate: Perquintill,
pub collator_reward_rate: Perquintill,
pub delegator_staking_rate: Perquintill,
pub delegator_reward_rate: Perquintill,
}

sp_api::decl_runtime_apis! {
pub trait ParachainStakingApi<AccountId, Balance>
where
AccountId: Codec,
Balance: Codec
{
fn get_unclaimed_staking_rewards(account: AccountId) -> BalanceWrapper<Balance>;
fn get_staking_rates() -> StakingRates;
}
}
85 changes: 85 additions & 0 deletions pallets/parachain-staking/rpc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! RPC interface for the parachain staking pallet.
use codec::Codec;
use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
proc_macros::rpc,
types::error::{CallError, ErrorCode, ErrorObject},
};
use module_oracle_rpc_runtime_api::BalanceWrapper;
use module_pallet_staking_rpc_runtime_api::{
ParachainStakingApi as ParachainStakingRuntimeApi, StakingRates,
};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::traits::{Block as BlockT, MaybeDisplay, MaybeFromStr};
use std::sync::Arc;

#[rpc(client, server)]
pub trait ParachainStakingApi<BlockHash, AccountId, Balance>
where
Balance: Codec + MaybeDisplay + MaybeFromStr,
AccountId: Codec,
{
#[method(name = "staking_getUnclaimedStakingRewards")]
fn get_unclaimed_staking_rewards(
&self,
account: AccountId,
at: Option<BlockHash>,
) -> RpcResult<BalanceWrapper<Balance>>;

#[method(name = "staking_getStakingRates")]
fn get_staking_rates(&self, at: Option<BlockHash>) -> RpcResult<StakingRates>;
}

fn internal_err<T: ToString>(message: T) -> JsonRpseeError {
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
ErrorCode::InternalError.code(),
message.to_string(),
None::<()>,
)))
}

/// A struct that implements the [`Staking`].
pub struct Staking<C, B> {
client: Arc<C>,
_marker: std::marker::PhantomData<B>,
}

impl<C, B> Staking<C, B> {
/// Create new `Staking` with the given reference to the client.
pub fn new(client: Arc<C>) -> Self {
Staking { client, _marker: Default::default() }
}
}

#[async_trait]
impl<C, Block, AccountId, Balance>
ParachainStakingApiServer<<Block as BlockT>::Hash, AccountId, Balance> for Staking<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: ParachainStakingRuntimeApi<Block, AccountId, Balance>,
Balance: Codec + MaybeDisplay + MaybeFromStr,
AccountId: Codec,
{
fn get_unclaimed_staking_rewards(
&self,
account: AccountId,
at: Option<<Block as BlockT>::Hash>,
) -> RpcResult<BalanceWrapper<Balance>> {
let api = self.client.runtime_api();
let at = at.unwrap_or_else(|| self.client.info().best_hash);

api.get_unclaimed_staking_rewards(at, account)
.map_err(|_e| internal_err(format!("Unable to get unclaimed staking rewards")))
}

fn get_staking_rates(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<StakingRates> {
let api = self.client.runtime_api();
let at = at.unwrap_or_else(|| self.client.info().best_hash);

api.get_staking_rates(at)
.map_err(|_e| internal_err(format!("Unable to get staking rates")))
}
}
6 changes: 3 additions & 3 deletions pallets/parachain-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod default_weights;
pub mod runtime_api;

#[cfg(test)]
pub(crate) mod mock;
Expand All @@ -135,6 +134,7 @@ mod types;
use frame_support::pallet;

pub use crate::{default_weights::WeightInfo, pallet::*};
pub use module_pallet_staking_rpc_runtime_api::StakingRates;

#[pallet]
pub mod pallet {
Expand Down Expand Up @@ -2559,7 +2559,7 @@ pub mod pallet {
/// delegators.
///
/// At least used in Runtime API.
pub fn get_staking_rates() -> runtime_api::StakingRates {
pub fn get_staking_rates() -> StakingRates {
let total_issuance = T::Currency::total_issuance();
let total_stake = TotalCollatorStake::<T>::get();
let inflation_config = InflationConfig::<T>::get();
Expand All @@ -2576,7 +2576,7 @@ pub mod pallet {
delegator_staking_rate.deconstruct(),
) * inflation_config.delegator.reward_rate.annual;

runtime_api::StakingRates {
StakingRates {
collator_staking_rate,
collator_reward_rate,
delegator_staking_rate,
Expand Down
42 changes: 0 additions & 42 deletions pallets/parachain-staking/src/runtime_api.rs

This file was deleted.

3 changes: 1 addition & 2 deletions pallets/parachain-staking/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,13 @@ use pallet_authorship::EventHandler;
use pallet_balances::{BalanceLock, Error as BalancesError, Reasons};
use pallet_session::{SessionManager, ShouldEndSession};
use sp_runtime::{traits::Zero, Perbill, Permill, Perquintill, SaturatedConversion};

use module_pallet_staking_rpc_runtime_api::StakingRates;
use crate::{
mock::{
almost_equal, events, last_event, roll_to, roll_to_claim_rewards, AccountId, Balance,
Balances, BlockNumber, ExtBuilder, RuntimeEvent as MetaEvent, RuntimeOrigin as Origin,
Session, StakePallet, System, Test, BLOCKS_PER_ROUND, DECIMALS, TREASURY_ACC,
},
runtime_api::StakingRates,
set::OrderedSet,
types::{
BalanceOf, Candidate, CandidateStatus, DelegationCounter, Delegator, RoundInfo, Stake,
Expand Down
Loading

0 comments on commit 46531bf

Please sign in to comment.