difftreelog
Inflation pallet documentation
in: master
1 file changed
pallets/inflation/src/lib.rsdiffbeforeafterboth1// 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// #![recursion_limit = "1024"]18#![cfg_attr(not(feature = "std"), no_std)]1920#[cfg(feature = "runtime-benchmarks")]21mod benchmarking;2223#[cfg(test)]24mod tests;2526use frame_support::{27 dispatch::{DispatchResult},28 traits::{Currency, Get},29};30pub use pallet::*;31use sp_runtime::{32 Perbill,33 traits::{BlockNumberProvider},34};3536use sp_std::convert::TryInto;3738type BalanceOf<T> =39 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;4041pub const YEAR: u32 = 5_259_600; // 6-second block42 // pub const YEAR: u32 = 2_629_800; // 12-second block43pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;44pub const START_INFLATION_PERCENT: u32 = 10;45pub const END_INFLATION_PERCENT: u32 = 4;4647#[frame_support::pallet]48pub mod pallet {49 use super::*;50 use frame_support::pallet_prelude::*;51 use frame_system::pallet_prelude::*;5253 #[pallet::config]54 pub trait Config: frame_system::Config {55 type Currency: Currency<Self::AccountId>;56 type TreasuryAccountId: Get<Self::AccountId>;5758 // The block number provider59 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;6061 /// Number of blocks that pass between treasury balance updates due to inflation62 #[pallet::constant]63 type InflationBlockInterval: Get<Self::BlockNumber>;64 }6566 #[pallet::pallet]67 #[pallet::generate_store(pub(super) trait Store)]68 pub struct Pallet<T>(_);6970 /// starting year total issuance71 #[pallet::storage]72 pub type StartingYearTotalIssuance<T: Config> =73 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> =82 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8384 /// Next target (relay) block when inflation is recalculated85 #[pallet::storage]86 pub type NextRecalculationBlock<T: Config> =87 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8889 /// Relay block when inflation has started90 #[pallet::storage]91 pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;9293 #[pallet::hooks]94 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {95 fn on_initialize(_: T::BlockNumber) -> Weight96 where97 <T as frame_system::Config>::BlockNumber: From<u32>,98 {99 let mut consumed_weight = 0;100 let mut add_weight = |reads, writes, weight| {101 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);102 consumed_weight += weight;103 };104105 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);106 let current_relay_block = T::BlockNumberProvider::current_block_number();107 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();108 add_weight(1, 0, 5_000_000);109110 // Apply inflation every InflationBlockInterval blocks111 // If next_inflation == 0, this means inflation wasn't yet initialized112 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {113 // Recalculate inflation on the first block of the year (or if it is not initialized yet)114 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"115 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.116 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();117 add_weight(1, 0, 0);118 if current_relay_block >= next_recalculation {119 Self::recalculate_inflation(next_recalculation);120 add_weight(0, 4, 5_000_000);121 }122123 T::Currency::deposit_into_existing(124 &T::TreasuryAccountId::get(),125 <BlockInflation<T>>::get(),126 )127 .ok();128129 // Update inflation block130 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());131132 add_weight(3, 3, 10_000_000);133 }134135 consumed_weight136 }137 }138139 #[pallet::call]140 impl<T: Config> Pallet<T> {141 /// This method sets the inflation start date. Can be only called once.142 /// Inflation start block can be backdated and will catch up. The method will create Treasury143 /// account if it does not exist and perform the first inflation deposit.144 ///145 /// # Permissions146 ///147 /// * Root148 ///149 /// # Arguments150 ///151 /// * inflation_start_relay_block: The relay chain block at which inflation should start152 #[pallet::weight(0)]153 pub fn start_inflation(154 origin: OriginFor<T>,155 inflation_start_relay_block: T::BlockNumber,156 ) -> DispatchResult157 where158 <T as frame_system::Config>::BlockNumber: From<u32>,159 {160 ensure_root(origin)?;161162 // Start inflation if it has not been yet initialized163 if <StartBlock<T>>::get() == 0u32.into() {164 // Set inflation global start block165 <StartBlock<T>>::set(inflation_start_relay_block);166167 // Recalculate inflation. This can be backdated and will catch up.168 Self::recalculate_inflation(inflation_start_relay_block);169 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);170 <NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());171172 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else173 T::Currency::deposit_creating(174 &T::TreasuryAccountId::get(),175 <BlockInflation<T>>::get(),176 );177 }178179 Ok(())180 }181 }182}183184impl<T: Config> Pallet<T> {185 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {186 let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())187 / T::BlockNumber::from(YEAR))188 .try_into()189 .unwrap_or(0);190 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);191192 let one_percent = Perbill::from_percent(1);193194 if current_year <= TOTAL_YEARS_UNTIL_FLAT {195 let amount: BalanceOf<T> = Perbill::from_rational(196 block_interval197 * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT198 - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),199 YEAR * TOTAL_YEARS_UNTIL_FLAT,200 ) * (one_percent * T::Currency::total_issuance());201 <BlockInflation<T>>::put(amount);202 } else {203 let amount: BalanceOf<T> =204 Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)205 * (one_percent * T::Currency::total_issuance());206 <BlockInflation<T>>::put(amount);207 }208 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());209210 // Update recalculation and inflation blocks211 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());212 }213}