Skip to content

Commit

Permalink
Merge branch 'main' into pallet-identity-root-extrinsics
Browse files Browse the repository at this point in the history
  • Loading branch information
rockbmb committed Nov 29, 2024
2 parents 8547326 + db4bb53 commit d28c776
Show file tree
Hide file tree
Showing 20 changed files with 1,220 additions and 170 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## [Unreleased]

### Added

- Location conversion tests for relays and parachains ([polkadot-fellows/runtimes#487](https://github.com/polkadot-fellows/runtimes/pull/487))

Changelog for the runtimes governed by the Polkadot Fellowship.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Expand All @@ -12,6 +18,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Update foreign asset ids in Asset Hub Polkadot and Asset Hub Kusama from v3 to v4 locations ([polkadot-fellows/runtimes#472](https://github.com/polkadot-fellows/runtimes/pull/472))
- Lower Parachain and Data Deposits to Encourage Experimentation on Kusama ([polkadot-fellows/runtimes#501](https://github.com/polkadot-fellows/runtimes/pull/501))

### Fixed

- Fix `experimental_inflation_info` in Polkadot and remove unused code (https://github.com/polkadot-fellows/runtimes/pull/497)

## [1.3.3] 01.10.2024

### Changed
Expand Down
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions relay/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod apis {
/// Both fields should be treated as best-effort, given that the inflation rate might not be
/// fully predict-able.
#[derive(scale_info::TypeInfo, codec::Encode, codec::Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct InflationInfo {
/// The rate of inflation estimated per annum.
pub inflation: sp_runtime::Perquintill,
Expand Down
99 changes: 99 additions & 0 deletions relay/kusama/tests/location_conversion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.

use polkadot_primitives::AccountId;
use sp_core::crypto::Ss58Codec;
use staging_kusama_runtime::xcm_config::SovereignAccountOf;
use xcm::prelude::*;
use xcm_runtime_apis::conversions::LocationToAccountHelper;

const ALICE: [u8; 32] = [1u8; 32];

#[test]
fn location_conversion_works() {
// the purpose of hardcoded values is to catch an unintended location conversion logic change.
struct TestCase {
description: &'static str,
location: Location,
expected_account_id_str: &'static str,
}

let test_cases = vec![
// DescribeTerminus
TestCase {
description: "DescribeTerminus Child",
location: Location::new(0, [Parachain(1111)]),
expected_account_id_str: "5Ec4AhP4h37t7TFsAZ4HhFq6k92usAAJDUC3ADSZ4H4Acru3",
},
// DescribePalletTerminal
TestCase {
description: "DescribePalletTerminal Child",
location: Location::new(0, [Parachain(1111), PalletInstance(50)]),
expected_account_id_str: "5FjEBrKn3STAFsZpQF4jzwxUYHNGnNgzdZqSQfTzeJ82XKp6",
},
// DescribeAccountId32Terminal
TestCase {
description: "DescribeAccountId32Terminal Child",
location: Location::new(
0,
[
Parachain(1111),
Junction::AccountId32 { network: None, id: AccountId::from(ALICE).into() },
],
),
expected_account_id_str: "5D6CDyPd9Mya81xFN3nChiKqLvUzd8zS9fwKhfCW6FtJKjS2",
},
// DescribeAccountKey20Terminal
TestCase {
description: "DescribeAccountKey20Terminal Sibling",
location: Location::new(
0,
[Parachain(1111), AccountKey20 { network: None, key: [123u8; 20] }],
),
expected_account_id_str: "5DEZsy7tsnNXB7ehLGkF8b4EUqfLQWqEzGiy2RrneC8uRNMK",
},
// DescribeTreasuryVoiceTerminal
TestCase {
description: "DescribeTreasuryVoiceTerminal Child",
location: Location::new(
0,
[Parachain(1111), Plurality { id: BodyId::Treasury, part: BodyPart::Voice }],
),
expected_account_id_str: "5GenE4vJgHvwYVcD6b4nBvH5HNY4pzpVHWoqwFpNMFT7a2oX",
},
// DescribeBodyTerminal
TestCase {
description: "DescribeBodyTerminal Child",
location: Location::new(
0,
[Parachain(1111), Plurality { id: BodyId::Unit, part: BodyPart::Voice }],
),
expected_account_id_str: "5DPgGBFTTYm1dGbtB1VWHJ3T3ScvdrskGGx6vSJZNP1WNStV",
},
];

for tc in test_cases {
let expected =
AccountId::from_string(tc.expected_account_id_str).expect("Invalid AccountId string");

let got = LocationToAccountHelper::<AccountId, SovereignAccountOf>::convert_location(
tc.location.into(),
)
.unwrap();

assert_eq!(got, expected, "{}", tc.description);
}
}
4 changes: 0 additions & 4 deletions relay/polkadot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ pallet-multisig = { workspace = true }
pallet-nomination-pools = { workspace = true }
pallet-nomination-pools-runtime-api = { workspace = true }
pallet-offences = { workspace = true }
pallet-parameters = { workspace = true }
pallet-preimage = { workspace = true }
pallet-proxy = { workspace = true }
pallet-referenda = { workspace = true }
Expand Down Expand Up @@ -168,7 +167,6 @@ std = [
"pallet-nomination-pools/std",
"pallet-offences-benchmarking?/std",
"pallet-offences/std",
"pallet-parameters/std",
"pallet-preimage/std",
"pallet-proxy/std",
"pallet-referenda/std",
Expand Down Expand Up @@ -247,7 +245,6 @@ runtime-benchmarks = [
"pallet-nomination-pools/runtime-benchmarks",
"pallet-offences-benchmarking/runtime-benchmarks",
"pallet-offences/runtime-benchmarks",
"pallet-parameters/runtime-benchmarks",
"pallet-preimage/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-referenda/runtime-benchmarks",
Expand Down Expand Up @@ -300,7 +297,6 @@ try-runtime = [
"pallet-multisig/try-runtime",
"pallet-nomination-pools/try-runtime",
"pallet-offences/try-runtime",
"pallet-parameters/try-runtime",
"pallet-preimage/try-runtime",
"pallet-proxy/try-runtime",
"pallet-referenda/try-runtime",
Expand Down
119 changes: 10 additions & 109 deletions relay/polkadot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use polkadot_runtime_common::{
traits::OnSwap,
BlockHashCount, BlockLength, CurrencyToVote, SlowAdjustingFeeUpdate,
};
use relay_common::apis::InflationInfo;

use runtime_parachains::{
assigner_coretime as parachains_assigner_coretime,
Expand Down Expand Up @@ -60,7 +61,6 @@ use frame_election_provider_support::{
};
use frame_support::{
construct_runtime,
dynamic_params::{dynamic_pallet_params, dynamic_params},
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{
Expand All @@ -85,15 +85,15 @@ use polkadot_primitives::{
GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, Moment,
NodeFeatures, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
LOWEST_PUBLIC_ID, PARACHAIN_KEY_TYPE_ID,
PARACHAIN_KEY_TYPE_ID,
};
use sp_core::{OpaqueMetadata, H256};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto,
Extrinsic as ExtrinsicT, IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion,
Saturating, Verify,
Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, RuntimeDebug,
Expand Down Expand Up @@ -619,88 +619,6 @@ impl pallet_bags_list::Config<VoterBagsListInstance> for Runtime {
type Score = sp_npos_elections::VoteWeight;
}

/// Dynamic params that can be adjusted at runtime.
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
pub mod dynamic_params {
use super::*;

/// Parameters used to calculate era payouts, see
/// [`polkadot_runtime_common::impls::EraPayoutParams`].
#[dynamic_pallet_params]
#[codec(index = 0)]
pub mod inflation {
/// Minimum inflation rate used to calculate era payouts.
#[codec(index = 0)]
pub static MinInflation: Perquintill = Perquintill::from_rational(25u64, 1000);

/// Maximum inflation rate used to calculate era payouts.
#[codec(index = 1)]
pub static MaxInflation: Perquintill = Perquintill::from_percent(10);

/// Ideal stake ratio used to calculate era payouts.
#[codec(index = 2)]
pub static IdealStake: Perquintill = Perquintill::from_percent(75);

/// Falloff used to calculate era payouts.
#[codec(index = 3)]
pub static Falloff: Perquintill = Perquintill::from_percent(5);

/// Whether to use auction slots or not in the calculation of era payouts, then we subtract
/// `num_auctioned_slots.min(60) / 300` from `ideal_stake`.
///
/// That is, we assume up to 60 parachains that are leased can reduce the ideal stake by a
/// maximum of 20%.
///
/// With the move to agile-coretime, this parameter does not make much sense and should
/// generally be set to false.
#[codec(index = 4)]
pub static UseAuctionSlots: bool = true;
}
}

#[cfg(feature = "runtime-benchmarks")]
impl Default for RuntimeParameters {
fn default() -> Self {
RuntimeParameters::Inflation(dynamic_params::inflation::Parameters::MinInflation(
dynamic_params::inflation::MinInflation,
Some(Perquintill::from_rational(25u64, 1000u64)),
))
}
}

/// Defines what origin can modify which dynamic parameters.
pub struct DynamicParameterOrigin;
impl frame_support::traits::EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey>
for DynamicParameterOrigin
{
type Success = ();

fn try_origin(
origin: RuntimeOrigin,
key: &RuntimeParametersKey,
) -> Result<Self::Success, RuntimeOrigin> {
use crate::RuntimeParametersKey::*;

match key {
Inflation(_) => frame_system::ensure_root(origin.clone()),
}
.map_err(|_| origin)
}

#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
// Provide the origin for the parameter returned by `Default`:
Ok(RuntimeOrigin::root())
}
}

impl pallet_parameters::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeParameters = RuntimeParameters;
type AdminOrigin = DynamicParameterOrigin;
type WeightInfo = weights::pallet_parameters::WeightInfo<Runtime>;
}

/// Defines how much should the inflation be for an era given its duration.
pub struct EraPayout;
impl pallet_staking::EraPayout<Balance> for EraPayout {
Expand Down Expand Up @@ -1641,7 +1559,6 @@ construct_runtime! {
Referenda: pallet_referenda = 21,
Origins: pallet_custom_origins = 22,
Whitelist: pallet_whitelist = 23,
Parameters: pallet_parameters = 27,

// Claims. Usable initially.
Claims: claims = 24,
Expand Down Expand Up @@ -2272,7 +2189,6 @@ mod benches {
);
}

use relay_common::apis::InflationInfo;
impl Runtime {
fn impl_experimental_inflation_info() -> InflationInfo {
use pallet_staking::{ActiveEra, EraPayout, ErasTotalStake};
Expand All @@ -2281,27 +2197,19 @@ impl Runtime {
.unwrap_or((0, 0));
let stake_able_issuance = Balances::total_issuance();

let ideal_staking_rate = dynamic_params::inflation::IdealStake::get();
let inflation = if dynamic_params::inflation::UseAuctionSlots::get() {
let auctioned_slots = parachains_paras::Parachains::<Runtime>::get()
.into_iter()
// all active para-ids that do not belong to a system chain is the number of
// parachains that we should take into account for inflation.
.filter(|i| *i >= LOWEST_PUBLIC_ID)
.count() as u64;
ideal_staking_rate
.saturating_sub(Perquintill::from_rational(auctioned_slots.min(60), 300u64))
} else {
ideal_staking_rate
};

// We assume un-delayed 24h eras.
let era_duration = 24 * (HOURS as Moment) * MILLISECS_PER_BLOCK;
let next_mint = <Self as pallet_staking::Config>::EraPayout::era_payout(
staked,
stake_able_issuance,
era_duration,
);
// reverse-engineer the current inflation by looking at the total minted against the total
// issuance.
let inflation = Perquintill::from_rational(
(next_mint.0 + next_mint.1) * 36525 / 100,
stake_able_issuance,
);

InflationInfo { inflation, next_mint }
}
Expand Down Expand Up @@ -3750,9 +3658,6 @@ mod remote_tests {
// timestamp now
hex!("f0c365c3cf59d671eb72da0e7a4113c49f1f0515f462cdcf84e0f1d6045dfcbb")
.to_vec(),
// para-ids
hex!("cd710b30bd2eab0352ddcc26417aa1940b76934f4cc08dee01012d059e1b83ee")
.to_vec(),
],
..Default::default()
}))
Expand Down Expand Up @@ -3783,13 +3688,9 @@ mod remote_tests {
log::info!(target: LOG_TARGET, "total-issuance = {:?}", token.amount(total_issuance));
log::info!(target: LOG_TARGET, "staking-rate = {:?}", Perquintill::from_rational(total_staked, total_issuance));
log::info!(target: LOG_TARGET, "era-duration = {:?}", average_era_duration_millis);
log::info!(target: LOG_TARGET, "min-inflation = {:?}", dynamic_params::inflation::MinInflation::get());
log::info!(target: LOG_TARGET, "max-inflation = {:?}", dynamic_params::inflation::MaxInflation::get());
log::info!(target: LOG_TARGET, "falloff = {:?}", dynamic_params::inflation::Falloff::get());
log::info!(target: LOG_TARGET, "useAuctionSlots = {:?}", dynamic_params::inflation::UseAuctionSlots::get());
log::info!(target: LOG_TARGET, "idealStake = {:?}", dynamic_params::inflation::IdealStake::get());
log::info!(target: LOG_TARGET, "maxStakingRewards = {:?}", pallet_staking::MaxStakedRewards::<Runtime>::get());
log::info!(target: LOG_TARGET, "💰 Inflation ==> staking = {:?} / leftover = {:?}", token.amount(staking), token.amount(leftover));
log::info!(target: LOG_TARGET, "inflation_rate runtime API: {:?}", Runtime::impl_experimental_inflation_info());
});
}
}
1 change: 0 additions & 1 deletion relay/polkadot/src/weights/mod.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit d28c776

Please sign in to comment.