git.delta.rocks / unique-network / refs/commits / 44c855833903

difftreelog

Merge pull request #255 from UniqueNetwork/feature/CORE-247

kozyrevdev2021-12-09parents: #6388bd8 #f94b311.patch.diff
in: master
Inflation pallet block provider added. Setted up to relay chain.

8 files changed

modifiedCargo.lockdiffbeforeafterboth
11679 "pallet-evm-migration",11679 "pallet-evm-migration",
11680 "pallet-evm-transaction-payment",11680 "pallet-evm-transaction-payment",
11681 "pallet-fungible",11681 "pallet-fungible",
11682 "pallet-inflation",
11682 "pallet-nonfungible",11683 "pallet-nonfungible",
11683 "pallet-randomness-collective-flip",11684 "pallet-randomness-collective-flip",
11684 "pallet-refungible",11685 "pallet-refungible",
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
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")]
10pub use std::*;
11
12pub use serde::{Serialize, Deserialize};
138
14#[cfg(feature = "runtime-benchmarks")]9#[cfg(feature = "runtime-benchmarks")]
15mod benchmarking;10mod benchmarking;
1611
17#[cfg(test)]12#[cfg(test)]
18mod tests;13mod tests;
1914
20pub use frame_support::{15use frame_support::{
21 construct_runtime, decl_module, decl_storage, ensure,16 dispatch::{DispatchResult},
22 traits::{17 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};18};
33
34// #[cfg(feature = "runtime-benchmarks")]
35pub use frame_support::dispatch::DispatchResult;19pub use pallet::*;
36
37use sp_runtime::{20use sp_runtime::{
38 Perbill,21 Perbill,
39 traits::{Zero},22 traits::{BlockNumberProvider},
40};23};
24
41use sp_std::convert::TryInto;25use sp_std::convert::TryInto;
4226
43use frame_system::{self as system};
44
45/// The balance type of this module.
46pub type BalanceOf<T> =27type BalanceOf<T> =
47 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;28 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
4829
49// pub const YEAR: u32 = 5_259_600; // 6-second block
50pub const YEAR: u32 = 2_629_800; // 12-second block30pub const YEAR: u32 = 5_259_600; // 6-second block
31 // pub const YEAR: u32 = 2_629_800; // 12-second block
51pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;32pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;
52pub const START_INFLATION_PERCENT: u32 = 10;33pub const START_INFLATION_PERCENT: u32 = 10;
53pub const END_INFLATION_PERCENT: u32 = 4;34pub const END_INFLATION_PERCENT: u32 = 4;
5435
36#[frame_support::pallet]
37pub mod pallet {
38 use super::*;
39 use frame_support::pallet_prelude::*;
40 use frame_system::pallet_prelude::*;
41
42 #[pallet::config]
55pub trait Config: system::Config {43 pub trait Config: frame_system::Config {
56 type Currency: Currency<Self::AccountId>;44 type Currency: Currency<Self::AccountId>;
57 type TreasuryAccountId: Get<Self::AccountId>;45 type TreasuryAccountId: Get<Self::AccountId>;
46
47 // The block number provider
48 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
49
50 /// Number of blocks that pass between treasury balance updates due to inflation
51 #[pallet::constant]
58 type InflationBlockInterval: Get<Self::BlockNumber>;52 type InflationBlockInterval: Get<Self::BlockNumber>;
59}53 }
6054
61decl_storage! {55 #[pallet::pallet]
56 #[pallet::generate_store(pub(super) trait Store)]
57 pub struct Pallet<T>(_);
58
59 /// starting year total issuance
60 #[pallet::storage]
61 pub type StartingYearTotalIssuance<T: Config> =
62 StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;
63
64 /// Current inflation for `InflationBlockInterval` number of blocks
65 #[pallet::storage]
66 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;
67
68 /// Next target (relay) block when inflation will be applied
69 #[pallet::storage]
70 pub type NextInflationBlock<T: Config> =
71 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
72
73 /// Next target (relay) block when inflation is recalculated
74 #[pallet::storage]
75 pub type NextRecalculationBlock<T: Config> =
76 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
77
78 #[pallet::hooks]
62 trait Store for Module<T: Config> as Inflation {79 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
63 /// starting year total issuance80 fn on_initialize(_: T::BlockNumber) -> Weight
81 where
82 <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 };
89
64 pub StartingYearTotalIssuance get(fn starting_year_total_issuance): BalanceOf<T>;90 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
6591 let current_relay_block = T::BlockNumberProvider::current_block_number();
66 /// Current block inflation92 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
93 add_weight(1, 0, 5_000_000);
94
95 // Apply inflation every InflationBlockInterval blocks
96 // If next_inflation == 0, this means inflation wasn't yet initialized
97 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 }
107
108 T::Currency::deposit_into_existing(
109 &T::TreasuryAccountId::get(),
67 pub BlockInflation get(fn block_inflation): BalanceOf<T>;110 <BlockInflation<T>>::get(),
68 }111 )
69}112 .ok();
70113
71decl_module! {114 // Update inflation block
115 <NextInflationBlock<T>>::set(next_inflation + block_interval.into());
116
117 add_weight(3, 3, 10_000_000);
118 }
119
120 consumed_weight
121 }
122 }
123
124 #[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 Treasury
128 /// account if it does not exist and perform the first inflation deposit.
129 ///
130 /// # Permissions
131 ///
132 /// * Root
133 ///
134 /// # Arguments
135 ///
136 /// * inflation_start_relay_block: The relay chain block at which inflation should start
137 #[pallet::weight(0)]
138 pub fn start_inflation(
139 origin: OriginFor<T>,
140 inflation_start_relay_block: T::BlockNumber,
141 ) -> DispatchResult
142 where
143 <T as frame_system::Config>::BlockNumber: From<u32>,
144 {
145 ensure_root(origin)?;
146
147 // Start inflation if it has not been yet initialized
148 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());
154
155 // First time deposit - create Treasury account so that we can call deposit_into_existing everywhere else
156 T::Currency::deposit_creating(
157 &T::TreasuryAccountId::get(),
158 <BlockInflation<T>>::get(),
159 );
160 }
161
162 Ok(())
163 }
164 }
165}
166
72 pub struct Module<T: Config> for enum Call167impl<T: Config> Pallet<T> {
73 where
74 origin: T::Origin,
75 {
76 const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();
77
78 fn on_initialize(now: T::BlockNumber) -> Weight168 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
79 {
80 let mut consumed_weight = 0;169 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR))
81 let mut add_weight = |reads, writes, weight| {
82 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
83 consumed_weight += weight;
84 };
85
86 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
87
88 // TODO: Rewrite inflation to use block timestamp instead of block number
89 // let _now = <timestamp::Module<T>>::get();
90
91 // Recalculate inflation on the first block of the year (or if it is not initialized yet)
92 if (now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {170 .try_into()
171 .unwrap_or(0);
93 let current_year: u32 = (now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);172 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
94173
95 let one_percent = Perbill::from_percent(1);174 let one_percent = Perbill::from_percent(1);
96175
97 if current_year <= TOTAL_YEARS_UNTIL_FLAT {176 if current_year <= TOTAL_YEARS_UNTIL_FLAT {
98 let amount: BalanceOf<T> = Perbill::from_rational(177 let amount: BalanceOf<T> = Perbill::from_rational(
99 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),178 block_interval
179 * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT
180 - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),
100 YEAR * TOTAL_YEARS_UNTIL_FLAT181 YEAR * TOTAL_YEARS_UNTIL_FLAT,
101 ) * ( one_percent * T::Currency::total_issuance() );182 ) * (one_percent * T::Currency::total_issuance());
102 <BlockInflation<T>>::put(amount);183 <BlockInflation<T>>::put(amount);
103 }184 } else {
104 else {
105 let amount: BalanceOf<T> = Perbill::from_rational(185 let amount: BalanceOf<T> =
106 block_interval * END_INFLATION_PERCENT,186 Perbill::from_rational(block_interval * END_INFLATION_PERCENT, YEAR)
107 YEAR
108 ) * (one_percent * T::Currency::total_issuance());187 * (one_percent * T::Currency::total_issuance());
109 <BlockInflation<T>>::put(amount);188 <BlockInflation<T>>::put(amount);
110 }189 }
111 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());190 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());
112191
113 // First time deposit192 // Update recalculation and inflation blocks
114 T::Currency::deposit_creating(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get());
115
116 add_weight(7, 6, 28_300_000);
117 }
118
119 // Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account
120 else if (now % T::BlockNumber::from(block_interval)).is_zero() {193 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());
121 T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();
122
123 add_weight(3, 2, 12_900_000);
124 }
125
126 consumed_weight
127 }194 }
128
129 }195}
130}
131196
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
3use crate as pallet_inflation;3use crate as pallet_inflation;
44
5use frame_support::{5use frame_support::{
6 assert_ok, parameter_types,
6 traits::{Currency},7 traits::{Currency, OnInitialize, Everything},
7 parameter_types,
8};8};
9use frame_support::{9use frame_system::RawOrigin;
10 traits::{OnInitialize, Everything},
11};
12use sp_core::H256;10use sp_core::H256;
13use sp_runtime::{11use sp_runtime::{
14 traits::{BlakeTwo256, IdentityLookup},12 traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
15 testing::Header,13 testing::Header,
16};14};
1715
18type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;16type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
19type Block = frame_system::mocking::MockBlock<Test>;17type Block = frame_system::mocking::MockBlock<Test>;
2018
21const YEAR: u64 = 2_629_800;19const YEAR: u64 = 5_259_600; // 6-second blocks
20 // const YEAR: u64 = 2_629_800; // 12-second blocks
21 // Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = FIRST_YEAR_BLOCK_INFLATION
22const FIRST_YEAR_BLOCK_INFLATION: u64 = 1901;
2223
23parameter_types! {24parameter_types! {
24 pub const ExistentialDeposit: u64 = 1;25 pub const ExistentialDeposit: u64 = 1;
85parameter_types! {86parameter_types! {
86 pub TreasuryAccountId: u64 = 1234;87 pub TreasuryAccountId: u64 = 1234;
87 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied88 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
89 pub static MockBlockNumberProvider: u64 = 0;
88}90}
91
92impl BlockNumberProvider for MockBlockNumberProvider {
93 type BlockNumber = u64;
94
95 fn current_block_number() -> Self::BlockNumber {
96 Self::get()
97 }
98}
8999
90impl pallet_inflation::Config for Test {100impl pallet_inflation::Config for Test {
91 type Currency = Balances;101 type Currency = Balances;
92 type TreasuryAccountId = TreasuryAccountId;102 type TreasuryAccountId = TreasuryAccountId;
93 type InflationBlockInterval = InflationBlockInterval;103 type InflationBlockInterval = InflationBlockInterval;
104 type BlockNumberProvider = MockBlockNumberProvider;
94}105}
95106
96pub fn new_test_ext() -> sp_io::TestExternalities {107pub fn new_test_ext() -> sp_io::TestExternalities {
100 .into()111 .into()
101}112}
113
114macro_rules! block_inflation {
115 // Block inflation doesn't have any argumets
116 () => {
117 // Return BlockInflation state variable current value
118 <pallet_inflation::BlockInflation<Test>>::get()
119 };
120}
121
122#[test]
123fn uninitialized_inflation() {
124 new_test_ext().execute_with(|| {
125 let initial_issuance: u64 = 1_000_000_000;
126 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
127 assert_eq!(Balances::free_balance(1234), initial_issuance);
128
129 // BlockInflation should be set after inflation is started
130 // first inflation deposit should be equal to BlockInflation
131 MockBlockNumberProvider::set(1);
132
133 assert_eq!(block_inflation!(), 0);
134 });
135}
102136
103#[test]137#[test]
104fn inflation_works() {138fn inflation_works() {
108 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);142 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
109 assert_eq!(Balances::free_balance(1234), initial_issuance);143 assert_eq!(Balances::free_balance(1234), initial_issuance);
110144
111 // BlockInflation should be set after 1st block and145 // BlockInflation should be set after inflation is started
112 // first inflation deposit should be equal to BlockInflation146 // first inflation deposit should be equal to BlockInflation
113 Inflation::on_initialize(1);147 MockBlockNumberProvider::set(1);
114148
115 // Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803149 // Start inflation as sudo
150 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));
151 assert_eq!(block_inflation!(), FIRST_YEAR_BLOCK_INFLATION);
116 assert_eq!(Inflation::block_inflation(), 3803);152 assert_eq!(
153 Balances::free_balance(1234) - initial_issuance,
154 block_inflation!()
155 );
156
157 // Trigger inflation
158 MockBlockNumberProvider::set(102);
159 Inflation::on_initialize(0);
117 assert_eq!(160 assert_eq!(
118 Balances::free_balance(1234) - initial_issuance,161 Balances::free_balance(1234) - initial_issuance,
119 Inflation::block_inflation()162 2 * block_inflation!()
120 );163 );
121 });164 });
122}165}
128 let initial_issuance: u64 = 1_000_000_000;171 let initial_issuance: u64 = 1_000_000_000;
129 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);172 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
130 assert_eq!(Balances::free_balance(1234), initial_issuance);173 assert_eq!(Balances::free_balance(1234), initial_issuance);
131 Inflation::on_initialize(1);174 MockBlockNumberProvider::set(1);
175
176 // Start inflation as sudo
177 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));
132178
133 // Next inflation deposit happens when block is multiple of InflationBlockInterval179 // Next inflation deposit happens when block is greater then or equal to NextInflationBlock
134 let mut block: u32 = 2;180 let mut block: u64 = 2;
135 let balance_before: u64 = Balances::free_balance(1234);181 let balance_before: u64 = Balances::free_balance(1234);
136 while block % InflationBlockInterval::get() != 0 {182 while block < <pallet_inflation::NextInflationBlock<Test>>::get() {
137 Inflation::on_initialize(block as u64);183 MockBlockNumberProvider::set(block as u64);
184 Inflation::on_initialize(0);
138 block += 1;185 block += 1;
139 }186 }
140 let balance_just_before: u64 = Balances::free_balance(1234);187 let balance_just_before: u64 = Balances::free_balance(1234);
141 assert_eq!(balance_before, balance_just_before);188 assert_eq!(balance_before, balance_just_before);
142189
143 // The block with inflation190 // The block with inflation
144 Inflation::on_initialize(block as u64);191 MockBlockNumberProvider::set(block as u64);
192 Inflation::on_initialize(0);
145 let balance_after: u64 = Balances::free_balance(1234);193 let balance_after: u64 = Balances::free_balance(1234);
146 assert_eq!(194 assert_eq!(balance_after - balance_just_before, block_inflation!());
147 balance_after - balance_just_before,
148 Inflation::block_inflation()
149 );
150 });195 });
151}196}
157 let initial_issuance: u64 = 1_000_000_000;202 let initial_issuance: u64 = 1_000_000_000;
158 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);203 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
159 assert_eq!(Balances::free_balance(1234), initial_issuance);204 assert_eq!(Balances::free_balance(1234), initial_issuance);
160 Inflation::on_initialize(1);205 MockBlockNumberProvider::set(1);
206
207 // Start inflation as sudo
208 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));
161209
162 // Go through all the block inflations for year 1,210 // Go through all the block inflations for year 1,
163 // total issuance will be updated accordingly211 // total issuance will be updated accordingly
212 // Inflation is set to start in block 1, so first iteration is block 101
164 for block in (100..YEAR).step_by(100) {213 for block in (101..YEAR).step_by(100) {
214 MockBlockNumberProvider::set(block);
165 Inflation::on_initialize(block);215 Inflation::on_initialize(0);
166 }216 }
167 assert_eq!(217 assert_eq!(
168 initial_issuance + (3803 * (YEAR / 100)),218 initial_issuance + (FIRST_YEAR_BLOCK_INFLATION * (YEAR / 100)),
169 <Balances as Currency<_>>::total_issuance()219 <Balances as Currency<_>>::total_issuance()
170 );220 );
171221
222 MockBlockNumberProvider::set(YEAR + 1);
172 Inflation::on_initialize(YEAR);223 Inflation::on_initialize(0);
173 let block_inflation_year_1 = Inflation::block_inflation();224 let block_inflation_year_2 = block_inflation!();
174 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904225 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR == 1951
226 let expecter_year_2_inflation: u64 = (initial_issuance
227 + FIRST_YEAR_BLOCK_INFLATION * YEAR / 100)
228 * 933 * 100 / (10000 * YEAR);
175 assert_eq!(block_inflation_year_1, 3904);229 assert_eq!(block_inflation_year_2 / 10, expecter_year_2_inflation / 10); // divide by 10 for approx. equality
176 });230 });
177}231}
178
179#[test]
180fn inflation_in_1_to_9_years() {
181 new_test_ext().execute_with(|| {
182 // Total issuance = 1_000_000_000
183 let initial_issuance: u64 = 1_000_000_000;
184 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
185 assert_eq!(Balances::free_balance(1234), initial_issuance);
186 Inflation::on_initialize(1);
187
188 for year in 1..=9 {
189 let block_inflation_year_before = Inflation::block_inflation();
190 Inflation::on_initialize(YEAR * year);
191 let block_inflation_year_after = Inflation::block_inflation();
192
193 // SBP M2 review: this is actually not true (not for the first few years)
194 // Assert that next year inflation is less than previous year inflation
195 assert!(block_inflation_year_before > block_inflation_year_after);
196 }
197 });
198}
199232
200#[test]233#[test]
201fn inflation_after_year_10_is_flat() {234fn inflation_after_year_10_is_flat() {
204 let initial_issuance: u64 = 1_000_000_000;237 let initial_issuance: u64 = 1_000_000_000;
205 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);238 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
206 assert_eq!(Balances::free_balance(1234), initial_issuance);239 assert_eq!(Balances::free_balance(1234), initial_issuance);
207 Inflation::on_initialize(YEAR * 9);240 MockBlockNumberProvider::set(YEAR * 9 + 1);
241
242 // Start inflation as sudo
243 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));
244
245 // Let inflation catch up
246 for _year in 1..=9 {
247 Inflation::on_initialize(0);
248 }
208249
209 for year in 10..=20 {250 for year in 10..=20 {
210 let block_inflation_year_before = Inflation::block_inflation();251 let block_inflation_year_before = block_inflation!();
211 Inflation::on_initialize(YEAR * year);252 MockBlockNumberProvider::set(YEAR * year + 1);
253 Inflation::on_initialize(0);
212 let block_inflation_year_after = Inflation::block_inflation();254 let block_inflation_year_after = block_inflation!();
213255
214 // Assert that next year inflation is equal to previous year inflation256 // Assert that next year inflation is equal to previous year inflation
215 assert_eq!(block_inflation_year_before, block_inflation_year_after);257 assert_eq!(block_inflation_year_before, block_inflation_year_after);
231 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);273 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
232 assert_eq!(Balances::free_balance(1234), initial_issuance);274 assert_eq!(Balances::free_balance(1234), initial_issuance);
275
276 // Start inflation as sudo
277 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));
233278
234 for year in 0..=10 {279 for year in 0..=10 {
235 // Year first block280 // Year first block
281 MockBlockNumberProvider::set(YEAR * year + 1);
236 Inflation::on_initialize(year * YEAR);282 Inflation::on_initialize(0);
237 let mut actual_payout = Inflation::block_inflation();283 let mut actual_payout = block_inflation!();
238 assert_eq!(actual_payout, payout_by_year[year as usize]);284 assert_eq!(actual_payout, payout_by_year[year as usize]);
239285
240 // Year second block286 // Year second block
241 Inflation::on_initialize(year * YEAR + 1);287 MockBlockNumberProvider::set(YEAR * year + 2);
288 Inflation::on_initialize(0);
242 actual_payout = Inflation::block_inflation();289 actual_payout = block_inflation!();
243 assert_eq!(actual_payout, payout_by_year[year as usize]);290 assert_eq!(actual_payout, payout_by_year[year as usize]);
244291
245 // Year middle block292 // Year middle block
246 Inflation::on_initialize(year * YEAR + YEAR / 2);293 MockBlockNumberProvider::set(year * YEAR + YEAR / 2);
294 Inflation::on_initialize(0);
247 actual_payout = Inflation::block_inflation();295 actual_payout = block_inflation!();
248 assert_eq!(actual_payout, payout_by_year[year as usize]);296 assert_eq!(actual_payout, payout_by_year[year as usize]);
249297
250 // Year last block298 // Year last block
251 Inflation::on_initialize((year + 1) * YEAR - 1);299 MockBlockNumberProvider::set((year + 1) * YEAR);
300 Inflation::on_initialize(0);
252 actual_payout = Inflation::block_inflation();301 actual_payout = block_inflation!();
253 assert_eq!(actual_payout, payout_by_year[year as usize]);302 assert_eq!(actual_payout, payout_by_year[year as usize]);
254 }303 }
255 });304 });
modifiedruntime/Cargo.tomldiffbeforeafterboth
33 'pallet-refungible/runtime-benchmarks',33 'pallet-refungible/runtime-benchmarks',
34 'pallet-nonfungible/runtime-benchmarks',34 'pallet-nonfungible/runtime-benchmarks',
35 'pallet-unique/runtime-benchmarks',35 'pallet-unique/runtime-benchmarks',
36# 'pallet-inflation/runtime-benchmarks',36 'pallet-inflation/runtime-benchmarks',
37 'pallet-xcm/runtime-benchmarks',37 'pallet-xcm/runtime-benchmarks',
38 'sp-runtime/runtime-benchmarks',38 'sp-runtime/runtime-benchmarks',
39 'xcm-builder/runtime-benchmarks',39 'xcm-builder/runtime-benchmarks',
75 'fp-self-contained/std',75 'fp-self-contained/std',
76 'parachain-info/std',76 'parachain-info/std',
77 'serde',77 'serde',
78# 'pallet-inflation/std',78 'pallet-inflation/std',
79 'pallet-common/std',79 'pallet-common/std',
80 'pallet-fungible/std',80 'pallet-fungible/std',
81 'pallet-refungible/std',81 'pallet-refungible/std',
380pallet-unique = { path = '../pallets/unique', default-features = false }380pallet-unique = { path = '../pallets/unique', default-features = false }
381up-rpc = { path = "../primitives/rpc", default-features = false }381up-rpc = { path = "../primitives/rpc", default-features = false }
382up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }382up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
383# pallet-inflation = { path = '../pallets/inflation', default-features = false }383pallet-inflation = { path = '../pallets/inflation', default-features = false }
384up-data-structs = { path = '../primitives/data-structs', default-features = false }384up-data-structs = { path = '../primitives/data-structs', default-features = false }
385pallet-common = { default-features = false, path = "../pallets/common" }385pallet-common = { default-features = false, path = "../pallets/common" }
386pallet-fungible = { default-features = false, path = "../pallets/fungible" }386pallet-fungible = { default-features = false, path = "../pallets/fungible" }
modifiedruntime/src/lib.rsdiffbeforeafterboth
785 type Event = Event;785 type Event = Event;
786 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;786 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
787}787}
788/*788
789parameter_types! {789parameter_types! {
790 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied790 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
791} */791}
792792
793/// Used for the pallet inflation793/// Used for the pallet inflation
794/* impl pallet_inflation::Config for Runtime {794impl pallet_inflation::Config for Runtime {
795 type Currency = Balances;795 type Currency = Balances;
796 type TreasuryAccountId = TreasuryAccountId;796 type TreasuryAccountId = TreasuryAccountId;
797 type InflationBlockInterval = InflationBlockInterval;797 type InflationBlockInterval = InflationBlockInterval;
798} */798 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
799}
799800
800// parameter_types! {801// parameter_types! {
801// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *802// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
882 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,883 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,
883884
884 // Unique Pallets885 // Unique Pallets
885 // Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,886 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
886 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,887 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
887 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,888 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
888 // free = 63889 // free = 63
13671368
1368 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1369 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);
1369 list_benchmark!(list, extra, pallet_unique, Unique);1370 list_benchmark!(list, extra, pallet_unique, Unique);
1370 //list_benchmark!(list, extra, pallet_inflation, Inflation);1371 list_benchmark!(list, extra, pallet_inflation, Inflation);
1371 list_benchmark!(list, extra, pallet_fungible, Fungible);1372 list_benchmark!(list, extra, pallet_fungible, Fungible);
1372 list_benchmark!(list, extra, pallet_refungible, Refungible);1373 list_benchmark!(list, extra, pallet_refungible, Refungible);
1373 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1374 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);
14011402
1402 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1403 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);
1403 add_benchmark!(params, batches, pallet_unique, Unique);1404 add_benchmark!(params, batches, pallet_unique, Unique);
1404 //add_benchmark!(params, batches, pallet_inflation, Inflation);1405 add_benchmark!(params, batches, pallet_inflation, Inflation);
1405 add_benchmark!(params, batches, pallet_fungible, Fungible);1406 add_benchmark!(params, batches, pallet_fungible, Fungible);
1406 add_benchmark!(params, batches, pallet_refungible, Refungible);1407 add_benchmark!(params, batches, pallet_refungible, Refungible);
1407 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1408 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
34// Skip the inflation block pauses if the block is close to inflation block34// Skip the inflation block pauses if the block is close to inflation block
35// until the inflation happens35// until the inflation happens
36/*eslint no-async-promise-executor: "off"*/36/*eslint no-async-promise-executor: "off"*/
37/*function skipInflationBlock(api: ApiPromise): Promise<void> {37function skipInflationBlock(api: ApiPromise): Promise<void> {
38 const promise = new Promise<void>(async (resolve) => {38 const promise = new Promise<void>(async (resolve) => {
39 const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();39 const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();
40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
41 const currentBlock = head.number.toNumber();41 const currentBlock = head.number.toNumber();
42 if (currentBlock % blockInterval < blockInterval - 10) {42 if (currentBlock % blockInterval < blockInterval - 10) {
43 unsubscribe();43 unsubscribe();
44 resolve();44 resolve();
45 } else {45 } else {
46 console.log(`Skipping inflation block, current block: ${currentBlock}`);46 console.log(`Skipping inflation block, current block: ${currentBlock}`);
47 }47 }
48 });48 });
49 });49 });
5050
51 return promise;51 return promise;
52}*/52}
5353
54describe('integration test: Fees must be credited to Treasury:', () => {54describe('integration test: Fees must be credited to Treasury:', () => {
55 before(async () => {55 before(async () => {
6161
62 it('Total issuance does not change', async () => {62 it('Total issuance does not change', async () => {
63 await usingApi(async (api) => {63 await usingApi(async (api) => {
64 //await skipInflationBlock(api);64 await skipInflationBlock(api);
65 await waitNewBlocks(api, 1);65 await waitNewBlocks(api, 1);
6666
67 const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();67 const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
8181
82 it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {82 it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {
83 await usingApi(async (api) => {83 await usingApi(async (api) => {
84 //await skipInflationBlock(api);84 await skipInflationBlock(api);
85 await waitNewBlocks(api, 1);85 await waitNewBlocks(api, 1);
8686
87 const alicePrivateKey = privateKey('//Alice');87 const alicePrivateKey = privateKey('//Alice');
125125
126 it('NFT Transactions also send fees to Treasury', async () => {126 it('NFT Transactions also send fees to Treasury', async () => {
127 await usingApi(async (api) => {127 await usingApi(async (api) => {
128 //await skipInflationBlock(api);128 await skipInflationBlock(api);
129 await waitNewBlocks(api, 1);129 await waitNewBlocks(api, 1);
130130
131 const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();131 const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();
144144
145 it('Fees are sane', async () => {145 it('Fees are sane', async () => {
146 await usingApi(async (api) => {146 await usingApi(async (api) => {
147 //await skipInflationBlock(api);147 await skipInflationBlock(api);
148 await waitNewBlocks(api, 1);148 await waitNewBlocks(api, 1);
149149
150 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();150 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
161161
162 it('NFT Transfer fee is close to 0.1 Unique', async () => {162 it('NFT Transfer fee is close to 0.1 Unique', async () => {
163 await usingApi(async (api) => {163 await usingApi(async (api) => {
164 //await skipInflationBlock(api);164 await skipInflationBlock(api);
165 await waitNewBlocks(api, 1);165 await waitNewBlocks(api, 1);
166166
167 const collectionId = await createCollectionExpectSuccess();167 const collectionId = await createCollectionExpectSuccess();
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
55
6import chai from 'chai';6import chai from 'chai';
7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';
8import {default as usingApi} from './substrate/substrate-api';8import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
9import privateKey from './substrate/privateKey';
910
10chai.use(chaiAsPromised);11chai.use(chaiAsPromised);
11const expect = chai.expect;12const expect = chai.expect;
1213
13describe.skip('integration test: Inflation', () => {14describe('integration test: Inflation', () => {
14 it('First year inflation is 10%', async () => {15 it('First year inflation is 10%', async () => {
15 await usingApi(async (api) => {16 await usingApi(async (api) => {
17
18 // Make sure non-sudo can't start inflation
19 const tx = api.tx.inflation.startInflation(1);
20 const bob = privateKey('//Bob');
21 await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
22
23 // Start inflation on relay block 1 (Alice is sudo)
24 const alice = privateKey('//Alice');
25 const sudoTx = api.tx.sudo.sudo(tx as any);
26 await submitTransactionAsync(alice, sudoTx);
1627
17 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();28 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
18 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();29 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
19 const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();30 const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();
2031
21 // const YEAR = 5259600n; // 6-second block. Blocks in one year
22 const YEAR = 2629800n; // 12-second block. Blocks in one year32 const YEAR = 5259600n; // 6-second block. Blocks in one year
33 // const YEAR = 2629800n; // 12-second block. Blocks in one year
2334
24 const totalExpectedInflation = totalIssuanceStart / 10n;35 const totalExpectedInflation = totalIssuanceStart / 10n;
25 const totalActualInflation = blockInflation * YEAR / blockInterval;36 const totalActualInflation = blockInflation * YEAR / blockInterval;
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
34 'polkadotxcm',34 'polkadotxcm',
35 'cumulusxcm',35 'cumulusxcm',
36 'dmpqueue',36 'dmpqueue',
37 //'inflation',37 'inflation',
38 'unique',38 'unique',
39 'nonfungible',39 'nonfungible',
40 'refungible',40 'refungible',