git.delta.rocks / unique-network / refs/commits / 574fb6756b14

difftreelog

Convert inflation to FRAMEv2 and update

Greg Zaitsev2021-12-06parent: #7645521.patch.diff
in: master

3 files changed

modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
6#![recursion_limit = "1024"]6#![recursion_limit = "1024"]
7#![cfg_attr(not(feature = "std"), no_std)]7#![cfg_attr(not(feature = "std"), no_std)]
8
9#[cfg(feature = "std")]8#![allow(
10pub use std::*;9 clippy::too_many_arguments,
10 clippy::unnecessary_mut_passed,
11 clippy::unused_unit
12)]
1113
12pub use serde::{Serialize, Deserialize};14mod benchmarking;
13
14#[cfg(feature = "runtime-benchmarks")]15#[cfg(test)]
15mod benchmarking;16mod mock;
16
17#[cfg(test)]17#[cfg(test)]
18mod tests;18mod tests;
1919
20pub 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};
33
34// #[cfg(feature = "runtime-benchmarks")]
35pub use frame_support::dispatch::DispatchResult;25pub use pallet::*;
36
37use sp_runtime::{26use sp_runtime::{
38 Perbill,27 Perbill,
39 traits::{BlockNumberProvider},28 traits::{BlockNumberProvider}
40};29};
30
41use sp_std::convert::TryInto;31use std::convert::TryInto;
4232
43use frame_system::{self as system};
44
45/// 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;
4835
49pub const YEAR: u32 = 5_259_600; // 6-second block36pub const YEAR: u32 = 5_259_600; // 6-second block
52pub 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;
5441
42#[frame_support::pallet]
43pub mod pallet {
44 use super::*;
45 use frame_support::pallet_prelude::*;
46 use frame_system::pallet_prelude::*;
47
48 #[pallet::error]
49 pub enum Error<T> {
50 /// Inflation has already been initialized
51 AlreadyInitialized,
52 }
53
54 #[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 provider
58 type InflationBlockInterval: Get<Self::BlockNumber>;60 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
5961
60 // The block number provider62 /// Number of blocks that pass between treasury balance updates due to inflation
63 #[pallet::constant]
61 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;64 type InflationBlockInterval: Get<Self::BlockNumber>;
62}65 }
6366
64decl_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>(_);
70
66 /// starting year total issuance71 /// starting year total issuance
72 #[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>;
6874
69 /// Current block inflation75 /// Current inflation for `InflationBlockInterval` number of blocks
76 #[pallet::storage]
70 pub BlockInflation get(fn block_inflation): BalanceOf<T>;77 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;
7178
72 /// Next (relay) block when inflation is applied. This value is approximate.79 /// Next target (relay) block when inflation will be applied
80 #[pallet::storage]
73 pub NextInflationBlock get(fn next_inflation_block): T::BlockNumber;81 pub type NextInflationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
7482
75 /// Next (relay) block when inflation is recalculated. This value is approximate.83 /// Next target (relay) block when inflation is recalculated
84 #[pallet::storage]
85 pub type NextRecalculationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
86
87 #[pallet::hooks]
88 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
89 fn on_initialize(_: T::BlockNumber) -> Weight
90 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 };
97
98 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);
102
103 // Apply inflation every InflationBlockInterval blocks
104 // If next_inflation == 0, this means inflation wasn't yet initialized
105 if (next_inflation != 0u32.into()) && (current_relay_block >= next_inflation) {
106
107 // 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 }
116
117 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();
118
119 // Update inflation block
120 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());
121
122 add_weight(3, 3, 10_000_000);
123 }
124
125 consumed_weight
126 }
127 }
128
129 #[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 /// # Permissions
136 ///
137 /// * Root
138 ///
139 /// # Arguments
140 ///
141 /// * inflation_start_relay_block: The relay chain block at which inflation should start
142 #[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)?;
146
147 // Ensure inflation has not been yet initialized
148 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
149 ensure!(next_inflation == 0u32.into(), Error::<T>::AlreadyInitialized);
150
151 // 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());
155
156 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else
157 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
158
159 Ok(())
160 }
161 }
162}
163
81 pub struct Module<T: Config> for enum Call164impl<T: Config> Pallet<T> {
82 where
83 origin: T::Origin,
84 {
85 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();165 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
86166
87 fn on_initialize() -> Weight
88 {
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 };
94
95 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);
100
101 // 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);
104169
105 let one_percent = Perbill::from_percent(1);170 let one_percent = Perbill::from_percent(1);
106171
107 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_FLAT
111 ) * ( 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 YEAR
118 ) * (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());
122
123 // First time deposit
124 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
125187
126 // Update recalculation and inflation blocks188 // Update recalculation and inflation blocks
127 <NextRecalculationBlock<T>>::set(next_recalculation + YEAR.into());189 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());
128 <NextInflationBlock<T>>::set(next_recalculation + block_interval.into());
129
130 add_weight(7, 8, 28_300_000);
131 }
132
133 // Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account
134 else if _now >= next_inflation {
135 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();
136
137 // Update inflation block
138 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());
139
140 add_weight(3, 3, 12_900_000);
141 }
142
143 consumed_weight
144 }190 }
145
146 }191}
147}
148
modifiedruntime/Cargo.tomldiffbeforeafterboth
377pallet-unique = { path = '../pallets/unique', default-features = false }377pallet-unique = { path = '../pallets/unique', default-features = false }
378up-rpc = { path = "../primitives/rpc", default-features = false }378up-rpc = { path = "../primitives/rpc", default-features = false }
379up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }379up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
380pallet-inflation = { path = '../pallets/inflation', default-features = false }380pallet-inflation = { path = '../pallets/inflation' }
381up-data-structs = { path = '../primitives/data-structs', default-features = false }381up-data-structs = { path = '../primitives/data-structs', default-features = false }
382pallet-common = { default-features = false, path = "../pallets/common" }382pallet-common = { default-features = false, path = "../pallets/common" }
383pallet-fungible = { default-features = false, path = "../pallets/fungible" }383pallet-fungible = { default-features = false, path = "../pallets/fungible" }
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
14 it('First year inflation is 10%', async () => {14 it('First year inflation is 10%', async () => {
15 await usingApi(async (api) => {15 await usingApi(async (api) => {
16
17 // Start inflation on relay block 1
18 await api.tx.inflation.start_inflation(1);
1619
17 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();20 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
18 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();21 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();