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

difftreelog

source

pallets/inflation/src/lib.rs6.6 KiBsourcehistory
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 = "runtime-benchmarks")]10mod benchmarking;1112#[cfg(test)]13mod tests;1415use frame_support::{16	dispatch::{DispatchResult},17	traits::{Currency, Get},18};19pub use pallet::*;20use sp_runtime::{21	Perbill,22	traits::{BlockNumberProvider},23};2425use sp_std::convert::TryInto;2627type BalanceOf<T> =28	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;2930pub const YEAR: u32 = 5_259_600; // 6-second block31								 // pub const YEAR: u32 = 2_629_800; // 12-second block32pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;33pub const START_INFLATION_PERCENT: u32 = 10;34pub const END_INFLATION_PERCENT: u32 = 4;3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::pallet_prelude::*;40	use frame_system::pallet_prelude::*;4142	#[pallet::config]43	pub trait Config: frame_system::Config {44		type Currency: Currency<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]52		type InflationBlockInterval: Get<Self::BlockNumber>;53	}5455	#[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	/// Relay block when inflation has started79	#[pallet::storage]80	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8182	#[pallet::hooks]83	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {84		fn on_initialize(_: T::BlockNumber) -> Weight85		where86			<T as frame_system::Config>::BlockNumber: From<u32>,87		{88			let mut consumed_weight = 0;89			let mut add_weight = |reads, writes, weight| {90				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);91				consumed_weight += weight;92			};9394			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);95			let current_relay_block = T::BlockNumberProvider::current_block_number();96			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();97			add_weight(1, 0, 5_000_000);9899			// Apply inflation every InflationBlockInterval blocks100			// If next_inflation == 0, this means inflation wasn't yet initialized101			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {102				// Recalculate inflation on the first block of the year (or if it is not initialized yet)103				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"104				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.105				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();106				add_weight(1, 0, 0);107				if current_relay_block >= next_recalculation {108					Self::recalculate_inflation(next_recalculation);109					add_weight(0, 4, 5_000_000);110				}111112				T::Currency::deposit_into_existing(113					&T::TreasuryAccountId::get(),114					<BlockInflation<T>>::get(),115				)116				.ok();117118				// Update inflation block119				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());120121				add_weight(3, 3, 10_000_000);122			}123124			consumed_weight125		}126	}127128	#[pallet::call]129	impl<T: Config> Pallet<T> {130		/// This method sets the inflation start date. Can be only called once.131		/// Inflation start block can be backdated and will catch up. The method will create Treasury132		/// account if it does not exist and perform the first inflation deposit.133		///134		/// # Permissions135		///136		/// * Root137		///138		/// # Arguments139		///140		/// * inflation_start_relay_block: The relay chain block at which inflation should start141		#[pallet::weight(0)]142		pub fn start_inflation(143			origin: OriginFor<T>,144			inflation_start_relay_block: T::BlockNumber,145		) -> DispatchResult146		where147			<T as frame_system::Config>::BlockNumber: From<u32>,148		{149			ensure_root(origin)?;150151			// Start inflation if it has not been yet initialized152			if <StartBlock<T>>::get() == 0u32.into() {153				// Set inflation global start block154				<StartBlock<T>>::set(inflation_start_relay_block);155156				// Recalculate inflation. This can be backdated and will catch up.157				Self::recalculate_inflation(inflation_start_relay_block);158				let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);159				<NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());160161				// First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else162				T::Currency::deposit_creating(163					&T::TreasuryAccountId::get(),164					<BlockInflation<T>>::get(),165				);166			}167168			Ok(())169		}170	}171}172173impl<T: Config> Pallet<T> {174	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {175		let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())176			/ T::BlockNumber::from(YEAR))177		.try_into()178		.unwrap_or(0);179		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);180181		let one_percent = Perbill::from_percent(1);182183		if current_year <= TOTAL_YEARS_UNTIL_FLAT {184			let amount: BalanceOf<T> = Perbill::from_rational(185				block_interval186					* (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT187						- current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),188				YEAR * TOTAL_YEARS_UNTIL_FLAT,189			) * (one_percent * T::Currency::total_issuance());190			<BlockInflation<T>>::put(amount);191		} else {192			let amount: BalanceOf<T> =193				Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)194					* (one_percent * T::Currency::total_issuance());195			<BlockInflation<T>>::put(amount);196		}197		<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());198199		// Update recalculation and inflation blocks200		<NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());201	}202}