git.delta.rocks / unique-network / refs/commits / 008833a7ebae

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	pub struct Pallet<T>(_);8283	/// starting year total issuance84	#[pallet::storage]85	pub type StartingYearTotalIssuance<T: Config> =86		StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;8788	/// Current inflation for `InflationBlockInterval` number of blocks89	#[pallet::storage]90	pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;9192	/// Next target (relay) block when inflation will be applied93	#[pallet::storage]94	pub type NextInflationBlock<T: Config> =95		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;9697	/// Next target (relay) block when inflation is recalculated98	#[pallet::storage]99	pub type NextRecalculationBlock<T: Config> =100		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;101102	/// Relay block when inflation has started103	#[pallet::storage]104	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;105106	#[pallet::hooks]107	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {108		fn on_initialize(_: T::BlockNumber) -> Weight109		where110			<T as frame_system::Config>::BlockNumber: From<u32>,111		{112			let mut consumed_weight = Weight::zero();113			let mut add_weight = |reads, writes, weight| {114				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);115				consumed_weight += weight;116			};117118			let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);119			let current_relay_block = T::BlockNumberProvider::current_block_number();120			let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();121			add_weight(1, 0, Weight::from_ref_time(5_000_000));122123			// Apply inflation every InflationBlockInterval blocks124			// If next_inflation == 0, this means inflation wasn't yet initialized125			if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {126				// Recalculate inflation on the first block of the year (or if it is not initialized yet)127				// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"128				// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.129				let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();130				add_weight(1, 0, Weight::zero());131				if current_relay_block >= next_recalculation {132					Self::recalculate_inflation(next_recalculation);133					add_weight(0, 4, Weight::from_ref_time(5_000_000));134				}135136				T::Currency::deposit_into_existing(137					&T::TreasuryAccountId::get(),138					<BlockInflation<T>>::get(),139				)140				.ok();141142				// Update inflation block143				<NextInflationBlock<T>>::set(next_inflation + block_interval.into());144145				add_weight(3, 3, Weight::from_ref_time(10_000_000));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		#[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}