difftreelog
Convert inflation to FRAMEv2 and update
in: master
3 files changed
pallets/inflation/src/lib.rsdiffbeforeafterboth6#![recursion_limit = "1024"]6#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]7#![cfg_attr(not(feature = "std"), no_std)]89#[cfg(feature = "std")]8#![allow(10pub use std::*;9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]111312pub use serde::{Serialize, Deserialize};14mod benchmarking;1314#[cfg(feature = "runtime-benchmarks")]15#[cfg(test)]15mod benchmarking;16mod mock;1617#[cfg(test)]17#[cfg(test)]18mod tests;18mod tests;191920pub use frame_support::{20use frame_support::{21 construct_runtime, decl_module, decl_storage, ensure,21 dispatch::{DispatchResult},22 ensure,22 traits::{23 traits::{Currency, Get},23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};24};3334// #[cfg(feature = "runtime-benchmarks")]35pub use frame_support::dispatch::DispatchResult;25pub use pallet::*;3637use sp_runtime::{26use sp_runtime::{38 Perbill,27 Perbill,39 traits::{BlockNumberProvider},28 traits::{BlockNumberProvider}40};29};3041use sp_std::convert::TryInto;31use std::convert::TryInto;423243use frame_system::{self as system};4445/// The balance type of this module.46pub type BalanceOf<T> =33type BalanceOf<T> =47 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;34 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;483549pub const YEAR: u32 = 5_259_600; // 6-second block36pub const YEAR: u32 = 5_259_600; // 6-second block52pub const START_INFLATION_PERCENT: u32 = 10;39pub const START_INFLATION_PERCENT: u32 = 10;53pub const END_INFLATION_PERCENT: u32 = 4;40pub const END_INFLATION_PERCENT: u32 = 4;544142#[frame_support::pallet]43pub mod pallet {44 use super::*;45 use frame_support::pallet_prelude::*;46 use frame_system::pallet_prelude::*;4748 #[pallet::error]49 pub enum Error<T> {50 /// Inflation has already been initialized51 AlreadyInitialized,52 }5354 #[pallet::config]55pub trait Config: system::Config {55 pub trait Config: frame_system::Config {56 type Currency: Currency<Self::AccountId>;56 type Currency: Currency<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;58 59 // The block number provider58 type InflationBlockInterval: Get<Self::BlockNumber>;60 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;596160 // The block number provider62 /// Number of blocks that pass between treasury balance updates due to inflation63 #[pallet::constant]61 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;64 type InflationBlockInterval: Get<Self::BlockNumber>;62}65 }636664decl_storage! {67 #[pallet::pallet]68 #[pallet::generate_store(pub(super) trait Store)]65 trait Store for Module<T: Config> as Inflation {69 pub struct Pallet<T>(_);7066 /// starting year total issuance71 /// starting year total issuance72 #[pallet::storage]67 pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;73 pub type StartingYearTotalIssuance<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;687469 /// Current block inflation75 /// Current inflation for `InflationBlockInterval` number of blocks76 #[pallet::storage]70 pub BlockInflation get(fn block_inflation): BalanceOf<T>;77 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;717872 /// Next (relay) block when inflation is applied. This value is approximate.79 /// Next target (relay) block when inflation will be applied80 #[pallet::storage]73 pub NextInflationBlock get(fn next_inflation_block): T::BlockNumber;81 pub type NextInflationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;748275 /// Next (relay) block when inflation is recalculated. This value is approximate.83 /// Next target (relay) block when inflation is recalculated84 #[pallet::storage]85 pub type NextRecalculationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8687 #[pallet::hooks]88 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {89 fn on_initialize(_: T::BlockNumber) -> Weight90 where <T as frame_system::Config>::BlockNumber: From<u32>91 {92 let mut consumed_weight = 0;93 let mut add_weight = |reads, writes, weight| {94 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);95 consumed_weight += weight;96 };9798 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);99 let current_relay_block = T::BlockNumberProvider::current_block_number();100 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();101 add_weight(1, 0, 5_000_000);102103 // Apply inflation every InflationBlockInterval blocks104 // If next_inflation == 0, this means inflation wasn't yet initialized105 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {106107 // Recalculate inflation on the first block of the year (or if it is not initialized yet)108 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation" 109 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.76 pub NextRecalculationBlock get(fn next_recalculation_block): T::BlockNumber;110 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();77 }111 add_weight(1, 0, 0);78}112 if current_relay_block >= next_recalculation {79113 Self::recalculate_inflation(next_recalculation);80decl_module! {114 add_weight(0, 4, 5_000_000);115 }116117 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();118119 // Update inflation block120 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());121122 add_weight(3, 3, 10_000_000);123 }124125 consumed_weight126 }127 }128129 #[pallet::call]130 impl<T: Config> Pallet<T> {131 /// This method sets the inflation start date. Can be only called once.132 /// Inflation start block can be backdated and will catch up. The method will create Treasury 133 /// account if it does not exist and perform the first inflation deposit.134 ///135 /// # Permissions136 ///137 /// * Root138 ///139 /// # Arguments140 ///141 /// * inflation_start_relay_block: The relay chain block at which inflation should start142 #[pallet::weight(0)]143 pub fn start_inflation(origin: OriginFor<T>, inflation_start_relay_block: T::BlockNumber) -> DispatchResult 144 where <T as frame_system::Config>::BlockNumber: From<u32> {145 ensure_root(origin)?;146147 // Ensure inflation has not been yet initialized148 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();149 ensure!(next_inflation == 0u32.into(), Error::<T>::AlreadyInitialized);150151 // Recalculate inflation. This can be backdated and will catch up.152 Self::recalculate_inflation(inflation_start_relay_block);153 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);154 <NextInflationBlock<T>>::set(inflation_start_relay_block + block_interval.into());155156 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else157 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());158159 Ok(())160 }161 }162}16381 pub struct Module<T: Config> for enum Call164impl<T: Config> Pallet<T> {82 where83 origin: T::Origin,84 {85 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();165 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {8616687 fn on_initialize() -> Weight88 {89 let mut consumed_weight = 0;167 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);90 let mut add_weight = |reads, writes, weight| {91 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);92 consumed_weight += weight;93 };9495 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);96 let _now = T::BlockNumberProvider::current_block_number();168 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);97 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();98 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();99 add_weight(2, 0, 5_000_000);100101 // Recalculate inflation on the first block of the year (or if it is not initialized yet)102 if _now >= next_recalculation {103 let current_year: u32 = (next_recalculation / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);104169105 let one_percent = Perbill::from_percent(1);170 let one_percent = Perbill::from_percent(1);106171107 if current_year <= TOTAL_YEARS_UNTIL_FLAT {172 if current_year <= TOTAL_YEARS_UNTIL_FLAT {108 let amount: BalanceOf<T> = Perbill::from_rational(173 let amount: BalanceOf<T> = Perbill::from_rational(109 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),174 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),110 YEAR * TOTAL_YEARS_UNTIL_FLAT175 YEAR * TOTAL_YEARS_UNTIL_FLAT111 ) * ( one_percent * T::Currency::total_issuance() );176 ) * ( one_percent * T::Currency::total_issuance() );112 <BlockInflation<T>>::put(amount);177 <BlockInflation<T>>::put(amount);113 }178 }114 else {179 else {115 let amount: BalanceOf<T> = Perbill::from_rational(180 let amount: BalanceOf<T> = Perbill::from_rational(116 block_interval * END_INFLATION_PERCENT,181 block_interval * END_INFLATION_PERCENT,117 YEAR182 YEAR118 ) * (one_percent * T::Currency::total_issuance());183 ) * (one_percent * T::Currency::total_issuance());119 <BlockInflation<T>>::put(amount);184 <BlockInflation<T>>::put(amount);120 }185 }121 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());186 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());122123 // First time deposit124 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());125187126 // Update recalculation and inflation blocks188 // Update recalculation and inflation blocks127 <NextRecalculationBlock<T>>::set(next_recalculation + YEAR.into());189 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());128 <NextInflationBlock<T>>::set(next_recalculation + block_interval.into());129130 add_weight(7, 8, 28_300_000);131 }132133 // Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account134 else if _now >= next_inflation {135 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();136137 // Update inflation block138 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());139140 add_weight(3, 3, 12_900_000);141 }142143 consumed_weight144 }190 }145146 }191}147}148runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -377,7 +377,7 @@
pallet-unique = { path = '../pallets/unique', default-features = false }
up-rpc = { path = "../primitives/rpc", default-features = false }
up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
-pallet-inflation = { path = '../pallets/inflation', default-features = false }
+pallet-inflation = { path = '../pallets/inflation' }
up-data-structs = { path = '../primitives/data-structs', default-features = false }
pallet-common = { default-features = false, path = "../pallets/common" }
pallet-fungible = { default-features = false, path = "../pallets/fungible" }
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -14,6 +14,9 @@
it('First year inflation is 10%', async () => {
await usingApi(async (api) => {
+ // Start inflation on relay block 1
+ await api.tx.inflation.start_inflation(1);
+
const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();