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

difftreelog

source

pallets/inflation/src/lib.rs8.1 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Inflation18//!19//! The inflation pallet is designed to increase the number of tokens at certain intervals.20//! With each iteration, increases the `total_issuance` value for the native token.21//! Executing an `on_initialize` hook at the beginning of each block, causing inflation to begin.22//!23//! ## Interface24//!25//! ### Dispatchable Functions26//!27//! * `start_inflation` - This method sets the inflation start date. Can be only called once.28//! Inflation start block can be backdated and will catch up. The method will create Treasury29//! account if it does not exist and perform the first inflation deposit.3031// #![recursion_limit = "1024"]32#![cfg_attr(not(feature = "std"), no_std)]3334#[cfg(feature = "runtime-benchmarks")]35mod benchmarking;3637#[cfg(test)]38mod tests;3940use frame_support::{41	dispatch::{DispatchResult},42	traits::{43		fungible::{Balanced, Inspect, Mutate},44		Get,45		tokens::Precision,46	},47};48pub use pallet::*;49use sp_runtime::{Perbill, traits::BlockNumberProvider};5051use sp_std::convert::TryInto;5253type BalanceOf<T> =54	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;5556pub const YEAR: u32 = 5_259_600; // 6-second block57								 // pub const YEAR: u32 = 2_629_800; // 12-second block58pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;59pub const START_INFLATION_PERCENT: u32 = 10;60pub const END_INFLATION_PERCENT: u32 = 4;6162#[frame_support::pallet]63pub mod pallet {64	use super::*;65	use frame_support::pallet_prelude::*;66	use frame_system::pallet_prelude::*;6768	#[pallet::config]69	pub trait Config: frame_system::Config {70		type Currency: Balanced<Self::AccountId>71			+ Inspect<Self::AccountId>72			+ Mutate<Self::AccountId>;73		type TreasuryAccountId: Get<Self::AccountId>;7475		// The block number provider76		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;7778		/// Number of blocks that pass between treasury balance updates due to inflation79		#[pallet::constant]80		type InflationBlockInterval: Get<Self::BlockNumber>;81	}8283	#[pallet::pallet]84	pub struct Pallet<T>(_);8586	/// starting year total issuance87	#[pallet::storage]88	pub type StartingYearTotalIssuance<T: Config> =89		StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;9091	/// Current inflation for `InflationBlockInterval` number of blocks92	#[pallet::storage]93	pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;9495	/// Next target (relay) block when inflation will be applied96	#[pallet::storage]97	pub type NextInflationBlock<T: Config> =98		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;99100	/// Next target (relay) block when inflation is recalculated101	#[pallet::storage]102	pub type NextRecalculationBlock<T: Config> =103		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;104105	/// Relay block when inflation has started106	#[pallet::storage]107	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;108109	#[pallet::hooks]110	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {111		fn on_initialize(_: T::BlockNumber) -> Weight112		where113			<T as frame_system::Config>::BlockNumber: From<u32>,114		{115			let mut consumed_weight = Weight::zero();116			let mut add_weight = |reads, writes, weight| {117				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);118				consumed_weight += weight;119			};120121			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);122			let current_relay_block = T::BlockNumberProvider::current_block_number();123			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();124			add_weight(1, 0, Weight::from_parts(5_000_000, 0));125126			// Apply inflation every InflationBlockInterval blocks127			// If next_inflation == 0, this means inflation wasn't yet initialized128			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {129				// Recalculate inflation on the first block of the year (or if it is not initialized yet)130				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"131				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.132				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();133				add_weight(1, 0, Weight::zero());134				if current_relay_block >= next_recalculation {135					Self::recalculate_inflation(next_recalculation);136					add_weight(0, 4, Weight::from_parts(5_000_000, 0));137				}138139				T::Currency::mint_into(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get())140					.ok();141142				// Update inflation block143				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());144145				add_weight(3, 3, Weight::from_parts(10_000_000, 0));146			}147148			consumed_weight149		}150	}151152	#[pallet::call]153	impl<T: Config> Pallet<T> {154		/// This method sets the inflation start date. Can be only called once.155		/// Inflation start block can be backdated and will catch up. The method will create Treasury156		/// account if it does not exist and perform the first inflation deposit.157		///158		/// # Permissions159		///160		/// * Root161		///162		/// # Arguments163		///164		/// * inflation_start_relay_block: The relay chain block at which inflation should start165		#[pallet::call_index(0)]166		// Constant weights are deprecated,167		// but in this case writing benchmark is not feasible, `start_inflation` call168		// might be even moved to GenesisConfig169		#[pallet::weight(Weight::from_parts(0, 0))]170		pub fn start_inflation(171			origin: OriginFor<T>,172			inflation_start_relay_block: T::BlockNumber,173		) -> DispatchResult174		where175			<T as frame_system::Config>::BlockNumber: From<u32>,176		{177			ensure_root(origin)?;178179			// Start inflation if it has not been yet initialized180			if <StartBlock<T>>::get() == 0u32.into() {181				// Set inflation global start block182				<StartBlock<T>>::set(inflation_start_relay_block);183184				// Recalculate inflation. This can be backdated and will catch up.185				Self::recalculate_inflation(inflation_start_relay_block);186				let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);187				<NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());188189				// First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else190				let _ = T::Currency::deposit(191					&T::TreasuryAccountId::get(),192					<BlockInflation<T>>::get(),193					Precision::Exact,194				)?;195			}196197			Ok(())198		}199	}200}201202impl<T: Config> Pallet<T> {203	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {204		let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())205			/ T::BlockNumber::from(YEAR))206		.try_into()207		.unwrap_or(0);208		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);209210		let one_percent = Perbill::from_percent(1);211212		if current_year <= TOTAL_YEARS_UNTIL_FLAT {213			let amount: BalanceOf<T> = Perbill::from_rational(214				block_interval215					* (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT216						- current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),217				YEAR * TOTAL_YEARS_UNTIL_FLAT,218			) * (one_percent * T::Currency::total_issuance());219			<BlockInflation<T>>::put(amount);220		} else {221			let amount: BalanceOf<T> =222				Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)223					* (one_percent * T::Currency::total_issuance());224			<BlockInflation<T>>::put(amount);225		}226		<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());227228		// Update recalculation and inflation blocks229		<NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());230	}231}