difftreelog
Inflation pallet block provider added. Setted up to relay chain.
in: master
3 files changed
pallets/inflation/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]89#[cfg(feature = "std")]10pub use std::*;1112pub use serde::{Serialize, Deserialize};1314#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;1617#[cfg(test)]18mod tests;1920pub use frame_support::{21 construct_runtime, decl_module, decl_storage, ensure,22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};3334// #[cfg(feature = "runtime-benchmarks")]35pub use frame_support::dispatch::DispatchResult;3637use sp_runtime::{38 Perbill,39 traits::{Zero},40};41use sp_std::convert::TryInto;4243use frame_system::{self as system};4445/// The balance type of this module.46pub type BalanceOf<T> =47 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;4849// pub const YEAR: u32 = 5_259_600; // 6-second block50pub const YEAR: u32 = 2_629_800; // 12-second block51pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;52pub const START_INFLATION_PERCENT: u32 = 10;53pub const END_INFLATION_PERCENT: u32 = 4;5455pub trait Config: system::Config {56 type Currency: Currency<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;58 type InflationBlockInterval: Get<Self::BlockNumber>;59}6061decl_storage! {62 trait Store for Module<T: Config> as Inflation {63 /// starting year total issuance64 pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;6566 /// Current block inflation67 pub BlockInflation get(fn block_inflation): BalanceOf<T>;68 }69}7071decl_module! {72 pub struct Module<T: Config> for enum Call73 where74 origin: T::Origin,75 {76 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();7778 fn on_initialize(now: T::BlockNumber) -> Weight79 {80 let mut consumed_weight = 0;81 let mut add_weight = |reads, writes, weight| {82 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);83 consumed_weight += weight;84 };8586 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);8788 // TODO: Rewrite inflation to use block timestamp instead of block number89 // let _now = <timestamp::Module<T>>::get();9091 // Recalculate inflation on the first block of the year (or if it is not initialized yet)92 if (now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {93 let current_year: u32 = (now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);9495 let one_percent = Perbill::from_percent(1);9697 if current_year <= TOTAL_YEARS_UNTIL_FLAT {98 let amount: BalanceOf<T> = Perbill::from_rational(99 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),100 YEAR * TOTAL_YEARS_UNTIL_FLAT101 ) * ( one_percent * T::Currency::total_issuance() );102 <BlockInflation<T>>::put(amount);103 }104 else {105 let amount: BalanceOf<T> = Perbill::from_rational(106 block_interval * END_INFLATION_PERCENT,107 YEAR108 ) * (one_percent * T::Currency::total_issuance());109 <BlockInflation<T>>::put(amount);110 }111 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());112113 // First time deposit114 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());115116 add_weight(7, 6, 28_300_000);117 }118119 // Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account120 else if (now % T::BlockNumber::from(block_interval)).is_zero() {121 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();122123 add_weight(3, 2, 12_900_000);124 }125126 consumed_weight127 }128129 }130}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]89#[cfg(feature = "std")]10pub use std::*;1112pub use serde::{Serialize, Deserialize};1314#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;1617#[cfg(test)]18mod tests;1920pub use frame_support::{21 construct_runtime, decl_module, decl_storage, ensure,22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};3334// #[cfg(feature = "runtime-benchmarks")]35pub use frame_support::dispatch::DispatchResult;3637use sp_runtime::{38 Perbill,39 traits::{BlockNumberProvider, Zero},40};41use sp_std::convert::TryInto;4243use frame_system::{self as system};4445/// The balance type of this module.46pub type BalanceOf<T> =47 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;4849// pub const YEAR: u32 = 5_259_600; // 6-second block50pub const YEAR: u32 = 2_629_800; // 12-second block51pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;52pub const START_INFLATION_PERCENT: u32 = 10;53pub const END_INFLATION_PERCENT: u32 = 4;5455pub trait Config: system::Config {56 type Currency: Currency<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;58 type InflationBlockInterval: Get<Self::BlockNumber>;5960 // The block number provider61 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;62}6364decl_storage! {65 trait Store for Module<T: Config> as Inflation {66 /// starting year total issuance67 pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;6869 /// Current block inflation70 pub BlockInflation get(fn block_inflation): BalanceOf<T>;71 }72}7374decl_module! {75 pub struct Module<T: Config> for enum Call76 where77 origin: T::Origin,78 {79 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();8081 fn on_initialize() -> Weight82 {83 let mut consumed_weight = 0;84 let mut add_weight = |reads, writes, weight| {85 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);86 consumed_weight += weight;87 };8889 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);90 let _now = T::BlockNumberProvider::current_block_number();9192 // Recalculate inflation on the first block of the year (or if it is not initialized yet)93 if (_now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {94 let current_year: u32 = (_now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);9596 let one_percent = Perbill::from_percent(1);9798 if current_year <= TOTAL_YEARS_UNTIL_FLAT {99 let amount: BalanceOf<T> = Perbill::from_rational(100 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),101 YEAR * TOTAL_YEARS_UNTIL_FLAT102 ) * ( one_percent * T::Currency::total_issuance() );103 <BlockInflation<T>>::put(amount);104 }105 else {106 let amount: BalanceOf<T> = Perbill::from_rational(107 block_interval * END_INFLATION_PERCENT,108 YEAR109 ) * (one_percent * T::Currency::total_issuance());110 <BlockInflation<T>>::put(amount);111 }112 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());113114 // First time deposit115 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());116117 add_weight(7, 6, 28_300_000);118 }119120 // Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account121 else if (_now % T::BlockNumber::from(block_interval)).is_zero() {122 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();123124 add_weight(3, 2, 12_900_000);125 }126127 consumed_weight128 }129130 }131}pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -11,7 +11,7 @@
};
use sp_core::H256;
use sp_runtime::{
- traits::{BlakeTwo256, IdentityLookup},
+ traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
testing::Header,
};
@@ -85,12 +85,22 @@
parameter_types! {
pub TreasuryAccountId: u64 = 1234;
pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
+ pub static MockBlockNumberProvider: u64 = 0;
}
+impl BlockNumberProvider for MockBlockNumberProvider {
+ type BlockNumber = u64;
+
+ fn current_block_number() -> Self::BlockNumber {
+ Self::get()
+ }
+}
+
impl pallet_inflation::Config for Test {
type Currency = Balances;
type TreasuryAccountId = TreasuryAccountId;
type InflationBlockInterval = InflationBlockInterval;
+ type BlockNumberProvider = MockBlockNumberProvider;
}
pub fn new_test_ext() -> sp_io::TestExternalities {
@@ -110,7 +120,8 @@
// BlockInflation should be set after 1st block and
// first inflation deposit should be equal to BlockInflation
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803
assert_eq!(Inflation::block_inflation(), 3803);
@@ -128,20 +139,23 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Next inflation deposit happens when block is multiple of InflationBlockInterval
let mut block: u32 = 2;
let balance_before: u64 = Balances::free_balance(1234);
while block % InflationBlockInterval::get() != 0 {
- Inflation::on_initialize(block as u64);
+ MockBlockNumberProvider::set(block as u64);
+ Inflation::on_initialize(0);
block += 1;
}
let balance_just_before: u64 = Balances::free_balance(1234);
assert_eq!(balance_before, balance_just_before);
// The block with inflation
- Inflation::on_initialize(block as u64);
+ MockBlockNumberProvider::set(block as u64);
+ Inflation::on_initialize(0);
let balance_after: u64 = Balances::free_balance(1234);
assert_eq!(
balance_after - balance_just_before,
@@ -157,19 +171,22 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Go through all the block inflations for year 1,
// total issuance will be updated accordingly
for block in (100..YEAR).step_by(100) {
- Inflation::on_initialize(block);
+ MockBlockNumberProvider::set(block);
+ Inflation::on_initialize(0);
}
assert_eq!(
initial_issuance + (3803 * (YEAR / 100)),
<Balances as Currency<_>>::total_issuance()
);
- Inflation::on_initialize(YEAR);
+ MockBlockNumberProvider::set(YEAR);
+ Inflation::on_initialize(0);
let block_inflation_year_1 = Inflation::block_inflation();
// Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904
assert_eq!(block_inflation_year_1, 3904);
@@ -181,13 +198,16 @@
new_test_ext().execute_with(|| {
// Total issuance = 1_000_000_000
let initial_issuance: u64 = 1_000_000_000;
+
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
for year in 1..=9 {
let block_inflation_year_before = Inflation::block_inflation();
- Inflation::on_initialize(YEAR * year);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let block_inflation_year_after = Inflation::block_inflation();
// SBP M2 review: this is actually not true (not for the first few years)
@@ -204,11 +224,13 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(YEAR * 9);
+ MockBlockNumberProvider::set(YEAR * 9);
+ Inflation::on_initialize(0);
for year in 10..=20 {
let block_inflation_year_before = Inflation::block_inflation();
- Inflation::on_initialize(YEAR * year);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let block_inflation_year_after = Inflation::block_inflation();
// Assert that next year inflation is equal to previous year inflation
@@ -233,22 +255,26 @@
for year in 0..=10 {
// Year first block
- Inflation::on_initialize(year * YEAR);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let mut actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year second block
- Inflation::on_initialize(year * YEAR + 1);
+ MockBlockNumberProvider::set(YEAR * year + 1);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year middle block
- Inflation::on_initialize(year * YEAR + YEAR / 2);
+ MockBlockNumberProvider::set(year * YEAR + YEAR / 2);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year last block
- Inflation::on_initialize((year + 1) * YEAR - 1);
+ MockBlockNumberProvider::set((year + 1) * YEAR - 1);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
}
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -768,6 +768,7 @@
type Currency = Balances;
type TreasuryAccountId = TreasuryAccountId;
type InflationBlockInterval = InflationBlockInterval;
+ type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
// parameter_types! {