Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add block rewards to altair and centrifuge runtimes #1342

Merged
merged 30 commits into from
May 16, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
0328dd0
feat: add ED funding to rewards pallet
wischli May 10, 2023
aad3cd7
feat: apply reward genesis config to dev runtime
wischli May 10, 2023
793797e
tests: apply rewards ED to block rewards
wischli May 11, 2023
e320b01
tests: add sanity intgr block rewards check
wischli May 11, 2023
cd36e63
feat: add block rewards to altair runtime
wischli May 11, 2023
1c64212
feat: add block rewards to cfg runtime
wischli May 11, 2023
7a4b92f
docs: improve blk rw migraton com
wischli May 11, 2023
afc4d54
feat: reduce collator kick threshold to 2 hours
wischli May 10, 2023
0301952
Revert "feat: reduce collator kick threshold to 2 hours"
wischli May 11, 2023
9b4dc2a
fix: re-enable transfer keep alive
wischli May 11, 2023
d2aeaa2
fix: chain_spec
wischli May 12, 2023
d0aa485
refactor: move rewards migration
wischli May 12, 2023
315bb78
feat: add session key migration
wischli May 12, 2023
e913b6f
Merge branch 'main' into feat/block-rewards-to-prod
wischli May 12, 2023
87446db
fix: mixed up tokens in spec
wischli May 12, 2023
12f08c1
refactor: rm dev migrations
wischli May 12, 2023
b87cd00
bench: fix block rewards
wischli May 15, 2023
a995225
Merge remote-tracking branch 'origin/main' into feat/block-rewards-to…
wischli May 15, 2023
2b43d2b
refactor: move migrations to sep file
wischli May 15, 2023
310f2b5
refactor: block rewards pallet id
wischli May 15, 2023
635a6af
refactor: improve pallet genesis build err log
wischli May 15, 2023
e3047d2
refactor: remove rewards domain concept (#1344)
wischli May 16, 2023
24616cf
refactor: rename LiquidityRewardsBase
wischli May 16, 2023
7d322e4
tests: add block rewards RAPI int
wischli May 16, 2023
9957c73
clippy: remove unused
wischli May 16, 2023
238ddc9
fmt: taplo
wischli May 16, 2023
4be7404
fix: dev chainspec after renaming
wischli May 16, 2023
1fb344e
refactor: apply suggestion from code review
wischli May 16, 2023
7bf4a40
Update runtime/centrifuge/src/lib.rs
wischli May 16, 2023
0fcf91c
Merge branch 'main' into feat/block-rewards-to-prod
wischli May 16, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

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

5 changes: 4 additions & 1 deletion pallets/block-rewards/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ benchmarks! {

}: _(RawOrigin::Signed(caller), beneficiary.clone())
verify {
let num_collators: u128 = BlockRewards::<T>::next_session_changes().collator_count.unwrap_or(
BlockRewards::<T>::active_session_data().collator_count
).into();
// Does not get entire reward since another collator is auto-staked via genesis config
assert_eq!(<T as Config>::Currency::balance(CurrencyId::Native.into(), &beneficiary).saturating_sub(before), (REWARD / 2).into());
assert_eq!(<T as Config>::Currency::balance(CurrencyId::Native.into(), &beneficiary).saturating_sub(before), (REWARD / (num_collators + 1)).into());
}

set_collator_reward {
Expand Down
3 changes: 1 addition & 2 deletions pallets/block-rewards/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ where
weight.saturating_accrue(T::DbWeight::get().writes(1));

for collator in collators.iter() {
// TODO: Benching preferred to be precise.
// However, not necessarily needed as num of collators <= 10.
// NOTE: Benching not required as num of collators <= 10.
lemunozm marked this conversation as resolved.
Show resolved Hide resolved
Pallet::<T>::do_init_collator(collator)
.map_err(|e| {
log::error!("Failed to init genesis collators for rewards: {:?}", e);
Expand Down
9 changes: 8 additions & 1 deletion pallets/block-rewards/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl pallet_session::Config for Test {
}

parameter_types! {
pub const ExistentialDeposit: Balance = 0;
pub const ExistentialDeposit: Balance = 1;
}
impl pallet_balances::Config for Test {
type AccountStore = System;
Expand Down Expand Up @@ -378,6 +378,13 @@ impl ExtBuilder {
.assimilate_storage(&mut storage)
.expect("Session pallet's storage can be assimilated");

pallet_rewards::GenesisConfig::<Test, pallet_rewards::Instance1> {
currency_id: CurrencyId::Native,
amount: ExistentialDeposit::get(),
}
.assimilate_storage(&mut storage)
.expect("Rewards pallet's storage can be assimilated");

let mut ext = sp_io::TestExternalities::new(storage);

ext.execute_with(|| {
Expand Down
25 changes: 20 additions & 5 deletions pallets/block-rewards/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,10 @@ fn single_claim_reward() {
},
));
assert_eq!(Balances::total_balance(&TREASURY_ADDRESS), 9 * REWARD);
assert_eq!(Balances::total_issuance(), 10 * REWARD);
assert_eq!(
Balances::total_issuance(),
10 * REWARD + ExistentialDeposit::get()
);
assert_eq!(Balances::free_balance(&1), REWARD);
});
}
Expand All @@ -314,7 +317,10 @@ fn collator_rewards_greater_than_remainder() {
),
Ok(REWARD)
);
assert_eq!(Balances::total_issuance(), 2 * REWARD);
assert_eq!(
Balances::total_issuance(),
2 * REWARD + ExistentialDeposit::get()
);
assert_eq!(Balances::total_balance(&TREASURY_ADDRESS), REWARD);

// EPOCH 1 -> EPOCH 2
Expand All @@ -333,7 +339,10 @@ fn collator_rewards_greater_than_remainder() {
Ok(2 * REWARD)
);
assert_eq!(Balances::total_balance(&TREASURY_ADDRESS), 2 * REWARD);
assert_eq!(Balances::total_issuance(), 4 * REWARD);
assert_eq!(
Balances::total_issuance(),
4 * REWARD + ExistentialDeposit::get()
);

// EPOCH 2 -> EPOCH 3
advance_session();
Expand Down Expand Up @@ -364,7 +373,10 @@ fn collator_rewards_greater_than_remainder() {
);
}
assert_eq!(Balances::total_balance(&TREASURY_ADDRESS), 2 * REWARD);
assert_eq!(Balances::total_issuance(), 6 * REWARD);
assert_eq!(
Balances::total_issuance(),
6 * REWARD + ExistentialDeposit::get()
);

// EPOCH 3 -> EPOCH 4
advance_session();
Expand Down Expand Up @@ -403,7 +415,10 @@ fn collator_rewards_greater_than_remainder() {
Ok(2 * REWARD / 3)
);
assert_eq!(Balances::total_balance(&TREASURY_ADDRESS), 2 * REWARD);
assert_eq!(Balances::total_issuance(), 8 * REWARD);
assert_eq!(
Balances::total_issuance(),
8 * REWARD + ExistentialDeposit::get()
);
});
}

Expand Down
2 changes: 2 additions & 0 deletions pallets/rewards/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ cfg-types = { path = "../../libs/types", default-features = false }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.37" }
frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.37" }
log = { version = "0.4.17", default-features = false }
num-traits = { version = "0.2", default-features = false }
scale-info = { version = "2.3.0", default-features = false, features = ["derive"] }
sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.37" }
Expand All @@ -42,6 +43,7 @@ std = [
"codec/std",
"frame-support/std",
"frame-system/std",
"log/std",
"sp-runtime/std",
"sp-std/std",
"cfg-traits/std",
Expand Down
48 changes: 45 additions & 3 deletions pallets/rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,16 @@ mod tests;

pub mod issuance;
pub mod mechanism;
pub mod migrations {
pub mod new_instance;
}

use cfg_traits::rewards::{AccountRewards, CurrencyGroupChange, GroupRewards, RewardIssuance};
use codec::FullCodec;
use frame_support::{
pallet_prelude::*,
traits::{
fungibles::{InspectHold, Mutate, MutateHold, Transfer},
fungibles::{Inspect, InspectHold, Mutate, MutateHold, Transfer},
tokens::AssetId,
},
PalletId,
Expand Down Expand Up @@ -110,7 +113,7 @@ pub mod pallet {
type DomainId: TypeInfo + MaxEncodedLen + FullCodec + Copy + PartialEq + Debug;

/// Type used to identify currencies.
type CurrencyId: AssetId + MaxEncodedLen;
type CurrencyId: AssetId + MaxEncodedLen + MaybeSerializeDeserialize + Default;

/// Identifier for the currency used to give the reward.
type RewardCurrency: Get<Self::CurrencyId>;
Expand All @@ -120,7 +123,8 @@ pub mod pallet {

/// Type used to handle currency transfers and reservations.
type Currency: MutateHold<Self::AccountId, AssetId = Self::CurrencyId, Balance = BalanceOf<Self, I>>
+ Mutate<Self::AccountId, AssetId = Self::CurrencyId, Balance = BalanceOf<Self, I>>;
+ Mutate<Self::AccountId, AssetId = Self::CurrencyId, Balance = BalanceOf<Self, I>>
+ Inspect<Self::AccountId, AssetId = Self::CurrencyId, Balance = BalanceOf<Self, I>>;

/// Specify the internal reward mechanism used by this pallet.
/// Check available mechanisms at [`mechanism`] module.
Expand All @@ -138,6 +142,44 @@ pub mod pallet {
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T, I = ()>(_);

#[pallet::genesis_config]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()>
where
BalanceOf<T, I>: MaybeSerializeDeserialize,
{
pub currency_id: T::CurrencyId,
pub amount: BalanceOf<T, I>,
}

#[cfg(feature = "std")]
impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I>
where
BalanceOf<T, I>: MaybeSerializeDeserialize,
{
fn default() -> Self {
Self {
currency_id: Default::default(),
amount: Default::default(),
}
}
}

#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> GenesisBuild<T, I> for GenesisConfig<T, I>
where
BalanceOf<T, I>: MaybeSerializeDeserialize,
{
fn build(&self) {
T::Currency::mint_into(
self.currency_id,
&T::PalletId::get().into_account_truncating(),
self.amount,
)
.map_err(|_| log::error!("Failed to mint ED for sovereign pallet account",))
wischli marked this conversation as resolved.
Show resolved Hide resolved
.ok();
}
}

// --------------------------
// Storage
// --------------------------
Expand Down
82 changes: 82 additions & 0 deletions pallets/rewards/src/migrations/new_instance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// 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 frame_support::traits::{
fungibles::{Inspect, Mutate},
Get, OnRuntimeUpgrade,
};
use sp_runtime::traits::AccountIdConversion;
use sp_std::marker::PhantomData;
#[cfg(feature = "try-runtime")]
use {frame_support::inherent::Vec, sp_std::vec};

use crate::{BalanceOf, Config};

pub struct FundExistentialDeposit<T, I, Currency, ED>(PhantomData<(T, I, Currency, ED)>);

fn pallet_is_funded<T, I, Currency, ED>() -> bool
where
T: Config<I>,
I: 'static,
Currency: Get<<T as Config<I>>::CurrencyId>,
ED: Get<BalanceOf<T, I>>,
{
let balance = <<T as Config<I>>::Currency as Inspect<T::AccountId>>::balance(
Currency::get(),
&<T as Config<I>>::PalletId::get().into_account_truncating(),
);
balance >= ED::get()
}

impl<T, I, Currency, ED> OnRuntimeUpgrade for FundExistentialDeposit<T, I, Currency, ED>
where
T: frame_system::Config + Config<I>,
I: 'static,
Currency: Get<<T as Config<I>>::CurrencyId>,
ED: Get<BalanceOf<T, I>>,
{
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
assert!(!pallet_is_funded::<T, I, Currency, ED>());

log::info!("💶 Rewards: Pre funding ED checks successful");
Ok(vec![])
}

fn on_runtime_upgrade() -> frame_support::weights::Weight {
if !pallet_is_funded::<T, I, Currency, ED>() {
mustermeiszer marked this conversation as resolved.
Show resolved Hide resolved
log::info!("💶 Rewards: Initiating ED funding to sovereign pallet account");
T::Currency::mint_into(
Currency::get(),
&T::PalletId::get().into_account_truncating(),
ED::get(),
)
.map_err(|_| log::error!("💶 Rewards: Failed to mint ED for sovereign pallet account",))
.ok();

T::DbWeight::get().reads_writes(1, 1)
} else {
log::info!(
"💶 Rewards: ED funding for sovereign pallet account not required anymore. This probably should be removed"
);
T::DbWeight::get().reads_writes(1, 0)
}
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_pre_state: Vec<u8>) -> Result<(), &'static str> {
assert!(pallet_is_funded::<T, I, Currency, ED>());

log::info!("💶 Rewards: Post funding ED checks successful");
Ok(())
}
}
6 changes: 6 additions & 0 deletions pallets/rewards/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ pub enum CurrencyId {
M,
}

impl Default for CurrencyId {
fn default() -> Self {
CurrencyId::Reward
}
}
lemunozm marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebug)]
pub enum DomainId {
D1,
Expand Down
Loading