git.delta.rocks / unique-network / refs/commits / 9a601ff5844d

difftreelog

source

pallets/inflation/src/lib.rs7.8 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::{Currency, Get},43};44pub use pallet::*;45use sp_runtime::{46	Perbill,47	traits::{BlockNumberProvider},48};4950use sp_std::convert::TryInto;5152type BalanceOf<T> =53	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;5455pub const YEAR: u32 = 5_259_600; // 6-second block56								 // pub const YEAR: u32 = 2_629_800; // 12-second block57pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;58pub const START_INFLATION_PERCENT: u32 = 10;59pub const END_INFLATION_PERCENT: u32 = 4;6061#[frame_support::pallet]62pub mod pallet {63	use super::*;64	use frame_support::pallet_prelude::*;65	use frame_system::pallet_prelude::*;6667	#[pallet::config]68	pub trait Config: frame_system::Config {69		type Currency: Currency<Self::AccountId>;70		type TreasuryAccountId: Get<Self::AccountId>;7172		// The block number provider73		type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;7475		/// Number of blocks that pass between treasury balance updates due to inflation76		#[pallet::constant]77		type InflationBlockInterval: Get<Self::BlockNumber>;78	}7980	#[pallet::pallet]81	#[pallet::generate_store(pub(super) trait Store)]82	pub struct Pallet<T>(_);8384	/// starting year total issuance85	#[pallet::storage]86	pub type StartingYearTotalIssuance<T: Config> =87		StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;8889	/// Current inflation for `InflationBlockInterval` number of blocks90	#[pallet::storage]91	pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;9293	/// Next target (relay) block when inflation will be applied94	#[pallet::storage]95	pub type NextInflationBlock<T: Config> =96		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;9798	/// Next target (relay) block when inflation is recalculated99	#[pallet::storage]100	pub type NextRecalculationBlock<T: Config> =101		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;102103	/// Relay block when inflation has started104	#[pallet::storage]105	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;106107	#[pallet::hooks]108	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {109		fn on_initialize(_: T::BlockNumber) -> Weight110		where111			<T as frame_system::Config>::BlockNumber: From<u32>,112		{113			let mut consumed_weight = Weight::zero();114			let mut add_weight = |reads, writes, weight| {115				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);116				consumed_weight += weight;117			};118119			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);120			let current_relay_block = T::BlockNumberProvider::current_block_number();121			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();122			add_weight(1, 0, Weight::from_ref_time(5_000_000));123124			// Apply inflation every InflationBlockInterval blocks125			// If next_inflation == 0, this means inflation wasn't yet initialized126			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {127				// Recalculate inflation on the first block of the year (or if it is not initialized yet)128				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"129				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.130				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();131				add_weight(1, 0, Weight::zero());132				if current_relay_block >= next_recalculation {133					Self::recalculate_inflation(next_recalculation);134					add_weight(0, 4, Weight::from_ref_time(5_000_000));135				}136137				T::Currency::deposit_into_existing(138					&T::TreasuryAccountId::get(),139					<BlockInflation<T>>::get(),140				)141				.ok();142143				// Update inflation block144				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());145146				add_weight(3, 3, Weight::from_ref_time(10_000_000));147			}148149			consumed_weight150		}151	}152153	#[pallet::call]154	impl<T: Config> Pallet<T> {155		/// This method sets the inflation start date. Can be only called once.156		/// Inflation start block can be backdated and will catch up. The method will create Treasury157		/// account if it does not exist and perform the first inflation deposit.158		///159		/// # Permissions160		///161		/// * Root162		///163		/// # Arguments164		///165		/// * inflation_start_relay_block: The relay chain block at which inflation should start166		#[pallet::weight(0)]167		pub fn start_inflation(168			origin: OriginFor<T>,169			inflation_start_relay_block: T::BlockNumber,170		) -> DispatchResult171		where172			<T as frame_system::Config>::BlockNumber: From<u32>,173		{174			ensure_root(origin)?;175176			// Start inflation if it has not been yet initialized177			if <StartBlock<T>>::get() == 0u32.into() {178				// Set inflation global start block179				<StartBlock<T>>::set(inflation_start_relay_block);180181				// Recalculate inflation. This can be backdated and will catch up.182				Self::recalculate_inflation(inflation_start_relay_block);183				let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);184				<NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());185186				// First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else187				T::Currency::deposit_creating(188					&T::TreasuryAccountId::get(),189					<BlockInflation<T>>::get(),190				);191			}192193			Ok(())194		}195	}196}197198impl<T: Config> Pallet<T> {199	pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {200		let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())201			/ T::BlockNumber::from(YEAR))202		.try_into()203		.unwrap_or(0);204		let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);205206		let one_percent = Perbill::from_percent(1);207208		if current_year <= TOTAL_YEARS_UNTIL_FLAT {209			let amount: BalanceOf<T> = Perbill::from_rational(210				block_interval211					* (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT212						- current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),213				YEAR * TOTAL_YEARS_UNTIL_FLAT,214			) * (one_percent * T::Currency::total_issuance());215			<BlockInflation<T>>::put(amount);216		} else {217			let amount: BalanceOf<T> =218				Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)219					* (one_percent * T::Currency::total_issuance());220			<BlockInflation<T>>::put(amount);221		}222		<StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());223224		// Update recalculation and inflation blocks225		<NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());226	}227}