difftreelog
Fix inflation build
in: master
3 files 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)]8#![allow(9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]1314mod benchmarking;15#[cfg(test)]16mod mock;17#[cfg(test)]18mod tests;1920use frame_support::{21 dispatch::{DispatchResult},22 ensure,23 traits::{Currency, Get},24};25pub use pallet::*;26use sp_runtime::{27 Perbill,28 traits::{BlockNumberProvider}29};3031use std::convert::TryInto;3233type BalanceOf<T> =34 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;3536pub const YEAR: u32 = 5_259_600; // 6-second block37// pub const YEAR: u32 = 2_629_800; // 12-second block38pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;39pub const START_INFLATION_PERCENT: u32 = 10;40pub const END_INFLATION_PERCENT: u32 = 4;4142#[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]55 pub trait Config: frame_system::Config {56 type Currency: Currency<Self::AccountId>;57 type TreasuryAccountId: Get<Self::AccountId>;58 59 // The block number provider60 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;6162 /// Number of blocks that pass between treasury balance updates due to inflation63 #[pallet::constant]64 type InflationBlockInterval: Get<Self::BlockNumber>;65 }6667 #[pallet::pallet]68 #[pallet::generate_store(pub(super) trait Store)]69 pub struct Pallet<T>(_);7071 /// starting year total issuance72 #[pallet::storage]73 pub type StartingYearTotalIssuance<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;7475 /// Current inflation for `InflationBlockInterval` number of blocks76 #[pallet::storage]77 pub type BlockInflation<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;7879 /// Next target (relay) block when inflation will be applied80 #[pallet::storage]81 pub type NextInflationBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;8283 /// 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.110 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();111 add_weight(1, 0, 0);112 if current_relay_block >= next_recalculation {113 Self::recalculate_inflation(next_recalculation);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}163164impl<T: Config> Pallet<T> {165 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {166167 let current_year: u32 = (recalculation_block / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);168 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);169170 let one_percent = Perbill::from_percent(1);171172 if current_year <= TOTAL_YEARS_UNTIL_FLAT {173 let amount: BalanceOf<T> = Perbill::from_rational(174 block_interval * (START_INFLATION_PERCENT * TOTAL_YEARS_UNTIL_FLAT - current_year * (START_INFLATION_PERCENT - END_INFLATION_PERCENT)),175 YEAR * TOTAL_YEARS_UNTIL_FLAT176 ) * ( one_percent * T::Currency::total_issuance() );177 <BlockInflation<T>>::put(amount);178 }179 else {180 let amount: BalanceOf<T> = Perbill::from_rational(181 block_interval * END_INFLATION_PERCENT,182 YEAR183 ) * (one_percent * T::Currency::total_issuance());184 <BlockInflation<T>>::put(amount);185 }186 <StartingYearTotalIssuance<T>>::set(T::Currency::total_issuance());187188 // Update recalculation and inflation blocks189 <NextRecalculationBlock<T>>::set(recalculation_block + YEAR.into());190 }191}runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -379,7 +379,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' }
+pallet-inflation = { path = '../pallets/inflation', default-features = false }
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
@@ -5,7 +5,8 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
+import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import privateKey from './substrate/privateKey';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -14,8 +15,15 @@
it('First year inflation is 10%', async () => {
await usingApi(async (api) => {
- // Start inflation on relay block 1
- await api.tx.inflation.start_inflation(1);
+ // Make sure non-sudo can't start inflation
+ const tx = api.tx.inflation.startInflation(1);
+ const bob = privateKey('//Bob');
+ await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
+
+ // Start inflation on relay block 1 (Alice is sudo)
+ const alice = privateKey('//Alice');
+ const sudoTx = api.tx.sudo.sudo(tx as any);
+ await submitTransactionAsync(alice, sudoTx);
const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();