git.delta.rocks / unique-network / refs/commits / e725f8510927

difftreelog

Replace spaces with tabs

Greg Zaitsev2021-04-07parent: #9d35eac.patch.diff
in: master

2 files changed

modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -20,19 +20,19 @@
 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,
+	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,
 };
 
 // #[cfg(feature = "runtime-benchmarks")]
@@ -40,7 +40,7 @@
 
 use sp_runtime::{
 	Perbill,
-    traits::{Zero}
+	traits::{Zero}
 };
 use sp_std::convert::TryInto;
 
@@ -56,75 +56,75 @@
 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>;
+	type Currency: Currency<Self::AccountId>;
+	type TreasuryAccountId: Get<Self::AccountId>;
+	type InflationBlockInterval: Get<Self::BlockNumber>;
 }
 
 decl_storage! {
-    trait Store for Module<T: Config> as Inflation {
-        /// starting year total issuance
-        pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;
+	trait Store for Module<T: Config> as Inflation {
+		/// starting year total issuance
+		pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;
 
-        /// Current block inflation
-        pub BlockInflation get(fn block_inflation): BalanceOf<T>;
-    }
+		/// Current block inflation
+		pub BlockInflation get(fn block_inflation): BalanceOf<T>;
+	}
 }
 
 decl_module! {
-    pub struct Module<T: Config> for enum Call 
-    where 
-        origin: T::Origin,
-    {
-        const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();
+	pub struct Module<T: Config> for enum Call 
+	where 
+		origin: T::Origin,
+	{
+		const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();
 
-        fn on_initialize(now: T::BlockNumber) -> Weight 
-        {
+		fn on_initialize(now: T::BlockNumber) -> Weight 
+		{
 			let mut consumed_weight = 0;
 			let mut add_weight = |reads, writes, weight| {
 				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
 				consumed_weight += weight;
 			};
 
-            let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
+			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
 
-            // 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);
+			// 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);
 
-                let one_percent = Perbill::from_percent(1);
+				let one_percent = Perbill::from_percent(1);
 
-                if current_year <= TOTAL_YEARS_UNTIL_FLAT {
-                    let amount: BalanceOf<T> = Perbill::from_rational_approximation(
-                        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_approximation(
-                        block_interval * END_INFLATION_PERCENT, 
-                        YEAR
-                    ) * (one_percent * T::Currency::total_issuance());
-                    <BlockInflation<T>>::put(amount);
-                }
-                <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());
+				if current_year <= TOTAL_YEARS_UNTIL_FLAT {
+					let amount: BalanceOf<T> = Perbill::from_rational_approximation(
+						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_approximation(
+						block_interval * END_INFLATION_PERCENT, 
+						YEAR
+					) * (one_percent * T::Currency::total_issuance());
+					<BlockInflation<T>>::put(amount);
+				}
+				<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());
 
-                // First time deposit
-                T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
+				// First time deposit
+				T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
 
-                add_weight(7, 6, 28_300_000);
-            }
+				add_weight(7, 6, 28_300_000);
+			}
 
-            // 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();
+			// 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();
 
-                add_weight(3, 2, 12_900_000);
-            }
+				add_weight(3, 2, 12_900_000);
+			}
 
-            consumed_weight
-        }
+			consumed_weight
+		}
 
-    }
+	}
 }
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
after · pallets/inflation/src/tests.rs
1#[cfg(test)]2mod tests {3	use crate as pallet_inflation;45	use frame_system;6	use frame_support::{traits::{Currency}, parameter_types};7	use frame_support::{traits::OnInitialize};8	use sp_core::H256;9	use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header};1011	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;12	type Block = frame_system::mocking::MockBlock<Test>;1314	const YEAR: u64 = 5_259_600;1516	parameter_types! {17		pub const ExistentialDeposit: u64 = 1;18		pub const MaxLocks: u32 = 50;19	}20	21	impl pallet_balances::Config for Test {22		type AccountStore = System;23		type Balance = u64;24		type DustRemoval = ();25		type Event = ();26		type ExistentialDeposit = ExistentialDeposit;27		type WeightInfo = ();28		type MaxLocks = MaxLocks;29	}30	31	frame_support::construct_runtime!(32		pub enum Test where33			Block = Block,34			NodeBlock = Block,35			UncheckedExtrinsic = UncheckedExtrinsic,36		{37			Balances: pallet_balances::{Module, Call, Storage},38			System: frame_system::{Module, Call, Config, Storage, Event<T>},39			Inflation: pallet_inflation::{Module, Call, Storage},40		}41	);4243	parameter_types! {44		pub const BlockHashCount: u64 = 250;45		pub BlockWeights: frame_system::limits::BlockWeights =46			frame_system::limits::BlockWeights::simple_max(1024);47		pub const SS58Prefix: u8 = 42;48	}4950	impl frame_system::Config for Test {51		type BaseCallFilter = ();52		type BlockWeights = ();53		type BlockLength = ();54		type DbWeight = ();55		type Origin = Origin;56		type Call = Call;57		type Index = u64;58		type BlockNumber = u64;59		type Hash = H256;60		type Hashing = BlakeTwo256;61		type AccountId = u64;62		type Lookup = IdentityLookup<Self::AccountId>;63		type Header = Header;64		type Event = ();65		type BlockHashCount = BlockHashCount;66		type Version = ();67		type PalletInfo = PalletInfo;68		type AccountData = pallet_balances::AccountData<u64>;69		type OnNewAccount = ();70		type OnKilledAccount = ();71		type SystemWeightInfo = ();72		type SS58Prefix = SS58Prefix;73	}7475	parameter_types! {76		pub TreasuryAccountId: u64 = 1234;77		pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied78	}79		80	impl pallet_inflation::Config for Test {81		type Currency = Balances;82		type TreasuryAccountId = TreasuryAccountId;83		type InflationBlockInterval = InflationBlockInterval;84	}8586	// Build genesis storage according to the mock runtime.87	pub fn new_test_ext() -> sp_io::TestExternalities {88		frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into()89	}9091	#[test]92	fn inflation_works() {93		new_test_ext().execute_with(|| {94			// Total issuance = 1_000_000_00095			let initial_issuance: u64 = 1_000_000_000;96			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);97			assert_eq!(Balances::free_balance(1234), initial_issuance);9899			// BlockInflation should be set after 1st block and 100			// first inflation deposit should be equal to BlockInflation101			Inflation::on_initialize(1);102			assert!(Inflation::block_inflation() > 0);103			assert_eq!(Balances::free_balance(1234) - initial_issuance, Inflation::block_inflation());104		});105	}106107	#[test]108	fn inflation_second_deposit() {109		new_test_ext().execute_with(|| {110			// Total issuance = 1_000_000_000111			let initial_issuance: u64 = 1_000_000_000;112			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);113			assert_eq!(Balances::free_balance(1234), initial_issuance);114			Inflation::on_initialize(1);115116			// Next inflation deposit happens when block is multiple of InflationBlockInterval117			let mut block: u32 = 2;118			let balance_before: u64 = Balances::free_balance(1234);119			while block % InflationBlockInterval::get() != 0 {120				Inflation::on_initialize(block as u64);121				block += 1;122			}123			let balance_just_before: u64 = Balances::free_balance(1234);124			assert_eq!(balance_before, balance_just_before);125126			// The block with inflation127			Inflation::on_initialize(block as u64);128			let balance_after: u64 = Balances::free_balance(1234);129			assert_eq!(balance_after - balance_just_before, Inflation::block_inflation());130		});131	}132133	#[test]134	fn inflation_in_1_year() {135		new_test_ext().execute_with(|| {136			// Total issuance = 1_000_000_000137			let initial_issuance: u64 = 1_000_000_000;138			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);139			assert_eq!(Balances::free_balance(1234), initial_issuance);140			Inflation::on_initialize(1);141			let block_inflation_year_0 = Inflation::block_inflation();142143			Inflation::on_initialize(YEAR);144			let block_inflation_year_1 = Inflation::block_inflation();145146			// Assert that year 1 inflation is less than year 0147			assert!(block_inflation_year_0 > block_inflation_year_1);148		});149	}150151	#[test]152	fn inflation_in_1_to_9_years() {153		new_test_ext().execute_with(|| {154			// Total issuance = 1_000_000_000155			let initial_issuance: u64 = 1_000_000_000;156			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);157			assert_eq!(Balances::free_balance(1234), initial_issuance);158			Inflation::on_initialize(1);159160			for year in 1..=9 {161				let block_inflation_year_before = Inflation::block_inflation();162				Inflation::on_initialize(YEAR * year);163				let block_inflation_year_after = Inflation::block_inflation();164165				// Assert that next year inflation is less than previous year inflation166				assert!(block_inflation_year_before > block_inflation_year_after);167			}168169		});170	}171172	#[test]173	fn inflation_after_year_10_is_flat() {174		new_test_ext().execute_with(|| {175			// Total issuance = 1_000_000_000176			let initial_issuance: u64 = 1_000_000_000;177			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);178			assert_eq!(Balances::free_balance(1234), initial_issuance);179			Inflation::on_initialize(YEAR * 9);180181			for year in 10..=20 {182				let block_inflation_year_before = Inflation::block_inflation();183				Inflation::on_initialize(YEAR * year);184				let block_inflation_year_after = Inflation::block_inflation();185186				// Assert that next year inflation is equal to previous year inflation187				assert_eq!(block_inflation_year_before, block_inflation_year_after);188			}189		});190	}191192	#[test]193	fn inflation_rate_by_year() {194		new_test_ext().execute_with(|| {195			let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;196197			// Inflation starts at 10% and does down by 2/3% every year until year 9 (included), 198			// then it is flat.199			let payout_by_year: [u64; 11] = [200				1000,201				933,202				867,203				800,204				733,205				667,206				600,207				533,208				467,209				400,210				400211			];212213			// For accuracy total issuance = payout0 * payouts * 10;214			let initial_issuance: u64 = payout_by_year[0] * payouts * 10;215			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);216			assert_eq!(Balances::free_balance(1234), initial_issuance);217218			for year in 0..=10 {219				// Year first block220				Inflation::on_initialize(year*YEAR);221				let mut actual_payout = Inflation::block_inflation();222				assert_eq!(actual_payout, payout_by_year[year as usize]);223224				// Year second block225				Inflation::on_initialize(year*YEAR+1);226				actual_payout = Inflation::block_inflation();227				assert_eq!(actual_payout, payout_by_year[year as usize]);228229				// Year middle block230				Inflation::on_initialize(year*YEAR + YEAR/2);231				actual_payout = Inflation::block_inflation();232				assert_eq!(actual_payout, payout_by_year[year as usize]);233234				// Year last block235				Inflation::on_initialize((year + 1)*YEAR-1);236				actual_payout = Inflation::block_inflation();237				assert_eq!(actual_payout, payout_by_year[year as usize]);238			}239		});240	}241}