git.delta.rocks / unique-network / refs/commits / 574fb6756b14

difftreelog

Convert inflation to FRAMEv2 and update

Greg Zaitsev2021-12-06parent: #7645521.patch.diff
in: master

3 files changed

modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
before · pallets/inflation/src/lib.rs
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},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;4849pub const YEAR: u32 = 5_259_600; // 6-second block50// pub 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>;7172		/// Next (relay) block when inflation is applied. This value is approximate.73		pub NextInflationBlock get(fn next_inflation_block): T::BlockNumber;7475		/// Next (relay) block when inflation is recalculated. This value is approximate.76		pub NextRecalculationBlock get(fn next_recalculation_block): T::BlockNumber;77	}78}7980decl_module! {81	pub struct Module<T: Config> for enum Call82	where83		origin: T::Origin,84	{85		const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();8687		fn on_initialize() -> Weight88		{89			let mut consumed_weight = 0;90			let mut add_weight = |reads, writes, weight| {91				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);92				consumed_weight += weight;93			};9495			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);96			let _now = T::BlockNumberProvider::current_block_number();97			let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();98			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();99			add_weight(2, 0, 5_000_000);100101			// Recalculate inflation on the first block of the year (or if it is not initialized yet)102			if _now >= next_recalculation {103				let current_year: u32 = (next_recalculation / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);104105				let one_percent = Perbill::from_percent(1);106107				if current_year <= TOTAL_YEARS_UNTIL_FLAT {108					let amount: BalanceOf<T> = Perbill::from_rational(109						block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),110						YEAR * TOTAL_YEARS_UNTIL_FLAT111					) * ( one_percent * T::Currency::total_issuance() );112					<BlockInflation<T>>::put(amount);113				}114				else {115					let amount: BalanceOf<T> = Perbill::from_rational(116						block_interval * END_INFLATION_PERCENT,117						YEAR118					) * (one_percent * T::Currency::total_issuance());119					<BlockInflation<T>>::put(amount);120				}121				<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());122123				// First time deposit124				T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());125126				// Update recalculation and inflation blocks127				<NextRecalculationBlock<T>>::set(next_recalculation + YEAR.into());128				<NextInflationBlock<T>>::set(next_recalculation + block_interval.into());129130				add_weight(7, 8, 28_300_000);131			}132133			// Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account134			else if _now >= next_inflation {135				T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();136137				// Update inflation block138				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());139140				add_weight(3, 3, 12_900_000);141			}142143			consumed_weight144		}145146	}147}
after · pallets/inflation/src/lib.rs
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)]8#![allow(9	clippy::too_many_arguments,10	clippy::unnecessary_mut_passed,11	clippy::unused_unit12)]1314mod benchmarking;15#[cfg(test)]16mod mock;17#[cfg(test)]18mod tests;1920use frame_support::{21	dispatch::{DispatchResult},22	ensure,23	traits::{Currency, Get},24};25pub use pallet::*;26use sp_runtime::{27	Perbill,28	traits::{BlockNumberProvider}29};3031use std::convert::TryInto;3233type BalanceOf<T> =34	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;3536pub const YEAR: u32 = 5_259_600; // 6-second block37// pub const YEAR: u32 = 2_629_800; // 12-second block38pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;39pub const START_INFLATION_PERCENT: u32 = 10;40pub const END_INFLATION_PERCENT: u32 = 4;4142#[frame_support::pallet]43pub mod pallet {44	use super::*;45	use frame_support::pallet_prelude::*;46	use frame_system::pallet_prelude::*;4748	#[pallet::error]49	pub enum Error<T> {50        /// Inflation has already been initialized51        AlreadyInitialized,52	}5354	#[pallet::config]55	pub trait Config: frame_system::Config {56		type Currency: Currency<Self::AccountId>;57		type TreasuryAccountId: Get<Self::AccountId>;58	59		// The block number provider60		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;6162		/// Number of blocks that pass between treasury balance updates due to inflation63		#[pallet::constant]64		type InflationBlockInterval: Get<Self::BlockNumber>;65	}6667	#[pallet::pallet]68	#[pallet::generate_store(pub(super) trait Store)]69	pub struct Pallet<T>(_);7071	/// starting year total issuance72	#[pallet::storage]73	pub type StartingYearTotalIssuance<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;7475	/// Current inflation for `InflationBlockInterval` number of blocks76	#[pallet::storage]77	pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;7879	/// Next target (relay) block when inflation will be applied80	#[pallet::storage]81	pub type NextInflationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8283	/// Next target (relay) block when inflation is recalculated84	#[pallet::storage]85	pub type NextRecalculationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8687	#[pallet::hooks]88	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {89		fn on_initialize(_: T::BlockNumber) -> Weight90		where <T as frame_system::Config>::BlockNumber: From<u32>91		{92			let mut consumed_weight = 0;93			let mut add_weight = |reads, writes, weight| {94				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);95				consumed_weight += weight;96			};9798			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);99			let current_relay_block = T::BlockNumberProvider::current_block_number();100			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();101			add_weight(1, 0, 5_000_000);102103			// Apply inflation every InflationBlockInterval blocks104			// If next_inflation == 0, this means inflation wasn't yet initialized105			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {106107				// Recalculate inflation on the first block of the year (or if it is not initialized yet)108				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation" 109				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.110				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();111				add_weight(1, 0, 0);112				if current_relay_block >= next_recalculation {113					Self::recalculate_inflation(next_recalculation);114					add_weight(0, 4, 5_000_000);115				}116117				T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();118119				// Update inflation block120				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());121122				add_weight(3, 3, 10_000_000);123			}124125			consumed_weight126		}127	}128129	#[pallet::call]130	impl<T: Config> Pallet<T> {131		/// This method sets the inflation start date. Can be only called once.132		/// Inflation start block can be backdated and will catch up. The method will create Treasury 133		/// account if it does not exist and perform the first inflation deposit.134		///135		/// # Permissions136		///137		/// * Root138		///139		/// # Arguments140		///141		/// * inflation_start_relay_block: The relay chain block at which inflation should start142		#[pallet::weight(0)]143		pub fn start_inflation(origin: OriginFor<T>, inflation_start_relay_block: T::BlockNumber) -> DispatchResult 144		where <T as frame_system::Config>::BlockNumber: From<u32> {145			ensure_root(origin)?;146147			// Ensure inflation has not been yet initialized148			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();149			ensure!(next_inflation == 0u32.into(), Error::<T>::AlreadyInitialized);150151			// Recalculate inflation. This can be backdated and will catch up.152			Self::recalculate_inflation(inflation_start_relay_block);153			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);154			<NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());155156			// First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else157			T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());158159			Ok(())160		}161	}162}163164impl<T: Config> Pallet<T> {165	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {166167		let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);168		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);169170		let one_percent = Perbill::from_percent(1);171172		if current_year <= TOTAL_YEARS_UNTIL_FLAT {173			let amount: BalanceOf<T> = Perbill::from_rational(174				block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),175				YEAR * TOTAL_YEARS_UNTIL_FLAT176			) * ( one_percent * T::Currency::total_issuance() );177			<BlockInflation<T>>::put(amount);178		}179		else {180			let amount: BalanceOf<T> = Perbill::from_rational(181				block_interval * END_INFLATION_PERCENT,182				YEAR183			) * (one_percent * T::Currency::total_issuance());184			<BlockInflation<T>>::put(amount);185		}186		<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());187188		// Update recalculation and inflation blocks189		<NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());190	}191}
modifiedruntime/Cargo.tomldiffbeforeafterboth
--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -377,7 +377,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' }
 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" }
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -14,6 +14,9 @@
   it('First year inflation is 10%', async () => {
     await usingApi(async (api) => {
 
+      // Start inflation on relay block 1
+      await api.tx.inflation.start_inflation(1);
+
       const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
       const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
       const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();