difftreelog
Format inflation
in: master
1 file changed
pallets/inflation/src/lib.rsdiffbeforeafterboth1//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>;46 47 // 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> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;6263 /// Current inflation for `InflationBlockInterval` number of blocks64 #[pallet::storage]65 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;6667 /// Next target (relay) block when inflation will be applied68 #[pallet::storage]69 pub type NextInflationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;7071 /// Next target (relay) block when inflation is recalculated72 #[pallet::storage]73 pub type NextRecalculationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;7475 #[pallet::hooks]76 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {77 fn on_initialize(_: T::BlockNumber) -> Weight78 where <T as frame_system::Config>::BlockNumber: From<u32>79 {80 let mut consumed_weight = 0;81 let mut add_weight = |reads, writes, weight| {82 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);83 consumed_weight += weight;84 };8586 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);87 let current_relay_block = T::BlockNumberProvider::current_block_number();88 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();89 add_weight(1, 0, 5_000_000);9091 // Apply inflation every InflationBlockInterval blocks92 // If next_inflation == 0, this means inflation wasn't yet initialized93 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {9495 // Recalculate inflation on the first block of the year (or if it is not initialized yet)96 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation" 97 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.98 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();99 add_weight(1, 0, 0);100 if current_relay_block >= next_recalculation {101 Self::recalculate_inflation(next_recalculation);102 add_weight(0, 4, 5_000_000);103 }104105 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();106107 // Update inflation block108 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());109110 add_weight(3, 3, 10_000_000);111 }112113 consumed_weight114 }115 }116117 #[pallet::call]118 impl<T: Config> Pallet<T> {119 /// This method sets the inflation start date. Can be only called once.120 /// Inflation start block can be backdated and will catch up. The method will create Treasury 121 /// account if it does not exist and perform the first inflation deposit.122 ///123 /// # Permissions124 ///125 /// * Root126 ///127 /// # Arguments128 ///129 /// * inflation_start_relay_block: The relay chain block at which inflation should start130 #[pallet::weight(0)]131 pub fn start_inflation(origin: OriginFor<T>, inflation_start_relay_block: T::BlockNumber) -> DispatchResult 132 where <T as frame_system::Config>::BlockNumber: From<u32> {133 ensure_root(origin)?;134135 // Start inflation if it has not been yet initialized136 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();137 if next_inflation == 0u32.into() {138 // Recalculate inflation. This can be backdated and will catch up.139 Self::recalculate_inflation(inflation_start_relay_block);140 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);141 <NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());142143 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else144 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());145 }146147 Ok(())148 }149 }150}151152impl<T: Config> Pallet<T> {153 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {154155 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);156 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);157158 let one_percent = Perbill::from_percent(1);159160 if current_year <= TOTAL_YEARS_UNTIL_FLAT {161 let amount: BalanceOf<T> = Perbill::from_rational(162 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),163 YEAR * TOTAL_YEARS_UNTIL_FLAT164 ) * ( one_percent * T::Currency::total_issuance() );165 <BlockInflation<T>>::put(amount);166 }167 else {168 let amount: BalanceOf<T> = Perbill::from_rational(169 block_interval * END_INFLATION_PERCENT,170 YEAR171 ) * (one_percent * T::Currency::total_issuance());172 <BlockInflation<T>>::put(amount);173 }174 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());175176 // Update recalculation and inflation blocks177 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());178 }179}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 #[pallet::hooks]79 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {80 fn on_initialize(_: T::BlockNumber) -> Weight81 where82 <T as frame_system::Config>::BlockNumber: From<u32>,83 {84 let mut consumed_weight = 0;85 let mut add_weight = |reads, writes, weight| {86 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);87 consumed_weight += weight;88 };8990 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);91 let current_relay_block = T::BlockNumberProvider::current_block_number();92 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();93 add_weight(1, 0, 5_000_000);9495 // Apply inflation every InflationBlockInterval blocks96 // If next_inflation == 0, this means inflation wasn't yet initialized97 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {98 // Recalculate inflation on the first block of the year (or if it is not initialized yet)99 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"100 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.101 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();102 add_weight(1, 0, 0);103 if current_relay_block >= next_recalculation {104 Self::recalculate_inflation(next_recalculation);105 add_weight(0, 4, 5_000_000);106 }107108 T::Currency::deposit_into_existing(109 &T::TreasuryAccountId::get(),110 <BlockInflation<T>>::get(),111 )112 .ok();113114 // Update inflation block115 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());116117 add_weight(3, 3, 10_000_000);118 }119120 consumed_weight121 }122 }123124 #[pallet::call]125 impl<T: Config> Pallet<T> {126 /// This method sets the inflation start date. Can be only called once.127 /// Inflation start block can be backdated and will catch up. The method will create Treasury128 /// account if it does not exist and perform the first inflation deposit.129 ///130 /// # Permissions131 ///132 /// * Root133 ///134 /// # Arguments135 ///136 /// * inflation_start_relay_block: The relay chain block at which inflation should start137 #[pallet::weight(0)]138 pub fn start_inflation(139 origin: OriginFor<T>,140 inflation_start_relay_block: T::BlockNumber,141 ) -> DispatchResult142 where143 <T as frame_system::Config>::BlockNumber: From<u32>,144 {145 ensure_root(origin)?;146147 // Start inflation if it has not been yet initialized148 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();149 if next_inflation == 0u32.into() {150 // Recalculate inflation. This can be backdated and will catch up.151 Self::recalculate_inflation(inflation_start_relay_block);152 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);153 <NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());154155 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else156 T::Currency::deposit_creating(157 &T::TreasuryAccountId::get(),158 <BlockInflation<T>>::get(),159 );160 }161162 Ok(())163 }164 }165}166167impl<T: Config> Pallet<T> {168 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {169 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR))170 .try_into()171 .unwrap_or(0);172 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);173174 let one_percent = Perbill::from_percent(1);175176 if current_year <= TOTAL_YEARS_UNTIL_FLAT {177 let amount: BalanceOf<T> = Perbill::from_rational(178 block_interval179 * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT180 - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),181 YEAR * TOTAL_YEARS_UNTIL_FLAT,182 ) * (one_percent * T::Currency::total_issuance());183 <BlockInflation<T>>::put(amount);184 } else {185 let amount: BalanceOf<T> =186 Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)187 * (one_percent * T::Currency::total_issuance());188 <BlockInflation<T>>::put(amount);189 }190 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());191192 // Update recalculation and inflation blocks193 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());194 }195}