difftreelog
feat speedup inflation pallet
in: master
4 files changed
js-packages/tests/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth--- a/js-packages/tests/creditFeesToTreasury.seqtest.ts
+++ b/js-packages/tests/creditFeesToTreasury.seqtest.ts
@@ -33,7 +33,7 @@
const blockInterval = inflationBlockInterval.toNumber();
const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
const currentBlock = head.number.toNumber();
- if(currentBlock % blockInterval < blockInterval - 10) {
+ if(currentBlock % blockInterval < blockInterval - 2) {
unsubscribe();
resolve();
} else {
js-packages/tests/inflation.seqtest.tsdiffbeforeafterboth--- a/js-packages/tests/inflation.seqtest.ts
+++ b/js-packages/tests/inflation.seqtest.ts
@@ -17,6 +17,8 @@
import type {IKeyringPair} from '@polkadot/types/types';
import {expect, itSub, usingPlaygrounds} from './util/index.js';
+const TREASURY = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';
+
// todo:playgrounds requires sudo, look into on the later stage
describe('integration test: Inflation', () => {
let superuser: IKeyringPair;
@@ -55,4 +57,23 @@
expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
});
+
+ itSub('Inflation happens after inflation block interval', async ({helper}) => {
+ const api = helper.getApi();
+ const blockInterval = await api.consts.inflation.inflationBlockInterval.toNumber();
+
+ const relayBlock = (await api.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
+ await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [helper.constructApiCall('api.tx.inflation.startInflation', [relayBlock])]);
+ const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
+ const startBlock = (relayBlock + blockInterval) - (relayBlock % blockInterval) + 1;
+
+ await helper.wait.forRelayBlockNumber(startBlock);
+
+ const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
+
+ await helper.wait.forRelayBlockNumber(startBlock + blockInterval);
+
+ const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);
+ expect(Number(treasuryBalanceAfter)).to.be.eqls(Number(treasuryBalanceBefore + blockInflation));
+ });
});
pallets/inflation/src/tests.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#![cfg(test)]18#![allow(clippy::from_over_into)]19use frame_support::{20 assert_ok, parameter_types,21 traits::{22 fungible::{Balanced, Inspect},23 tokens::Precision,24 ConstU32, Everything, OnInitialize,25 },26 weights::Weight,27};28use frame_system::RawOrigin;29use sp_core::H256;30use sp_runtime::{31 traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},32 BuildStorage,33};3435use crate as pallet_inflation;3637type Block = frame_system::mocking::MockBlockU32<Test>;3839// 6-second blocks40// const YEAR: u32 = 2_629_800; // 12-second blocks41// Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = FIRST_YEAR_BLOCK_INFLATION42const YEAR: u32 = 5_259_600;43const FIRST_YEAR_BLOCK_INFLATION: u64 = 1901;4445parameter_types! {46 pub const ExistentialDeposit: u64 = 1;47 pub const MaxLocks: u32 = 50;48}4950impl pallet_balances::Config for Test {51 type AccountStore = System;52 type Balance = u64;53 type DustRemoval = ();54 type RuntimeEvent = ();55 type ExistentialDeposit = ExistentialDeposit;56 type WeightInfo = ();57 type MaxLocks = MaxLocks;58 type MaxReserves = ();59 type ReserveIdentifier = ();60 type FreezeIdentifier = ();61 type MaxHolds = ();62 type MaxFreezes = ();63 type RuntimeHoldReason = RuntimeHoldReason;64}6566frame_support::construct_runtime!(67 pub enum Test {68 Balances: pallet_balances,69 System: frame_system,70 Inflation: pallet_inflation,71 }72);7374parameter_types! {75 pub const BlockHashCount: u32 = 250;76 pub BlockWeights: frame_system::limits::BlockWeights =77 frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 0));78 pub const SS58Prefix: u8 = 42;79}8081impl frame_system::Config for Test {82 type BaseCallFilter = Everything;83 type Block = Block;84 type BlockWeights = ();85 type BlockLength = ();86 type DbWeight = ();87 type RuntimeOrigin = RuntimeOrigin;88 type RuntimeCall = RuntimeCall;89 type Nonce = u64;90 type Hash = H256;91 type Hashing = BlakeTwo256;92 type AccountId = u64;93 type Lookup = IdentityLookup<Self::AccountId>;94 type RuntimeEvent = ();95 type BlockHashCount = BlockHashCount;96 type Version = ();97 type PalletInfo = PalletInfo;98 type AccountData = pallet_balances::AccountData<u64>;99 type OnNewAccount = ();100 type OnKilledAccount = ();101 type SystemWeightInfo = ();102 type SS58Prefix = SS58Prefix;103 type OnSetCode = ();104 type MaxConsumers = ConstU32<16>;105}106107parameter_types! {108 pub TreasuryAccountId: u64 = 1234;109 pub const InflationBlockInterval: u32 = 10; // every time per how many blocks inflation is applied110 pub static MockBlockNumberProvider: u32 = 0;111}112113impl BlockNumberProvider for MockBlockNumberProvider {114 type BlockNumber = u32;115116 fn current_block_number() -> Self::BlockNumber {117 Self::get()118 }119}120121impl pallet_inflation::Config for Test {122 type Currency = Balances;123 type TreasuryAccountId = TreasuryAccountId;124 type InflationBlockInterval = InflationBlockInterval;125 type OnInitializeBlockNumberProvider = MockBlockNumberProvider;126}127128pub fn new_test_ext() -> sp_io::TestExternalities {129 <frame_system::GenesisConfig<Test>>::default()130 .build_storage()131 .unwrap()132 .into()133}134135macro_rules! block_inflation {136 // Block inflation doesn't have any argumets137 () => {138 // Return BlockInflation state variable current value139 <pallet_inflation::BlockInflation<Test>>::get()140 };141}142143#[test]144fn uninitialized_inflation() {145 new_test_ext().execute_with(|| {146 let initial_issuance: u64 = 1_000_000_000;147 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);148 assert_eq!(Balances::free_balance(1234), initial_issuance);149150 // BlockInflation should be set after inflation is started151 // first inflation deposit should be equal to BlockInflation152 MockBlockNumberProvider::set(1);153154 assert_eq!(block_inflation!(), 0);155 });156}157158#[test]159fn inflation_works() {160 new_test_ext().execute_with(|| {161 // Total issuance = 1_000_000_000162 let initial_issuance: u64 = 1_000_000_000;163 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);164 assert_eq!(Balances::free_balance(1234), initial_issuance);165166 // BlockInflation should be set after inflation is started167 // first inflation deposit should be equal to BlockInflation168 MockBlockNumberProvider::set(1);169170 // Start inflation as sudo171 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));172 assert_eq!(block_inflation!(), FIRST_YEAR_BLOCK_INFLATION);173 assert_eq!(174 Balances::free_balance(1234) - initial_issuance,175 block_inflation!()176 );177178 // Trigger inflation179 MockBlockNumberProvider::set(102);180 Inflation::on_initialize(0);181 assert_eq!(182 Balances::free_balance(1234) - initial_issuance,183 2 * block_inflation!()184 );185 });186}187188#[test]189fn inflation_second_deposit() {190 new_test_ext().execute_with(|| {191 // Total issuance = 1_000_000_000192 let initial_issuance = 1_000_000_000;193 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);194 assert_eq!(Balances::free_balance(1234), initial_issuance);195 MockBlockNumberProvider::set(1);196197 // Start inflation as sudo198 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));199200 // Next inflation deposit happens when block is greater then or equal to NextInflationBlock201 let mut block = 2;202 let balance_before = Balances::free_balance(1234);203 while block < <pallet_inflation::NextInflationBlock<Test>>::get() {204 MockBlockNumberProvider::set(block);205 Inflation::on_initialize(0);206 block += 1;207 }208 let balance_just_before = Balances::free_balance(1234);209 assert_eq!(balance_before, balance_just_before);210211 // The block with inflation212 MockBlockNumberProvider::set(block);213 Inflation::on_initialize(0);214 let balance_after = Balances::free_balance(1234);215 assert_eq!(balance_after - balance_just_before, block_inflation!());216 });217}218219#[test]220fn inflation_in_1_year() {221 new_test_ext().execute_with(|| {222 // Total issuance = 1_000_000_000223 let initial_issuance: u64 = 1_000_000_000;224 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);225 assert_eq!(Balances::free_balance(1234), initial_issuance);226 MockBlockNumberProvider::set(1);227228 // Start inflation as sudo229 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));230231 // Go through all the block inflations for year 1,232 // total issuance will be updated accordingly233 // Inflation is set to start in block 1, so first iteration is block 101234 for block in (101..YEAR).step_by(100) {235 MockBlockNumberProvider::set(block);236 Inflation::on_initialize(0);237 }238 assert_eq!(239 initial_issuance + (FIRST_YEAR_BLOCK_INFLATION * ((YEAR as u64) / 100)),240 <Balances as Inspect<_>>::total_issuance()241 );242243 MockBlockNumberProvider::set(YEAR + 1);244 Inflation::on_initialize(0);245 let block_inflation_year_2 = block_inflation!();246 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR == 1951247 let expecter_year_2_inflation: u64 = (initial_issuance248 + FIRST_YEAR_BLOCK_INFLATION * (YEAR as u64) / 100)249 * 933 * 100 / (10000 * (YEAR as u64));250 assert_eq!(block_inflation_year_2 / 10, expecter_year_2_inflation / 10); // divide by 10 for approx. equality251 });252}253254#[test]255fn inflation_start_large_kusama_block() {256 new_test_ext().execute_with(|| {257 // Total issuance = 1_000_000_000258 let initial_issuance = 1_000_000_000;259 let start_block = 10457457;260 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);261 assert_eq!(Balances::free_balance(1234), initial_issuance);262 MockBlockNumberProvider::set(start_block);263264 // Start inflation as sudo265 assert_ok!(Inflation::start_inflation(266 RawOrigin::Root.into(),267 start_block268 ));269270 // Go through all the block inflations for year 1,271 // total issuance will be updated accordingly272 // Inflation is set to start in block 1, so first iteration is block 101273 for block in (101..YEAR).step_by(100) {274 MockBlockNumberProvider::set(start_block + block);275 Inflation::on_initialize(0);276 }277 assert_eq!(278 initial_issuance + (FIRST_YEAR_BLOCK_INFLATION * ((YEAR as u64) / 100)),279 <Balances as Inspect<_>>::total_issuance()280 );281282 MockBlockNumberProvider::set(start_block + YEAR + 1);283 Inflation::on_initialize(0);284 let block_inflation_year_2 = block_inflation!();285 // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR == 1951286 let expecter_year_2_inflation: u64 = (initial_issuance287 + FIRST_YEAR_BLOCK_INFLATION * (YEAR as u64) / 100)288 * 933 * 100 / (10000 * (YEAR as u64));289 assert_eq!(block_inflation_year_2 / 10, expecter_year_2_inflation / 10); // divide by 10 for approx. equality290 });291}292293#[test]294fn inflation_after_year_10_is_flat() {295 new_test_ext().execute_with(|| {296 // Total issuance = 1_000_000_000297 let initial_issuance: u64 = 1_000_000_000;298 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);299 assert_eq!(Balances::free_balance(1234), initial_issuance);300 MockBlockNumberProvider::set(YEAR * 9 + 1);301302 // Start inflation as sudo303 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));304305 // Let inflation catch up306 for _year in 1..=9 {307 Inflation::on_initialize(0);308 }309310 for year in 10..=20 {311 let block_inflation_year_before = block_inflation!();312 MockBlockNumberProvider::set(YEAR * year + 1);313 Inflation::on_initialize(0);314 let block_inflation_year_after = block_inflation!();315316 // Assert that next year inflation is equal to previous year inflation317 assert_eq!(block_inflation_year_before, block_inflation_year_after);318 }319 });320}321322#[test]323fn inflation_rate_by_year() {324 new_test_ext().execute_with(|| {325 let payouts = (YEAR / InflationBlockInterval::get()) as u64;326327 // Inflation starts at 10% and does down by 2/3% every year until year 9 (included),328 // then it is flat.329 let payout_by_year: [u64; 11] = [1000, 933, 867, 800, 733, 667, 600, 533, 467, 400, 400];330331 // For accuracy total issuance = payout0 * payouts * 10;332 let initial_issuance = payout_by_year[0] * payouts * 10;333 let _ = <Balances as Balanced<_>>::deposit(&1234, initial_issuance, Precision::Exact);334 assert_eq!(Balances::free_balance(1234), initial_issuance);335336 // Start inflation as sudo337 assert_ok!(Inflation::start_inflation(RawOrigin::Root.into(), 1));338339 for year in 0..=10 {340 // Year first block341 MockBlockNumberProvider::set(YEAR * year + 1);342 Inflation::on_initialize(0);343 let mut actual_payout = block_inflation!();344 assert_eq!(actual_payout, payout_by_year[year as usize]);345346 // Year second block347 MockBlockNumberProvider::set(YEAR * year + 2);348 Inflation::on_initialize(0);349 actual_payout = block_inflation!();350 assert_eq!(actual_payout, payout_by_year[year as usize]);351352 // Year middle block353 MockBlockNumberProvider::set(year * YEAR + YEAR / 2);354 Inflation::on_initialize(0);355 actual_payout = block_inflation!();356 assert_eq!(actual_payout, payout_by_year[year as usize]);357358 // Year last block359 MockBlockNumberProvider::set((year + 1) * YEAR);360 Inflation::on_initialize(0);361 actual_payout = block_inflation!();362 assert_eq!(actual_payout, payout_by_year[year as usize]);363 }364 });365}runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -102,7 +102,7 @@
}
parameter_types! {
- pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
+ pub const InflationBlockInterval: BlockNumber = 10; // every time per how many blocks inflation is applied
}
/// Pallet-inflation needs block number in on_initialize, where there is no `validation_data` exists yet