git.delta.rocks / unique-network / refs/commits / 44c855833903

difftreelog

Merge pull request #255 from UniqueNetwork/feature/CORE-247

kozyrevdev2021-12-09parents: #6388bd8 #f94b311.patch.diff
in: master
Inflation pallet block provider added. Setted up to relay chain.

8 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11679,6 +11679,7 @@
  "pallet-evm-migration",
  "pallet-evm-transaction-payment",
  "pallet-fungible",
+ "pallet-inflation",
  "pallet-nonfungible",
  "pallet-randomness-collective-flip",
  "pallet-refungible",
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -3,13 +3,8 @@
 // file 'LICENSE', which is part of this source code package.
 //
 
-#![recursion_limit = "1024"]
+// #![recursion_limit = "1024"]
 #![cfg_attr(not(feature = "std"), no_std)]
-
-#[cfg(feature = "std")]
-pub use std::*;
-
-pub use serde::{Serialize, Deserialize};
 
 #[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
@@ -17,65 +12,74 @@
 #[cfg(test)]
 mod tests;
 
-pub use frame_support::{
-	construct_runtime, decl_module, decl_storage, ensure,
-	traits::{
-		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
-		Randomness, IsSubType, WithdrawReasons,
-	},
-	weights::{
-		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
-		WeightToFeePolynomial, DispatchClass,
-	},
-	StorageValue, transactional,
+use frame_support::{
+	dispatch::{DispatchResult},
+	traits::{Currency, Get},
 };
-
-// #[cfg(feature = "runtime-benchmarks")]
-pub use frame_support::dispatch::DispatchResult;
-
+pub use pallet::*;
 use sp_runtime::{
 	Perbill,
-	traits::{Zero},
+	traits::{BlockNumberProvider},
 };
+
 use sp_std::convert::TryInto;
-
-use frame_system::{self as system};
 
-/// The balance type of this module.
-pub type BalanceOf<T> =
+type BalanceOf<T> =
 	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
 
-// pub const YEAR: u32 = 5_259_600; // 6-second block
-pub const YEAR: u32 = 2_629_800; // 12-second block
+pub const YEAR: u32 = 5_259_600; // 6-second block
+								 // pub const YEAR: u32 = 2_629_800; // 12-second block
 pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;
 pub const START_INFLATION_PERCENT: u32 = 10;
 pub const END_INFLATION_PERCENT: u32 = 4;
 
-pub trait Config: system::Config {
-	type Currency: Currency<Self::AccountId>;
-	type TreasuryAccountId: Get<Self::AccountId>;
-	type InflationBlockInterval: Get<Self::BlockNumber>;
-}
+#[frame_support::pallet]
+pub mod pallet {
+	use super::*;
+	use frame_support::pallet_prelude::*;
+	use frame_system::pallet_prelude::*;
 
-decl_storage! {
-	trait Store for Module<T: Config> as Inflation {
-		/// starting year total issuance
-		pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;
+	#[pallet::config]
+	pub trait Config: frame_system::Config {
+		type Currency: Currency<Self::AccountId>;
+		type TreasuryAccountId: Get<Self::AccountId>;
+
+		// The block number provider
+		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
 
-		/// Current block inflation
-		pub BlockInflation get(fn block_inflation): BalanceOf<T>;
+		/// Number of blocks that pass between treasury balance updates due to inflation
+		#[pallet::constant]
+		type InflationBlockInterval: Get<Self::BlockNumber>;
 	}
-}
 
-decl_module! {
-	pub struct Module<T: Config> for enum Call
-	where
-		origin: T::Origin,
-	{
-		const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	pub struct Pallet<T>(_);
+
+	/// starting year total issuance
+	#[pallet::storage]
+	pub type StartingYearTotalIssuance<T: Config> =
+		StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;
 
-		fn on_initialize(now: T::BlockNumber) -> Weight
+	/// Current inflation for `InflationBlockInterval` number of blocks
+	#[pallet::storage]
+	pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;
+
+	/// Next target (relay) block when inflation will be applied
+	#[pallet::storage]
+	pub type NextInflationBlock<T: Config> =
+		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+
+	/// Next target (relay) block when inflation is recalculated
+	#[pallet::storage]
+	pub type NextRecalculationBlock<T: Config> =
+		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+
+	#[pallet::hooks]
+	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+		fn on_initialize(_: T::BlockNumber) -> Weight
+		where
+			<T as frame_system::Config>::BlockNumber: From<u32>,
 		{
 			let mut consumed_weight = 0;
 			let mut add_weight = |reads, writes, weight| {
@@ -84,47 +88,108 @@
 			};
 
 			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
+			let current_relay_block = T::BlockNumberProvider::current_block_number();
+			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
+			add_weight(1, 0, 5_000_000);
 
-			// TODO: Rewrite inflation to use block timestamp instead of block number
-			// let _now = <timestamp::Module<T>>::get();
+			// Apply inflation every InflationBlockInterval blocks
+			// If next_inflation == 0, this means inflation wasn't yet initialized
+			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {
+				// Recalculate inflation on the first block of the year (or if it is not initialized yet)
+				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"
+				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.
+				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();
+				add_weight(1, 0, 0);
+				if current_relay_block >= next_recalculation {
+					Self::recalculate_inflation(next_recalculation);
+					add_weight(0, 4, 5_000_000);
+				}
 
-			// Recalculate inflation on the first block of the year (or if it is not initialized yet)
-			if (now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {
-				let current_year: u32 = (now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);
+				T::Currency::deposit_into_existing(
+					&T::TreasuryAccountId::get(),
+					<BlockInflation<T>>::get(),
+				)
+				.ok();
 
-				let one_percent = Perbill::from_percent(1);
+				// Update inflation block
+				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());
 
-				if current_year <= TOTAL_YEARS_UNTIL_FLAT {
-					let amount: BalanceOf<T> = Perbill::from_rational(
-						block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),
-						YEAR * TOTAL_YEARS_UNTIL_FLAT
-					) * ( one_percent * T::Currency::total_issuance() );
-					<BlockInflation<T>>::put(amount);
-				}
-				else {
-					let amount: BalanceOf<T> = Perbill::from_rational(
-						block_interval * END_INFLATION_PERCENT,
-						YEAR
-					) * (one_percent * T::Currency::total_issuance());
-					<BlockInflation<T>>::put(amount);
-				}
-				<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());
+				add_weight(3, 3, 10_000_000);
+			}
+
+			consumed_weight
+		}
+	}
+
+	#[pallet::call]
+	impl<T: Config> Pallet<T> {
+		/// This method sets the inflation start date. Can be only called once.
+		/// Inflation start block can be backdated and will catch up. The method will create Treasury
+		/// account if it does not exist and perform the first inflation deposit.
+		///
+		/// # Permissions
+		///
+		/// * Root
+		///
+		/// # Arguments
+		///
+		/// * inflation_start_relay_block: The relay chain block at which inflation should start
+		#[pallet::weight(0)]
+		pub fn start_inflation(
+			origin: OriginFor<T>,
+			inflation_start_relay_block: T::BlockNumber,
+		) -> DispatchResult
+		where
+			<T as frame_system::Config>::BlockNumber: From<u32>,
+		{
+			ensure_root(origin)?;
 
-				// First time deposit
-				T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
+			// Start inflation if it has not been yet initialized
+			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
+			if next_inflation == 0u32.into() {
+				// Recalculate inflation. This can be backdated and will catch up.
+				Self::recalculate_inflation(inflation_start_relay_block);
+				let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
+				<NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());
 
-				add_weight(7, 6, 28_300_000);
+				// First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else
+				T::Currency::deposit_creating(
+					&T::TreasuryAccountId::get(),
+					<BlockInflation<T>>::get(),
+				);
 			}
 
-			// Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account
-			else if (now % T::BlockNumber::from(block_interval)).is_zero() {
-				T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();
+			Ok(())
+		}
+	}
+}
+
+impl<T: Config> Pallet<T> {
+	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
+		let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR))
+			.try_into()
+			.unwrap_or(0);
+		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
 
-				add_weight(3, 2, 12_900_000);
-			}
+		let one_percent = Perbill::from_percent(1);
 
-			consumed_weight
+		if current_year <= TOTAL_YEARS_UNTIL_FLAT {
+			let amount: BalanceOf<T> = Perbill::from_rational(
+				block_interval
+					* (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT
+						- current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),
+				YEAR * TOTAL_YEARS_UNTIL_FLAT,
+			) * (one_percent * T::Currency::total_issuance());
+			<BlockInflation<T>>::put(amount);
+		} else {
+			let amount: BalanceOf<T> =
+				Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)
+					* (one_percent * T::Currency::total_issuance());
+			<BlockInflation<T>>::put(amount);
 		}
+		<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());
 
+		// Update recalculation and inflation blocks
+		<NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());
 	}
 }
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
before · pallets/inflation/src/tests.rs
1#![cfg(test)]2#![allow(clippy::from_over_into)]3use crate as pallet_inflation;45use frame_support::{6	traits::{Currency},7	parameter_types,8};9use frame_support::{10	traits::{OnInitialize, Everything},11};12use sp_core::H256;13use sp_runtime::{14	traits::{BlakeTwo256, IdentityLookup},15	testing::Header,16};1718type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;19type Block = frame_system::mocking::MockBlock<Test>;2021const YEAR: u64 = 2_629_800;2223parameter_types! {24	pub const ExistentialDeposit: u64 = 1;25	pub const MaxLocks: u32 = 50;26}2728impl pallet_balances::Config for Test {29	type AccountStore = System;30	type Balance = u64;31	type DustRemoval = ();32	type Event = ();33	type ExistentialDeposit = ExistentialDeposit;34	type WeightInfo = ();35	type MaxLocks = MaxLocks;36	type MaxReserves = ();37	type ReserveIdentifier = ();38}3940frame_support::construct_runtime!(41	pub enum Test where42		Block = Block,43		NodeBlock = Block,44		UncheckedExtrinsic = UncheckedExtrinsic,45	{46		Balances: pallet_balances::{Pallet, Call, Storage},47		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},48		Inflation: pallet_inflation::{Pallet, Call, Storage},49	}50);5152parameter_types! {53	pub const BlockHashCount: u64 = 250;54	pub BlockWeights: frame_system::limits::BlockWeights =55		frame_system::limits::BlockWeights::simple_max(1024);56	pub const SS58Prefix: u8 = 42;57}5859impl frame_system::Config for Test {60	type BaseCallFilter = Everything;61	type BlockWeights = ();62	type BlockLength = ();63	type DbWeight = ();64	type Origin = Origin;65	type Call = Call;66	type Index = u64;67	type BlockNumber = u64;68	type Hash = H256;69	type Hashing = BlakeTwo256;70	type AccountId = u64;71	type Lookup = IdentityLookup<Self::AccountId>;72	type Header = Header;73	type Event = ();74	type BlockHashCount = BlockHashCount;75	type Version = ();76	type PalletInfo = PalletInfo;77	type AccountData = pallet_balances::AccountData<u64>;78	type OnNewAccount = ();79	type OnKilledAccount = ();80	type SystemWeightInfo = ();81	type SS58Prefix = SS58Prefix;82	type OnSetCode = ();83}8485parameter_types! {86	pub TreasuryAccountId: u64 = 1234;87	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied88}8990impl pallet_inflation::Config for Test {91	type Currency = Balances;92	type TreasuryAccountId = TreasuryAccountId;93	type InflationBlockInterval = InflationBlockInterval;94}9596pub fn new_test_ext() -> sp_io::TestExternalities {97	frame_system::GenesisConfig::default()98		.build_storage::<Test>()99		.unwrap()100		.into()101}102103#[test]104fn inflation_works() {105	new_test_ext().execute_with(|| {106		// Total issuance = 1_000_000_000107		let initial_issuance: u64 = 1_000_000_000;108		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);109		assert_eq!(Balances::free_balance(1234), initial_issuance);110111		// BlockInflation should be set after 1st block and112		// first inflation deposit should be equal to BlockInflation113		Inflation::on_initialize(1);114115		// Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803116		assert_eq!(Inflation::block_inflation(), 3803);117		assert_eq!(118			Balances::free_balance(1234) - initial_issuance,119			Inflation::block_inflation()120		);121	});122}123124#[test]125fn inflation_second_deposit() {126	new_test_ext().execute_with(|| {127		// Total issuance = 1_000_000_000128		let initial_issuance: u64 = 1_000_000_000;129		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);130		assert_eq!(Balances::free_balance(1234), initial_issuance);131		Inflation::on_initialize(1);132133		// Next inflation deposit happens when block is multiple of InflationBlockInterval134		let mut block: u32 = 2;135		let balance_before: u64 = Balances::free_balance(1234);136		while block % InflationBlockInterval::get() != 0 {137			Inflation::on_initialize(block as u64);138			block += 1;139		}140		let balance_just_before: u64 = Balances::free_balance(1234);141		assert_eq!(balance_before, balance_just_before);142143		// The block with inflation144		Inflation::on_initialize(block as u64);145		let balance_after: u64 = Balances::free_balance(1234);146		assert_eq!(147			balance_after - balance_just_before,148			Inflation::block_inflation()149		);150	});151}152153#[test]154fn inflation_in_1_year() {155	new_test_ext().execute_with(|| {156		// Total issuance = 1_000_000_000157		let initial_issuance: u64 = 1_000_000_000;158		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);159		assert_eq!(Balances::free_balance(1234), initial_issuance);160		Inflation::on_initialize(1);161162		// Go through all the block inflations for year 1,163		// total issuance will be updated accordingly164		for block in (100..YEAR).step_by(100) {165			Inflation::on_initialize(block);166		}167		assert_eq!(168			initial_issuance + (3803 * (YEAR / 100)),169			<Balances as Currency<_>>::total_issuance()170		);171172		Inflation::on_initialize(YEAR);173		let block_inflation_year_1 = Inflation::block_inflation();174		// Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904175		assert_eq!(block_inflation_year_1, 3904);176	});177}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}199200#[test]201fn inflation_after_year_10_is_flat() {202	new_test_ext().execute_with(|| {203		// Total issuance = 1_000_000_000204		let initial_issuance: u64 = 1_000_000_000;205		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);206		assert_eq!(Balances::free_balance(1234), initial_issuance);207		Inflation::on_initialize(YEAR * 9);208209		for year in 10..=20 {210			let block_inflation_year_before = Inflation::block_inflation();211			Inflation::on_initialize(YEAR * year);212			let block_inflation_year_after = Inflation::block_inflation();213214			// Assert that next year inflation is equal to previous year inflation215			assert_eq!(block_inflation_year_before, block_inflation_year_after);216		}217	});218}219220#[test]221fn inflation_rate_by_year() {222	new_test_ext().execute_with(|| {223		let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;224225		// Inflation starts at 10% and does down by 2/3% every year until year 9 (included),226		// then it is flat.227		let payout_by_year: [u64; 11] = [1000, 933, 867, 800, 733, 667, 600, 533, 467, 400, 400];228229		// For accuracy total issuance = payout0 * payouts * 10;230		let initial_issuance: u64 = payout_by_year[0] * payouts * 10;231		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);232		assert_eq!(Balances::free_balance(1234), initial_issuance);233234		for year in 0..=10 {235			// Year first block236			Inflation::on_initialize(year * YEAR);237			let mut actual_payout = Inflation::block_inflation();238			assert_eq!(actual_payout, payout_by_year[year as usize]);239240			// Year second block241			Inflation::on_initialize(year * YEAR + 1);242			actual_payout = Inflation::block_inflation();243			assert_eq!(actual_payout, payout_by_year[year as usize]);244245			// Year middle block246			Inflation::on_initialize(year * YEAR + YEAR / 2);247			actual_payout = Inflation::block_inflation();248			assert_eq!(actual_payout, payout_by_year[year as usize]);249250			// Year last block251			Inflation::on_initialize((year + 1) * YEAR - 1);252			actual_payout = Inflation::block_inflation();253			assert_eq!(actual_payout, payout_by_year[year as usize]);254		}255	});256}
after · pallets/inflation/src/tests.rs
1#![cfg(test)]2#![allow(clippy::from_over_into)]3use crate as pallet_inflation;45use frame_support::{6	assert_ok, parameter_types,7	traits::{Currency, OnInitialize, Everything},8};9use frame_system::RawOrigin;10use sp_core::H256;11use sp_runtime::{12	traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},13	testing::Header,14};1516type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;17type Block = frame_system::mocking::MockBlock<Test>;1819const 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;2324parameter_types! {25	pub const ExistentialDeposit: u64 = 1;26	pub const MaxLocks: u32 = 50;27}2829impl pallet_balances::Config for Test {30	type AccountStore = System;31	type Balance = u64;32	type DustRemoval = ();33	type Event = ();34	type ExistentialDeposit = ExistentialDeposit;35	type WeightInfo = ();36	type MaxLocks = MaxLocks;37	type MaxReserves = ();38	type ReserveIdentifier = ();39}4041frame_support::construct_runtime!(42	pub enum Test where43		Block = Block,44		NodeBlock = Block,45		UncheckedExtrinsic = UncheckedExtrinsic,46	{47		Balances: pallet_balances::{Pallet, Call, Storage},48		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},49		Inflation: pallet_inflation::{Pallet, Call, Storage},50	}51);5253parameter_types! {54	pub const BlockHashCount: u64 = 250;55	pub BlockWeights: frame_system::limits::BlockWeights =56		frame_system::limits::BlockWeights::simple_max(1024);57	pub const SS58Prefix: u8 = 42;58}5960impl frame_system::Config for Test {61	type BaseCallFilter = Everything;62	type BlockWeights = ();63	type BlockLength = ();64	type DbWeight = ();65	type Origin = Origin;66	type Call = Call;67	type Index = u64;68	type BlockNumber = u64;69	type Hash = H256;70	type Hashing = BlakeTwo256;71	type AccountId = u64;72	type Lookup = IdentityLookup<Self::AccountId>;73	type Header = Header;74	type Event = ();75	type BlockHashCount = BlockHashCount;76	type Version = ();77	type PalletInfo = PalletInfo;78	type AccountData = pallet_balances::AccountData<u64>;79	type OnNewAccount = ();80	type OnKilledAccount = ();81	type SystemWeightInfo = ();82	type SS58Prefix = SS58Prefix;83	type OnSetCode = ();84}8586parameter_types! {87	pub TreasuryAccountId: u64 = 1234;88	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied89	pub static MockBlockNumberProvider: u64 = 0;90}9192impl BlockNumberProvider for MockBlockNumberProvider {93	type BlockNumber = u64;9495	fn current_block_number() -> Self::BlockNumber {96		Self::get()97	}98}99100impl pallet_inflation::Config for Test {101	type Currency = Balances;102	type TreasuryAccountId = TreasuryAccountId;103	type InflationBlockInterval = InflationBlockInterval;104	type BlockNumberProvider = MockBlockNumberProvider;105}106107pub fn new_test_ext() -> sp_io::TestExternalities {108	frame_system::GenesisConfig::default()109		.build_storage::<Test>()110		.unwrap()111		.into()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}136137#[test]138fn inflation_works() {139	new_test_ext().execute_with(|| {140		// Total issuance = 1_000_000_000141		let initial_issuance: u64 = 1_000_000_000;142		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);143		assert_eq!(Balances::free_balance(1234), initial_issuance);144145		// BlockInflation should be set after inflation is started146		// first inflation deposit should be equal to BlockInflation147		MockBlockNumberProvider::set(1);148149		// Start inflation as sudo150		assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));151		assert_eq!(block_inflation!(), FIRST_YEAR_BLOCK_INFLATION);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);160		assert_eq!(161			Balances::free_balance(1234) - initial_issuance,162			2 * block_inflation!()163		);164	});165}166167#[test]168fn inflation_second_deposit() {169	new_test_ext().execute_with(|| {170		// Total issuance = 1_000_000_000171		let initial_issuance: u64 = 1_000_000_000;172		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);173		assert_eq!(Balances::free_balance(1234), initial_issuance);174		MockBlockNumberProvider::set(1);175176		// Start inflation as sudo177		assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));178179		// Next inflation deposit happens when block is greater then or equal to NextInflationBlock180		let mut block: u64 = 2;181		let balance_before: u64 = Balances::free_balance(1234);182		while block < <pallet_inflation::NextInflationBlock<Test>>::get() {183			MockBlockNumberProvider::set(block as u64);184			Inflation::on_initialize(0);185			block += 1;186		}187		let balance_just_before: u64 = Balances::free_balance(1234);188		assert_eq!(balance_before, balance_just_before);189190		// The block with inflation191		MockBlockNumberProvider::set(block as u64);192		Inflation::on_initialize(0);193		let balance_after: u64 = Balances::free_balance(1234);194		assert_eq!(balance_after - balance_just_before, block_inflation!());195	});196}197198#[test]199fn inflation_in_1_year() {200	new_test_ext().execute_with(|| {201		// Total issuance = 1_000_000_000202		let initial_issuance: u64 = 1_000_000_000;203		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);204		assert_eq!(Balances::free_balance(1234), initial_issuance);205		MockBlockNumberProvider::set(1);206207		// Start inflation as sudo208		assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));209210		// Go through all the block inflations for year 1,211		// total issuance will be updated accordingly212		// Inflation is set to start in block 1, so first iteration is block 101213		for block in (101..YEAR).step_by(100) {214			MockBlockNumberProvider::set(block);215			Inflation::on_initialize(0);216		}217		assert_eq!(218			initial_issuance + (FIRST_YEAR_BLOCK_INFLATION * (YEAR / 100)),219			<Balances as Currency<_>>::total_issuance()220		);221222		MockBlockNumberProvider::set(YEAR + 1);223		Inflation::on_initialize(0);224		let block_inflation_year_2 = block_inflation!();225		// 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);229		assert_eq!(block_inflation_year_2 / 10, expecter_year_2_inflation / 10); // divide by 10 for approx. equality230	});231}232233#[test]234fn inflation_after_year_10_is_flat() {235	new_test_ext().execute_with(|| {236		// Total issuance = 1_000_000_000237		let initial_issuance: u64 = 1_000_000_000;238		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);239		assert_eq!(Balances::free_balance(1234), initial_issuance);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		}249250		for year in 10..=20 {251			let block_inflation_year_before = block_inflation!();252			MockBlockNumberProvider::set(YEAR * year + 1);253			Inflation::on_initialize(0);254			let block_inflation_year_after = block_inflation!();255256			// Assert that next year inflation is equal to previous year inflation257			assert_eq!(block_inflation_year_before, block_inflation_year_after);258		}259	});260}261262#[test]263fn inflation_rate_by_year() {264	new_test_ext().execute_with(|| {265		let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;266267		// Inflation starts at 10% and does down by 2/3% every year until year 9 (included),268		// then it is flat.269		let payout_by_year: [u64; 11] = [1000, 933, 867, 800, 733, 667, 600, 533, 467, 400, 400];270271		// For accuracy total issuance = payout0 * payouts * 10;272		let initial_issuance: u64 = payout_by_year[0] * payouts * 10;273		let _ = <Balances as Currency<_>>::deposit_creating(&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));278279		for year in 0..=10 {280			// Year first block281			MockBlockNumberProvider::set(YEAR * year + 1);282			Inflation::on_initialize(0);283			let mut actual_payout = block_inflation!();284			assert_eq!(actual_payout, payout_by_year[year as usize]);285286			// Year second block287			MockBlockNumberProvider::set(YEAR * year + 2);288			Inflation::on_initialize(0);289			actual_payout = block_inflation!();290			assert_eq!(actual_payout, payout_by_year[year as usize]);291292			// Year middle block293			MockBlockNumberProvider::set(year * YEAR + YEAR / 2);294			Inflation::on_initialize(0);295			actual_payout = block_inflation!();296			assert_eq!(actual_payout, payout_by_year[year as usize]);297298			// Year last block299			MockBlockNumberProvider::set((year + 1) * YEAR);300			Inflation::on_initialize(0);301			actual_payout = block_inflation!();302			assert_eq!(actual_payout, payout_by_year[year as usize]);303		}304	});305}
modifiedruntime/Cargo.tomldiffbeforeafterboth
--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -33,7 +33,7 @@
     'pallet-refungible/runtime-benchmarks',
     'pallet-nonfungible/runtime-benchmarks',
     'pallet-unique/runtime-benchmarks',
-#    'pallet-inflation/runtime-benchmarks',
+    'pallet-inflation/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -75,7 +75,7 @@
     'fp-self-contained/std',
     'parachain-info/std',
     'serde',
-#    'pallet-inflation/std',
+    'pallet-inflation/std',
     'pallet-common/std',
     'pallet-fungible/std',
     'pallet-refungible/std',
@@ -380,7 +380,7 @@
 pallet-unique = { path = '../pallets/unique', default-features = false }
 up-rpc = { path = "../primitives/rpc", default-features = false }
 up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
-# pallet-inflation = { path = '../pallets/inflation', default-features = false }
+pallet-inflation = { path = '../pallets/inflation', default-features = false }
 up-data-structs = { path = '../primitives/data-structs', default-features = false }
 pallet-common = { default-features = false, path = "../pallets/common" }
 pallet-fungible = { default-features = false, path = "../pallets/fungible" }
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -785,17 +785,18 @@
 	type Event = Event;
 	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
 }
-/*
+
 parameter_types! {
 	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
-} */
+}
 
 /// Used for the pallet inflation
-/* impl pallet_inflation::Config for Runtime {
+impl pallet_inflation::Config for Runtime {
 	type Currency = Balances;
 	type TreasuryAccountId = TreasuryAccountId;
 	type InflationBlockInterval = InflationBlockInterval;
-} */
+	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
+}
 
 // parameter_types! {
 // 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
@@ -882,7 +883,7 @@
 		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,
 
 		// Unique Pallets
-		// Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
+		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
 		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
@@ -1367,7 +1368,7 @@
 
 			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);
 			list_benchmark!(list, extra, pallet_unique, Unique);
-			//list_benchmark!(list, extra, pallet_inflation, Inflation);
+			list_benchmark!(list, extra, pallet_inflation, Inflation);
 			list_benchmark!(list, extra, pallet_fungible, Fungible);
 			list_benchmark!(list, extra, pallet_refungible, Refungible);
 			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);
@@ -1401,7 +1402,7 @@
 
 			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);
 			add_benchmark!(params, batches, pallet_unique, Unique);
-			//add_benchmark!(params, batches, pallet_inflation, Inflation);
+			add_benchmark!(params, batches, pallet_inflation, Inflation);
 			add_benchmark!(params, batches, pallet_fungible, Fungible);
 			add_benchmark!(params, batches, pallet_refungible, Refungible);
 			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -34,7 +34,7 @@
 // Skip the inflation block pauses if the block is close to inflation block
 // until the inflation happens
 /*eslint no-async-promise-executor: "off"*/
-/*function skipInflationBlock(api: ApiPromise): Promise<void> {
+function skipInflationBlock(api: ApiPromise): Promise<void> {
   const promise = new Promise<void>(async (resolve) => {
     const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();
     const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
@@ -49,7 +49,7 @@
   });
 
   return promise;
-}*/
+}
 
 describe('integration test: Fees must be credited to Treasury:', () => {
   before(async () => {
@@ -61,7 +61,7 @@
 
   it('Total issuance does not change', async () => {
     await usingApi(async (api) => {
-      //await skipInflationBlock(api);
+      await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
@@ -81,7 +81,7 @@
 
   it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {
     await usingApi(async (api) => {
-      //await skipInflationBlock(api);
+      await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const alicePrivateKey = privateKey('//Alice');
@@ -125,7 +125,7 @@
 
   it('NFT Transactions also send fees to Treasury', async () => {
     await usingApi(async (api) => {
-      //await skipInflationBlock(api);
+      await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();
@@ -144,7 +144,7 @@
 
   it('Fees are sane', async () => {
     await usingApi(async (api) => {
-      //await skipInflationBlock(api);
+      await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
@@ -161,7 +161,7 @@
 
   it('NFT Transfer fee is close to 0.1 Unique', async () => {
     await usingApi(async (api) => {
-      //await skipInflationBlock(api);
+      await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const collectionId = await createCollectionExpectSuccess();
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -5,21 +5,32 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
+import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import privateKey from './substrate/privateKey';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
-describe.skip('integration test: Inflation', () => {
+describe('integration test: Inflation', () => {
   it('First year inflation is 10%', async () => {
     await usingApi(async (api) => {
 
+      // Make sure non-sudo can't start inflation
+      const tx = api.tx.inflation.startInflation(1);
+      const bob = privateKey('//Bob');
+      await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
+
+      // Start inflation on relay block 1 (Alice is sudo)
+      const alice = privateKey('//Alice');
+      const sudoTx = api.tx.sudo.sudo(tx as any);
+      await submitTransactionAsync(alice, sudoTx);
+
       const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
       const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
       const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();
 
-      // const YEAR = 5259600n;  // 6-second block. Blocks in one year
-      const YEAR = 2629800n; // 12-second block. Blocks in one year
+      const YEAR = 5259600n;  // 6-second block. Blocks in one year
+      // const YEAR = 2629800n; // 12-second block. Blocks in one year
 
       const totalExpectedInflation = totalIssuanceStart / 10n;
       const totalActualInflation = blockInflation * YEAR / blockInterval;
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -34,7 +34,7 @@
   'polkadotxcm',
   'cumulusxcm',
   'dmpqueue',
-  //'inflation',
+  'inflation',
   'unique',
   'nonfungible',
   'refungible',