difftreelog
Merge pull request #255 from UniqueNetwork/feature/CORE-247
in: master
Inflation pallet block provider added. Setted up to relay chain.
8 files changed
Cargo.lockdiffbeforeafterboth11679 "pallet-evm-migration",11679 "pallet-evm-migration",11680 "pallet-evm-transaction-payment",11680 "pallet-evm-transaction-payment",11681 "pallet-fungible",11681 "pallet-fungible",11682 "pallet-inflation",11682 "pallet-nonfungible",11683 "pallet-nonfungible",11683 "pallet-randomness-collective-flip",11684 "pallet-randomness-collective-flip",11684 "pallet-refungible",11685 "pallet-refungible",pallets/inflation/src/lib.rsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556#![recursion_limit = "1024"]6// #![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]7#![cfg_attr(not(feature = "std"), no_std)]89#[cfg(feature = "std")]10pub use std::*;1112pub use serde::{Serialize, Deserialize};13814#[cfg(feature = "runtime-benchmarks")]9#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;10mod benchmarking;161117#[cfg(test)]12#[cfg(test)]18mod tests;13mod tests;191420pub use frame_support::{15use frame_support::{21 construct_runtime, decl_module, decl_storage, ensure,16 dispatch::{DispatchResult},22 traits::{17 traits::{Currency, Get},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};18};3334// #[cfg(feature = "runtime-benchmarks")]35pub use frame_support::dispatch::DispatchResult;19pub use pallet::*;3637use sp_runtime::{20use sp_runtime::{38 Perbill,21 Perbill,39 traits::{Zero},22 traits::{BlockNumberProvider},40};23};2441use sp_std::convert::TryInto;25use sp_std::convert::TryInto;422643use frame_system::{self as system};4445/// The balance type of this module.46pub type BalanceOf<T> =27type BalanceOf<T> =47 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;28 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;482949// pub const YEAR: u32 = 5_259_600; // 6-second block50pub const YEAR: u32 = 2_629_800; // 12-second block30pub const YEAR: u32 = 5_259_600; // 6-second block31 // pub const YEAR: u32 = 2_629_800; // 12-second block51pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;32pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;52pub const START_INFLATION_PERCENT: u32 = 10;33pub const START_INFLATION_PERCENT: u32 = 10;53pub const END_INFLATION_PERCENT: u32 = 4;34pub const END_INFLATION_PERCENT: u32 = 4;543536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use frame_support::pallet_prelude::*;40 use frame_system::pallet_prelude::*;4142 #[pallet::config]55pub trait Config: system::Config {43 pub trait Config: frame_system::Config {56 type Currency: Currency<Self::AccountId>;44 type Currency: Currency<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;45 type TreasuryAccountId: Get<Self::AccountId>;4647 // The block number provider48 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;4950 /// Number of blocks that pass between treasury balance updates due to inflation51 #[pallet::constant]58 type InflationBlockInterval: Get<Self::BlockNumber>;52 type InflationBlockInterval: Get<Self::BlockNumber>;59}53 }605461decl_storage! {55 #[pallet::pallet]56 #[pallet::generate_store(pub(super) trait Store)]57 pub struct Pallet<T>(_);5859 /// starting year total issuance60 #[pallet::storage]61 pub type StartingYearTotalIssuance<T: Config> =62 StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;6364 /// Current inflation for `InflationBlockInterval` number of blocks65 #[pallet::storage]66 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;6768 /// Next target (relay) block when inflation will be applied69 #[pallet::storage]70 pub type NextInflationBlock<T: Config> =71 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;7273 /// Next target (relay) block when inflation is recalculated74 #[pallet::storage]75 pub type NextRecalculationBlock<T: Config> =76 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;7778 #[pallet::hooks]62 trait Store for Module<T: Config> as Inflation {79 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {63 /// starting year total issuance80 fn on_initialize(_: T::BlockNumber) -> Weight81 where82 <T as frame_system::Config>::BlockNumber: From<u32>,83 {84 let mut consumed_weight = 0;85 let mut add_weight = |reads, writes, weight| {86 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);87 consumed_weight += weight;88 };8964 pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;90 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);6591 let current_relay_block = T::BlockNumberProvider::current_block_number();66 /// Current block inflation92 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();93 add_weight(1, 0, 5_000_000);9495 // Apply inflation every InflationBlockInterval blocks96 // If next_inflation == 0, this means inflation wasn't yet initialized97 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {98 // Recalculate inflation on the first block of the year (or if it is not initialized yet)99 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"100 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.101 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();102 add_weight(1, 0, 0);103 if current_relay_block >= next_recalculation {104 Self::recalculate_inflation(next_recalculation);105 add_weight(0, 4, 5_000_000);106 }107108 T::Currency::deposit_into_existing(109 &T::TreasuryAccountId::get(),67 pub BlockInflation get(fn block_inflation): BalanceOf<T>;110 <BlockInflation<T>>::get(),68 }111 )69}112 .ok();7011371decl_module! {114 // Update inflation block115 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());116117 add_weight(3, 3, 10_000_000);118 }119120 consumed_weight121 }122 }123124 #[pallet::call]125 impl<T: Config> Pallet<T> {126 /// This method sets the inflation start date. Can be only called once.127 /// Inflation start block can be backdated and will catch up. The method will create Treasury128 /// account if it does not exist and perform the first inflation deposit.129 ///130 /// # Permissions131 ///132 /// * Root133 ///134 /// # Arguments135 ///136 /// * inflation_start_relay_block: The relay chain block at which inflation should start137 #[pallet::weight(0)]138 pub fn start_inflation(139 origin: OriginFor<T>,140 inflation_start_relay_block: T::BlockNumber,141 ) -> DispatchResult142 where143 <T as frame_system::Config>::BlockNumber: From<u32>,144 {145 ensure_root(origin)?;146147 // Start inflation if it has not been yet initialized148 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();149 if next_inflation == 0u32.into() {150 // Recalculate inflation. This can be backdated and will catch up.151 Self::recalculate_inflation(inflation_start_relay_block);152 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);153 <NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());154155 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else156 T::Currency::deposit_creating(157 &T::TreasuryAccountId::get(),158 <BlockInflation<T>>::get(),159 );160 }161162 Ok(())163 }164 }165}16672 pub struct Module<T: Config> for enum Call167impl<T: Config> Pallet<T> {73 where74 origin: T::Origin,75 {76 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();7778 fn on_initialize(now: T::BlockNumber) -> Weight168 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {79 {80 let mut consumed_weight = 0;169 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR))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() {170 .try_into()171 .unwrap_or(0);93 let current_year: u32 = (now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);172 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);9417395 let one_percent = Perbill::from_percent(1);174 let one_percent = Perbill::from_percent(1);9617597 if current_year <= TOTAL_YEARS_UNTIL_FLAT {176 if current_year <= TOTAL_YEARS_UNTIL_FLAT {98 let amount: BalanceOf<T> = Perbill::from_rational(177 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)),178 block_interval179 * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT180 - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),100 YEAR * TOTAL_YEARS_UNTIL_FLAT181 YEAR * TOTAL_YEARS_UNTIL_FLAT,101 ) * ( one_percent * T::Currency::total_issuance() );182 ) * (one_percent * T::Currency::total_issuance());102 <BlockInflation<T>>::put(amount);183 <BlockInflation<T>>::put(amount);103 }184 } else {104 else {105 let amount: BalanceOf<T> = Perbill::from_rational(185 let amount: BalanceOf<T> =106 block_interval * END_INFLATION_PERCENT,186 Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)107 YEAR108 ) * (one_percent * T::Currency::total_issuance());187 * (one_percent * T::Currency::total_issuance());109 <BlockInflation<T>>::put(amount);188 <BlockInflation<T>>::put(amount);110 }189 }111 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());190 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());112191113 // First time deposit192 // Update recalculation and inflation blocks114 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() {193 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());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 }194 }128129 }195}130}131196pallets/inflation/src/tests.rsdiffbeforeafterboth3use crate as pallet_inflation;3use crate as pallet_inflation;445use frame_support::{5use frame_support::{6 assert_ok, parameter_types,6 traits::{Currency},7 traits::{Currency, OnInitialize, Everything},7 parameter_types,8};8};9use frame_support::{9use frame_system::RawOrigin;10 traits::{OnInitialize, Everything},11};12use sp_core::H256;10use sp_core::H256;13use sp_runtime::{11use sp_runtime::{14 traits::{BlakeTwo256, IdentityLookup},12 traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},15 testing::Header,13 testing::Header,16};14};171518type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;16type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;19type Block = frame_system::mocking::MockBlock<Test>;17type Block = frame_system::mocking::MockBlock<Test>;201821const YEAR: u64 = 2_629_800;19const YEAR: u64 = 5_259_600; // 6-second blocks20 // const YEAR: u64 = 2_629_800; // 12-second blocks21 // Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = FIRST_YEAR_BLOCK_INFLATION22const FIRST_YEAR_BLOCK_INFLATION: u64 = 1901;222323parameter_types! {24parameter_types! {24 pub const ExistentialDeposit: u64 = 1;25 pub const ExistentialDeposit: u64 = 1;85parameter_types! {86parameter_types! {86 pub TreasuryAccountId: u64 = 1234;87 pub TreasuryAccountId: u64 = 1234;87 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied88 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied89 pub static MockBlockNumberProvider: u64 = 0;88}90}9192impl BlockNumberProvider for MockBlockNumberProvider {93 type BlockNumber = u64;9495 fn current_block_number() -> Self::BlockNumber {96 Self::get()97 }98}899990impl pallet_inflation::Config for Test {100impl pallet_inflation::Config for Test {91 type Currency = Balances;101 type Currency = Balances;92 type TreasuryAccountId = TreasuryAccountId;102 type TreasuryAccountId = TreasuryAccountId;93 type InflationBlockInterval = InflationBlockInterval;103 type InflationBlockInterval = InflationBlockInterval;104 type BlockNumberProvider = MockBlockNumberProvider;94}105}9510696pub fn new_test_ext() -> sp_io::TestExternalities {107pub fn new_test_ext() -> sp_io::TestExternalities {100 .into()111 .into()101}112}113114macro_rules! block_inflation {115 // Block inflation doesn't have any argumets116 () => {117 // Return BlockInflation state variable current value118 <pallet_inflation::BlockInflation<Test>>::get()119 };120}121122#[test]123fn uninitialized_inflation() {124 new_test_ext().execute_with(|| {125 let initial_issuance: u64 = 1_000_000_000;126 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);127 assert_eq!(Balances::free_balance(1234), initial_issuance);128129 // BlockInflation should be set after inflation is started130 // first inflation deposit should be equal to BlockInflation131 MockBlockNumberProvider::set(1);132133 assert_eq!(block_inflation!(), 0);134 });135}102136103#[test]137#[test]104fn inflation_works() {138fn inflation_works() {108 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);142 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);109 assert_eq!(Balances::free_balance(1234), initial_issuance);143 assert_eq!(Balances::free_balance(1234), initial_issuance);110144111 // BlockInflation should be set after 1st block and145 // BlockInflation should be set after inflation is started112 // first inflation deposit should be equal to BlockInflation146 // first inflation deposit should be equal to BlockInflation113 Inflation::on_initialize(1);147 MockBlockNumberProvider::set(1);114148115 // Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803149 // Start inflation as sudo150 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));151 assert_eq!(block_inflation!(), FIRST_YEAR_BLOCK_INFLATION);116 assert_eq!(Inflation::block_inflation(), 3803);152 assert_eq!(153 Balances::free_balance(1234) - initial_issuance,154 block_inflation!()155 );156157 // Trigger inflation158 MockBlockNumberProvider::set(102);159 Inflation::on_initialize(0);117 assert_eq!(160 assert_eq!(118 Balances::free_balance(1234) - initial_issuance,161 Balances::free_balance(1234) - initial_issuance,119 Inflation::block_inflation()162 2 * block_inflation!()120 );163 );121 });164 });122}165}128 let initial_issuance: u64 = 1_000_000_000;171 let initial_issuance: u64 = 1_000_000_000;129 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);172 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);130 assert_eq!(Balances::free_balance(1234), initial_issuance);173 assert_eq!(Balances::free_balance(1234), initial_issuance);131 Inflation::on_initialize(1);174 MockBlockNumberProvider::set(1);175176 // Start inflation as sudo177 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));132178133 // Next inflation deposit happens when block is multiple of InflationBlockInterval179 // Next inflation deposit happens when block is greater then or equal to NextInflationBlock134 let mut block: u32 = 2;180 let mut block: u64 = 2;135 let balance_before: u64 = Balances::free_balance(1234);181 let balance_before: u64 = Balances::free_balance(1234);136 while block % InflationBlockInterval::get() != 0 {182 while block < <pallet_inflation::NextInflationBlock<Test>>::get() {137 Inflation::on_initialize(block as u64);183 MockBlockNumberProvider::set(block as u64);184 Inflation::on_initialize(0);138 block += 1;185 block += 1;139 }186 }140 let balance_just_before: u64 = Balances::free_balance(1234);187 let balance_just_before: u64 = Balances::free_balance(1234);141 assert_eq!(balance_before, balance_just_before);188 assert_eq!(balance_before, balance_just_before);142189143 // The block with inflation190 // The block with inflation144 Inflation::on_initialize(block as u64);191 MockBlockNumberProvider::set(block as u64);192 Inflation::on_initialize(0);145 let balance_after: u64 = Balances::free_balance(1234);193 let balance_after: u64 = Balances::free_balance(1234);146 assert_eq!(194 assert_eq!(balance_after - balance_just_before, block_inflation!());147 balance_after - balance_just_before,148 Inflation::block_inflation()149 );150 });195 });151}196}157 let initial_issuance: u64 = 1_000_000_000;202 let initial_issuance: u64 = 1_000_000_000;158 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);203 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);159 assert_eq!(Balances::free_balance(1234), initial_issuance);204 assert_eq!(Balances::free_balance(1234), initial_issuance);160 Inflation::on_initialize(1);205 MockBlockNumberProvider::set(1);206207 // Start inflation as sudo208 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));161209162 // Go through all the block inflations for year 1,210 // Go through all the block inflations for year 1,163 // total issuance will be updated accordingly211 // total issuance will be updated accordingly212 // Inflation is set to start in block 1, so first iteration is block 101164 for block in (100..YEAR).step_by(100) {213 for block in (101..YEAR).step_by(100) {214 MockBlockNumberProvider::set(block);165 Inflation::on_initialize(block);215 Inflation::on_initialize(0);166 }216 }167 assert_eq!(217 assert_eq!(168 initial_issuance + (3803 * (YEAR / 100)),218 initial_issuance + (FIRST_YEAR_BLOCK_INFLATION * (YEAR / 100)),169 <Balances as Currency<_>>::total_issuance()219 <Balances as Currency<_>>::total_issuance()170 );220 );171221222 MockBlockNumberProvider::set(YEAR + 1);172 Inflation::on_initialize(YEAR);223 Inflation::on_initialize(0);173 let block_inflation_year_1 = Inflation::block_inflation();224 let block_inflation_year_2 = block_inflation!();174 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904225 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR == 1951226 let expecter_year_2_inflation: u64 = (initial_issuance227 + FIRST_YEAR_BLOCK_INFLATION * YEAR / 100)228 * 933 * 100 / (10000 * YEAR);175 assert_eq!(block_inflation_year_1, 3904);229 assert_eq!(block_inflation_year_2 / 10, expecter_year_2_inflation / 10); // divide by 10 for approx. equality176 });230 });177}231}178179#[test]180fn inflation_in_1_to_9_years() {181 new_test_ext().execute_with(|| {182 // Total issuance = 1_000_000_000183 let initial_issuance: u64 = 1_000_000_000;184 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);185 assert_eq!(Balances::free_balance(1234), initial_issuance);186 Inflation::on_initialize(1);187188 for year in 1..=9 {189 let block_inflation_year_before = Inflation::block_inflation();190 Inflation::on_initialize(YEAR * year);191 let block_inflation_year_after = Inflation::block_inflation();192193 // SBP M2 review: this is actually not true (not for the first few years)194 // Assert that next year inflation is less than previous year inflation195 assert!(block_inflation_year_before > block_inflation_year_after);196 }197 });198}199232200#[test]233#[test]201fn inflation_after_year_10_is_flat() {234fn inflation_after_year_10_is_flat() {204 let initial_issuance: u64 = 1_000_000_000;237 let initial_issuance: u64 = 1_000_000_000;205 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);238 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);206 assert_eq!(Balances::free_balance(1234), initial_issuance);239 assert_eq!(Balances::free_balance(1234), initial_issuance);207 Inflation::on_initialize(YEAR * 9);240 MockBlockNumberProvider::set(YEAR * 9 + 1);241242 // Start inflation as sudo243 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));244245 // Let inflation catch up246 for _year in 1..=9 {247 Inflation::on_initialize(0);248 }208249209 for year in 10..=20 {250 for year in 10..=20 {210 let block_inflation_year_before = Inflation::block_inflation();251 let block_inflation_year_before = block_inflation!();211 Inflation::on_initialize(YEAR * year);252 MockBlockNumberProvider::set(YEAR * year + 1);253 Inflation::on_initialize(0);212 let block_inflation_year_after = Inflation::block_inflation();254 let block_inflation_year_after = block_inflation!();213255214 // Assert that next year inflation is equal to previous year inflation256 // Assert that next year inflation is equal to previous year inflation215 assert_eq!(block_inflation_year_before, block_inflation_year_after);257 assert_eq!(block_inflation_year_before, block_inflation_year_after);231 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);273 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);232 assert_eq!(Balances::free_balance(1234), initial_issuance);274 assert_eq!(Balances::free_balance(1234), initial_issuance);275276 // Start inflation as sudo277 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));233278234 for year in 0..=10 {279 for year in 0..=10 {235 // Year first block280 // Year first block281 MockBlockNumberProvider::set(YEAR * year + 1);236 Inflation::on_initialize(year * YEAR);282 Inflation::on_initialize(0);237 let mut actual_payout = Inflation::block_inflation();283 let mut actual_payout = block_inflation!();238 assert_eq!(actual_payout, payout_by_year[year as usize]);284 assert_eq!(actual_payout, payout_by_year[year as usize]);239285240 // Year second block286 // Year second block241 Inflation::on_initialize(year * YEAR + 1);287 MockBlockNumberProvider::set(YEAR * year + 2);288 Inflation::on_initialize(0);242 actual_payout = Inflation::block_inflation();289 actual_payout = block_inflation!();243 assert_eq!(actual_payout, payout_by_year[year as usize]);290 assert_eq!(actual_payout, payout_by_year[year as usize]);244291245 // Year middle block292 // Year middle block246 Inflation::on_initialize(year * YEAR + YEAR / 2);293 MockBlockNumberProvider::set(year * YEAR + YEAR / 2);294 Inflation::on_initialize(0);247 actual_payout = Inflation::block_inflation();295 actual_payout = block_inflation!();248 assert_eq!(actual_payout, payout_by_year[year as usize]);296 assert_eq!(actual_payout, payout_by_year[year as usize]);249297250 // Year last block298 // Year last block251 Inflation::on_initialize((year + 1) * YEAR - 1);299 MockBlockNumberProvider::set((year + 1) * YEAR);300 Inflation::on_initialize(0);252 actual_payout = Inflation::block_inflation();301 actual_payout = block_inflation!();253 assert_eq!(actual_payout, payout_by_year[year as usize]);302 assert_eq!(actual_payout, payout_by_year[year as usize]);254 }303 }255 });304 });runtime/Cargo.tomldiffbeforeafterboth33 'pallet-refungible/runtime-benchmarks',33 'pallet-refungible/runtime-benchmarks',34 'pallet-nonfungible/runtime-benchmarks',34 'pallet-nonfungible/runtime-benchmarks',35 'pallet-unique/runtime-benchmarks',35 'pallet-unique/runtime-benchmarks',36# 'pallet-inflation/runtime-benchmarks',36 'pallet-inflation/runtime-benchmarks',37 'pallet-xcm/runtime-benchmarks',37 'pallet-xcm/runtime-benchmarks',38 'sp-runtime/runtime-benchmarks',38 'sp-runtime/runtime-benchmarks',39 'xcm-builder/runtime-benchmarks',39 'xcm-builder/runtime-benchmarks',75 'fp-self-contained/std',75 'fp-self-contained/std',76 'parachain-info/std',76 'parachain-info/std',77 'serde',77 'serde',78# 'pallet-inflation/std',78 'pallet-inflation/std',79 'pallet-common/std',79 'pallet-common/std',80 'pallet-fungible/std',80 'pallet-fungible/std',81 'pallet-refungible/std',81 'pallet-refungible/std',380pallet-unique = { path = '../pallets/unique', default-features = false }380pallet-unique = { path = '../pallets/unique', default-features = false }381up-rpc = { path = "../primitives/rpc", default-features = false }381up-rpc = { path = "../primitives/rpc", default-features = false }382up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }382up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }383# pallet-inflation = { path = '../pallets/inflation', default-features = false }383pallet-inflation = { path = '../pallets/inflation', default-features = false }384up-data-structs = { path = '../primitives/data-structs', default-features = false }384up-data-structs = { path = '../primitives/data-structs', default-features = false }385pallet-common = { default-features = false, path = "../pallets/common" }385pallet-common = { default-features = false, path = "../pallets/common" }386pallet-fungible = { default-features = false, path = "../pallets/fungible" }386pallet-fungible = { default-features = false, path = "../pallets/fungible" }runtime/src/lib.rsdiffbeforeafterboth785 type Event = Event;785 type Event = Event;786 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;786 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;787}787}788/*788789parameter_types! {789parameter_types! {790 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied790 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied791} */791}792792793/// Used for the pallet inflation793/// Used for the pallet inflation794/* impl pallet_inflation::Config for Runtime {794impl pallet_inflation::Config for Runtime {795 type Currency = Balances;795 type Currency = Balances;796 type TreasuryAccountId = TreasuryAccountId;796 type TreasuryAccountId = TreasuryAccountId;797 type InflationBlockInterval = InflationBlockInterval;797 type InflationBlockInterval = InflationBlockInterval;798} */798 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;799}799800800// parameter_types! {801// parameter_types! {801// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *802// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *882 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,883 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,883884884 // Unique Pallets885 // Unique Pallets885 // Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,886 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,886 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,887 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,887 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,888 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,888 // free = 63889 // free = 63136713681368 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1369 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1369 list_benchmark!(list, extra, pallet_unique, Unique);1370 list_benchmark!(list, extra, pallet_unique, Unique);1370 //list_benchmark!(list, extra, pallet_inflation, Inflation);1371 list_benchmark!(list, extra, pallet_inflation, Inflation);1371 list_benchmark!(list, extra, pallet_fungible, Fungible);1372 list_benchmark!(list, extra, pallet_fungible, Fungible);1372 list_benchmark!(list, extra, pallet_refungible, Refungible);1373 list_benchmark!(list, extra, pallet_refungible, Refungible);1373 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1374 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);140114021402 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1403 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1403 add_benchmark!(params, batches, pallet_unique, Unique);1404 add_benchmark!(params, batches, pallet_unique, Unique);1404 //add_benchmark!(params, batches, pallet_inflation, Inflation);1405 add_benchmark!(params, batches, pallet_inflation, Inflation);1405 add_benchmark!(params, batches, pallet_fungible, Fungible);1406 add_benchmark!(params, batches, pallet_fungible, Fungible);1406 add_benchmark!(params, batches, pallet_refungible, Refungible);1407 add_benchmark!(params, batches, pallet_refungible, Refungible);1407 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1408 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth34// Skip the inflation block pauses if the block is close to inflation block34// Skip the inflation block pauses if the block is close to inflation block35// until the inflation happens35// until the inflation happens36/*eslint no-async-promise-executor: "off"*/36/*eslint no-async-promise-executor: "off"*/37/*function skipInflationBlock(api: ApiPromise): Promise<void> {37function skipInflationBlock(api: ApiPromise): Promise<void> {38 const promise = new Promise<void>(async (resolve) => {38 const promise = new Promise<void>(async (resolve) => {39 const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();39 const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {41 const currentBlock = head.number.toNumber();41 const currentBlock = head.number.toNumber();42 if (currentBlock % blockInterval < blockInterval - 10) {42 if (currentBlock % blockInterval < blockInterval - 10) {43 unsubscribe();43 unsubscribe();44 resolve();44 resolve();45 } else {45 } else {46 console.log(`Skipping inflation block, current block: ${currentBlock}`);46 console.log(`Skipping inflation block, current block: ${currentBlock}`);47 }47 }48 });48 });49 });49 });505051 return promise;51 return promise;52}*/52}535354describe('integration test: Fees must be credited to Treasury:', () => {54describe('integration test: Fees must be credited to Treasury:', () => {55 before(async () => {55 before(async () => {616162 it('Total issuance does not change', async () => {62 it('Total issuance does not change', async () => {63 await usingApi(async (api) => {63 await usingApi(async (api) => {64 //await skipInflationBlock(api);64 await skipInflationBlock(api);65 await waitNewBlocks(api, 1);65 await waitNewBlocks(api, 1);666667 const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();67 const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();818182 it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {82 it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {83 await usingApi(async (api) => {83 await usingApi(async (api) => {84 //await skipInflationBlock(api);84 await skipInflationBlock(api);85 await waitNewBlocks(api, 1);85 await waitNewBlocks(api, 1);868687 const alicePrivateKey = privateKey('//Alice');87 const alicePrivateKey = privateKey('//Alice');125125126 it('NFT Transactions also send fees to Treasury', async () => {126 it('NFT Transactions also send fees to Treasury', async () => {127 await usingApi(async (api) => {127 await usingApi(async (api) => {128 //await skipInflationBlock(api);128 await skipInflationBlock(api);129 await waitNewBlocks(api, 1);129 await waitNewBlocks(api, 1);130130131 const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();131 const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();144144145 it('Fees are sane', async () => {145 it('Fees are sane', async () => {146 await usingApi(async (api) => {146 await usingApi(async (api) => {147 //await skipInflationBlock(api);147 await skipInflationBlock(api);148 await waitNewBlocks(api, 1);148 await waitNewBlocks(api, 1);149149150 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();150 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();161161162 it('NFT Transfer fee is close to 0.1 Unique', async () => {162 it('NFT Transfer fee is close to 0.1 Unique', async () => {163 await usingApi(async (api) => {163 await usingApi(async (api) => {164 //await skipInflationBlock(api);164 await skipInflationBlock(api);165 await waitNewBlocks(api, 1);165 await waitNewBlocks(api, 1);166166167 const collectionId = await createCollectionExpectSuccess();167 const collectionId = await createCollectionExpectSuccess();tests/src/inflation.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import {default as usingApi} from './substrate/substrate-api';8import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';9import privateKey from './substrate/privateKey';91010chai.use(chaiAsPromised);11chai.use(chaiAsPromised);11const expect = chai.expect;12const expect = chai.expect;121313describe.skip('integration test: Inflation', () => {14describe('integration test: Inflation', () => {14 it('First year inflation is 10%', async () => {15 it('First year inflation is 10%', async () => {15 await usingApi(async (api) => {16 await usingApi(async (api) => {1718 // Make sure non-sudo can't start inflation19 const tx = api.tx.inflation.startInflation(1);20 const bob = privateKey('//Bob');21 await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;2223 // Start inflation on relay block 1 (Alice is sudo)24 const alice = privateKey('//Alice');25 const sudoTx = api.tx.sudo.sudo(tx as any);26 await submitTransactionAsync(alice, sudoTx);162717 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();28 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();18 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();29 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();19 const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();30 const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();203121 // const YEAR = 5259600n; // 6-second block. Blocks in one year22 const YEAR = 2629800n; // 12-second block. Blocks in one year32 const YEAR = 5259600n; // 6-second block. Blocks in one year33 // const YEAR = 2629800n; // 12-second block. Blocks in one year233424 const totalExpectedInflation = totalIssuanceStart / 10n;35 const totalExpectedInflation = totalIssuanceStart / 10n;25 const totalActualInflation = blockInflation * YEAR / blockInterval;36 const totalActualInflation = blockInflation * YEAR / blockInterval;tests/src/pallet-presence.test.tsdiffbeforeafterboth34 'polkadotxcm',34 'polkadotxcm',35 'cumulusxcm',35 'cumulusxcm',36 'dmpqueue',36 'dmpqueue',37 //'inflation',37 'inflation',38 'unique',38 'unique',39 'nonfungible',39 'nonfungible',40 'refungible',40 'refungible',