Skip to content

Commit

Permalink
1063 add rewards runtime api (#1124)
Browse files Browse the repository at this point in the history
* fix weightlimit + mocks

* attempt to adapt pools integration builder to new version of fudge

* Skip e2e / pools for now

Lots of compilation errors in the way. Let's comment those out and
address everything else first.

* Fixing integrations test

* rewards: Rename CurrencyId to RewardCurrencyId

* rewards: Add tests for list currencies

* runtime: Add rewards API

* rpc: Add rewards API

* deps: Add rewards pallet to runtime-common

* scripts: Change log level to info when starting parachain

* rewards-api: Rename param and change param order

* lint: Obey

* rewards-api: Convert result to option

* rewards: Revert CurrencyId name change

* rewards: Drop turbofish from collect

* rewards-test: Drop func that checks user currencies and use assert

* rewards: Adjust CurrencyId comment

* rewards-test: Add test for associating different currencies

* rewards: Return vector when listing currencies

* Start testing runtime apis: Setup

* integration-test: Add tests for rewards runtime API

* nix: Update flake.nix

Co-authored-by: Miguel Hervas <[email protected]>
Co-authored-by: nuno <[email protected]>
Co-authored-by: mustermeiszer <[email protected]>
  • Loading branch information
4 people authored Dec 14, 2022
1 parent bc9b750 commit 2260d6e
Show file tree
Hide file tree
Showing 18 changed files with 504 additions and 11 deletions.
3 changes: 3 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 flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
};

# This is a hash of all the Cargo dependencies, for reproducibility.
cargoSha256 = "sha256-rNLSOoDRhLgG4ftCD9Dznnoqj+6AjoyL9pnDPJa4Ze8=";
cargoSha256 = "sha256-y+d3TTC6+AiErJU9eF0XYV78UeI0ck/74R/6iXct22U=";

nativeBuildInputs = with pkgs; [ clang git-mock pkg-config ];
buildInputs = with pkgs; [ openssl ] ++ (
Expand Down
6 changes: 3 additions & 3 deletions libs/traits/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ pub trait AccountRewards<AccountId> {
/// Type used as balance for all currencies and reward.
type Balance;

/// Type used to identify the currency
/// Type used to identify the currency.
type CurrencyId;

/// Deposit a stake amount for a account_id associated to a currency_id.
Expand Down Expand Up @@ -162,10 +162,10 @@ pub trait AccountRewards<AccountId> {

/// Support for change currencies among groups.
pub trait CurrencyGroupChange {
/// Type used to identify the group
/// Type used to identify the group.
type GroupId;

/// Type used to identify the currency
/// Type used to identify the currency.
type CurrencyId;

/// Associate the currency to a group.
Expand Down
18 changes: 16 additions & 2 deletions pallets/rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ use frame_support::{
use mechanism::{DistributionId, MoveCurrencyError, RewardMechanism};
pub use pallet::*;
use sp_runtime::{traits::AccountIdConversion, TokenError};
use sp_std::fmt::Debug;

type RewardCurrencyOf<T, I> = <<T as Config<I>>::RewardMechanism as RewardMechanism>::Currency;
type RewardGroupOf<T, I> = <<T as Config<I>>::RewardMechanism as RewardMechanism>::Group;
Expand All @@ -101,7 +102,7 @@ pub mod pallet {
type PalletId: Get<PalletId>;

/// Type used to identify domains.
type DomainId: TypeInfo + MaxEncodedLen + FullCodec + Copy + PartialEq + sp_std::fmt::Debug;
type DomainId: TypeInfo + MaxEncodedLen + FullCodec + Copy + PartialEq + Debug;

/// Type used to identify currencies.
type CurrencyId: AssetId + MaxEncodedLen;
Expand All @@ -110,7 +111,7 @@ pub mod pallet {
type RewardCurrency: Get<Self::CurrencyId>;

/// Type used to identify groups.
type GroupId: FullCodec + TypeInfo + MaxEncodedLen + Copy + PartialEq + sp_std::fmt::Debug;
type GroupId: FullCodec + TypeInfo + MaxEncodedLen + Copy + PartialEq + Debug;

/// Type used to handle currency transfers and reservations.
type Currency: MutateHold<Self::AccountId, AssetId = Self::CurrencyId, Balance = BalanceOf<Self, I>>
Expand Down Expand Up @@ -428,4 +429,17 @@ pub mod pallet {
Currencies::<T, I>::get(currency_id).0
}
}

impl<T: Config<I>, I: 'static> Pallet<T, I>
where
RewardAccountOf<T, I>: FullCodec + Default,
{
pub fn list_currencies(
account_id: T::AccountId,
) -> sp_std::vec::Vec<(T::DomainId, T::CurrencyId)> {
StakeAccounts::<T, I>::iter_prefix(account_id)
.map(|(currency_id, _)| currency_id)
.collect()
}
}
}
40 changes: 40 additions & 0 deletions pallets/rewards/src/tests/currency_movement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,46 @@ macro_rules! currency_movement_tests {
assert_eq!(rewards_account(), 0);
});
}

#[test]
fn associate_different_currencies() {
new_test_ext().execute_with(|| {
let expected_currency_ids = vec![
&(DomainId::D1, CurrencyId::A),
&(DomainId::D1, CurrencyId::B),
&(DomainId::D1, CurrencyId::C),
&(DomainId::D1, CurrencyId::M),
];

assert_ok!($pallet::attach_currency(DOM_1_CURRENCY_A, GROUP_A));
assert_ok!($pallet::attach_currency(DOM_1_CURRENCY_B, GROUP_A));
assert_ok!($pallet::attach_currency(DOM_1_CURRENCY_C, GROUP_A));
assert_ok!($pallet::attach_currency(DOM_1_CURRENCY_M, GROUP_A));

assert_ok!($pallet::deposit_stake(DOM_1_CURRENCY_A, &USER_A, STAKE_A));
assert!(expected_currency_ids[0..1]
.iter()
.all(|x| $pallet::list_currencies(USER_A).contains(x)));

assert_ok!($pallet::deposit_stake(DOM_1_CURRENCY_B, &USER_A, STAKE_A));
assert!(expected_currency_ids[0..2]
.iter()
.all(|x| $pallet::list_currencies(USER_A).contains(x)));

assert_ok!($pallet::deposit_stake(DOM_1_CURRENCY_C, &USER_A, STAKE_A));
assert!(expected_currency_ids[0..3]
.iter()
.all(|x| $pallet::list_currencies(USER_A).contains(x)));

assert_ok!($pallet::deposit_stake(DOM_1_CURRENCY_M, &USER_A, STAKE_A));
assert!(expected_currency_ids
.iter()
.all(|x| $pallet::list_currencies(USER_A).contains(x)));

assert_ok!($pallet::withdraw_stake(DOM_1_CURRENCY_A, &USER_A, STAKE_A));
assert_eq!($pallet::list_currencies(USER_A).len(), 4);
});
}
}
};
}
1 change: 1 addition & 0 deletions runtime/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ cfg-types = { path = "../../libs/types", default-features = false }
pallet-anchors = { path = "../../pallets/anchors", default-features = false }
pallet-permissions = { path = "../../pallets/permissions", default-features = false }
pallet-pool-system = { path = "../../pallets/pool-system", default-features = false }
pallet-rewards = { path = "../../pallets/rewards", default-features = false }

[dev-dependencies]
sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.32" }
Expand Down
2 changes: 2 additions & 0 deletions runtime/common/src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
//! Runtime apis useful in the Centrifuge ecosystem
pub use anchors::*;
pub use pools::*;
pub use rewards::*;

mod anchors;
mod pools;
mod rewards;
30 changes: 30 additions & 0 deletions runtime/common/src/apis/rewards.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright 2021 Centrifuge Foundation (centrifuge.io).
//
// This file is part of the Centrifuge chain project.
// Centrifuge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version (see http://www.gnu.org/licenses).
// Centrifuge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

use codec::Codec;
use sp_api::decl_runtime_apis;
use sp_std::vec::Vec;

decl_runtime_apis! {
/// Runtime API for the rewards pallet.
pub trait RewardsApi<AccountId, Balance, DomainId, CurrencyId>
where
AccountId: Codec,
Balance: Codec,
DomainId: Codec,
CurrencyId: Codec,
{
fn list_currencies(account_id: AccountId) -> Vec<(DomainId, CurrencyId)>;

fn compute_reward(currency_id: (DomainId, CurrencyId), account_id: AccountId) -> Option<Balance>;
}
}
18 changes: 16 additions & 2 deletions runtime/development/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ pub use cfg_primitives::{
types::{PoolId, *},
};
use cfg_traits::{
CurrencyPrice, OrderManager, Permissions as PermissionsT, PoolInspect, PoolUpdateGuard,
PreConditions, PriceValue, TrancheCurrency as _,
rewards::AccountRewards, CurrencyPrice, OrderManager, Permissions as PermissionsT, PoolInspect,
PoolUpdateGuard, PreConditions, PriceValue, TrancheCurrency as _,
};
pub use cfg_types::tokens::CurrencyId;
use cfg_types::{
Expand Down Expand Up @@ -82,6 +82,8 @@ use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use runtime_common::fees::{DealWithFees, WeightToFee};
pub use runtime_common::*;
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_api::impl_runtime_apis;
use sp_core::OpaqueMetadata;
use sp_inherents::{CheckInherentsResult, InherentData};
Expand Down Expand Up @@ -1608,6 +1610,7 @@ impl<
}

#[derive(Clone, Copy, PartialEq, Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum RewardDomain {
Liquidity,
Block,
Expand Down Expand Up @@ -1987,6 +1990,17 @@ impl_runtime_apis! {
}
}

// RewardsApi
impl runtime_common::apis::RewardsApi<Block, AccountId, Balance, RewardDomain, CurrencyId> for Runtime {
fn list_currencies(account_id: AccountId) -> Vec<(RewardDomain, CurrencyId)> {
pallet_rewards::Pallet::<Runtime, pallet_rewards::Instance1>::list_currencies(account_id)
}

fn compute_reward(currency_id: (RewardDomain, CurrencyId), account_id: AccountId) -> Option<Balance> {
<pallet_rewards::Pallet::<Runtime, pallet_rewards::Instance1> as AccountRewards<AccountId>>::compute_reward(currency_id, &account_id).ok()
}
}

#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn dispatch_benchmark(
Expand Down
2 changes: 2 additions & 0 deletions runtime/integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pallet-transaction-payment = { git = "https://github.com/paritytech/substrate",
pallet-uniques = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.32" }

## Substrate-Primitives
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.32" }
sp-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.32" }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.32" }
sp-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.32" }
Expand Down Expand Up @@ -95,6 +96,7 @@ pallet-loans = { path = "../../pallets/loans" }
pallet-permissions = { path = "../../pallets/permissions" }
pallet-pool-registry = { path = "../../pallets/pool-registry" }
pallet-pool-system = { path = "../../pallets/pool-system" }
pallet-rewards = { path = "../../pallets/rewards" }

sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.32" }
sp-std = { git = "https://github.com/paritytech/substrate", default-features = true, branch = "polkadot-v0.9.32" }
Expand Down
1 change: 1 addition & 0 deletions runtime/integration-tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#![allow(unused)]

mod pools;
mod runtime_apis;
mod xcm;

/// Re-exports the correct runtimes that we run the integration tests with
Expand Down
2 changes: 1 addition & 1 deletion runtime/integration-tests/src/pools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@

mod env;
mod pool_starts;
mod utils;
pub mod utils;
Loading

0 comments on commit 2260d6e

Please sign in to comment.