Companion for #9373 (Refactor Benchmarks for Wasm Memory) (#3549)

* cargo update -p sp-io

* fix benchmarking

* fix bridge benchmarks
This commit is contained in:
Shawn Tabrizi
2021-08-02 11:17:19 +02:00
committed by GitHub
parent 1b0baab401
commit 3445cbecd0
5 changed files with 853 additions and 615 deletions
+159 -157
View File
File diff suppressed because it is too large Load Diff
+81 -28
View File
@@ -40,16 +40,20 @@ pub mod rialto_poa;
use crate::millau_messages::{ToMillauMessagePayload, WithMillauMessageBridge};
use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge};
use bridge_runtime_common::messages::{
source::estimate_message_dispatch_and_delivery_fee, MessageBridge,
};
use codec::Decode;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};
use pallet_grandpa::{
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::traits::{Block as BlockT, IdentityLookup, NumberFor, OpaqueKeys};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{Block as BlockT, IdentityLookup, NumberFor, OpaqueKeys},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature, MultiSigner,
};
@@ -146,10 +150,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
parameter_types! {
@@ -278,10 +279,15 @@ impl bp_currency_exchange::DepositInto for DepositInto {
type Recipient = AccountId;
type Amount = Balance;
fn deposit_into(recipient: Self::Recipient, amount: Self::Amount) -> bp_currency_exchange::Result<()> {
fn deposit_into(
recipient: Self::Recipient,
amount: Self::Amount,
) -> bp_currency_exchange::Result<()> {
// let balances module make all checks for us (it won't allow depositing lower than existential
// deposit, balance overflow, ...)
let deposited = <pallet_balances::Pallet<Runtime> as Currency<AccountId>>::deposit_creating(&recipient, amount);
let deposited = <pallet_balances::Pallet<Runtime> as Currency<AccountId>>::deposit_creating(
&recipient, amount,
);
// I'm dropping deposited here explicitly to illustrate the fact that it'll update `TotalIssuance`
// on drop
@@ -302,7 +308,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
);
Ok(())
}
},
_ if deposited_amount == 0 => {
log::error!(
target: "runtime",
@@ -312,7 +318,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
);
Err(bp_currency_exchange::Error::DepositFailed)
}
},
_ => {
log::error!(
target: "runtime",
@@ -324,7 +330,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
// we can't return DepositFailed error here, because storage changes were made
Err(bp_currency_exchange::Error::DepositPartiallyFailed)
}
},
}
}
}
@@ -333,9 +339,12 @@ impl pallet_grandpa::Config for Runtime {
type Event = Event;
type Call = Call;
type KeyOwnerProofSystem = ();
type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type KeyOwnerIdentification =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::IdentificationTuple;
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation = ();
// TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78)
type WeightInfo = ();
@@ -485,7 +494,8 @@ impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type TargetHeaderChain = crate::millau_messages::Millau;
type LaneMessageVerifier = crate::millau_messages::ToMillauMessageVerifier;
type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
type MessageDeliveryAndDispatchPayment =
pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
GetDeliveryConfirmationTransactionFee,
@@ -550,8 +560,13 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signatu
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive =
frame_executive::Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllPallets>;
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPallets,
>;
impl_runtime_apis! {
impl sp_api::Core<Block> for Runtime {
@@ -802,10 +817,36 @@ impl_runtime_apis! {
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
list_benchmark!(
list,
extra,
pallet_bridge_currency_exchange,
BridgeCurrencyExchangeBench::<Runtime, KovanCurrencyExchange>
);
list_benchmark!(
list,
extra,
pallet_bridge_messages,
MessagesBench::<Runtime, WithMillauMessagesInstance>
);
list_benchmark!(list, extra, pallet_bridge_grandpa, BridgeMillauGrandpa);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig,
) -> Result<
(Vec<frame_benchmarking::BenchmarkBatch>, Vec<frame_support::traits::StorageInfo>),
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
@@ -1051,8 +1092,7 @@ impl_runtime_apis! {
add_benchmark!(params, batches, pallet_bridge_grandpa, BridgeMillauGrandpa);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
let storage_info = AllPalletsWithSystem::storage_info();
Ok((batches, storage_info))
Ok(batches)
}
}
}
@@ -1088,7 +1128,8 @@ mod tests {
use bridge_runtime_common::messages;
fn run_deposit_into_test(test: impl Fn(AccountId) -> Balance) {
let mut ext: sp_io::TestExternalities = SystemConfig::default().build_storage::<Runtime>().unwrap().into();
let mut ext: sp_io::TestExternalities =
SystemConfig::default().build_storage::<Runtime>().unwrap().into();
ext.execute_with(|| {
// initially issuance is zero
assert_eq!(
@@ -1100,7 +1141,10 @@ mod tests {
let account: AccountId = [1u8; 32].into();
let initial_amount = ExistentialDeposit::get();
let deposited =
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::deposit_creating(&account, initial_amount);
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::deposit_creating(
&account,
initial_amount,
);
drop(deposited);
assert_eq!(
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::total_issuance(),
@@ -1140,10 +1184,13 @@ mod tests {
bp_rialto::max_extrinsic_size(),
bp_rialto::max_extrinsic_weight(),
max_incoming_message_proof_size,
messages::target::maximal_incoming_message_dispatch_weight(bp_rialto::max_extrinsic_weight()),
messages::target::maximal_incoming_message_dispatch_weight(
bp_rialto::max_extrinsic_weight(),
),
);
let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint(
let max_incoming_inbound_lane_data_proof_size =
bp_messages::InboundLaneData::<()>::encoded_size_hint(
bp_rialto::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _,
bp_millau::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _,
@@ -1162,7 +1209,9 @@ mod tests {
fn deposit_into_existing_account_works() {
run_deposit_into_test(|existing_account| {
let initial_amount =
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(&existing_account);
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(
&existing_account,
);
let additional_amount = 10_000;
<Runtime as pallet_bridge_currency_exchange::Config<KovanCurrencyExchange>>::DepositInto::deposit_into(
existing_account.clone(),
@@ -1170,7 +1219,9 @@ mod tests {
)
.unwrap();
assert_eq!(
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(&existing_account),
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(
&existing_account
),
initial_amount + additional_amount,
);
additional_amount
@@ -1189,7 +1240,9 @@ mod tests {
)
.unwrap();
assert_eq!(
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(&new_account),
<pallet_balances::Pallet<Runtime> as Currency<AccountId>>::free_balance(
&new_account
),
initial_amount + additional_amount,
);
additional_amount
+206 -146
View File
@@ -21,89 +21,87 @@
#![recursion_limit = "256"]
use pallet_transaction_payment::CurrencyAdapter;
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use sp_core::u32_trait::{_1, _2, _3, _5};
use parity_scale_codec::{Encode, Decode, MaxEncodedLen};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
};
use runtime_common::{
claims, paras_registrar, xcm_sender, slots, auctions, crowdloan,
SlowAdjustingFeeUpdate, CurrencyToVote, impls::DealWithFees,
BlockHashCount, RocksDbWeight, BlockWeights, BlockLength,
OffchainSolutionWeightLimit, OffchainSolutionLengthLimit,
ToAuthor,
auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, slots, xcm_sender,
BlockHashCount, BlockLength, BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit,
OffchainSolutionWeightLimit, RocksDbWeight, SlowAdjustingFeeUpdate, ToAuthor,
};
use sp_core::u32_trait::{_1, _2, _3, _5};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use runtime_parachains::{
configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp,
inclusion as parachains_inclusion, initializer as parachains_initializer,
origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler,
session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
};
use runtime_parachains::origin as parachains_origin;
use runtime_parachains::configuration as parachains_configuration;
use runtime_parachains::shared as parachains_shared;
use runtime_parachains::inclusion as parachains_inclusion;
use runtime_parachains::paras_inherent as parachains_paras_inherent;
use runtime_parachains::initializer as parachains_initializer;
use runtime_parachains::session_info as parachains_session_info;
use runtime_parachains::paras as parachains_paras;
use runtime_parachains::dmp as parachains_dmp;
use runtime_parachains::ump as parachains_ump;
use runtime_parachains::hrmp as parachains_hrmp;
use runtime_parachains::scheduler as parachains_scheduler;
use runtime_parachains::reward_points as parachains_reward_points;
use runtime_parachains::runtime_api_impl::v1 as parachains_runtime_api_impl;
use xcm::v0::{MultiLocation::{self, Null, X1}, NetworkId, BodyId, Xcm, Junction::Parachain};
use xcm::v0::MultiAsset::{self, AllConcreteFungible};
use xcm_builder::{
AccountId32Aliases, ChildParachainConvertsVia, SovereignSignedViaLocation, CurrencyAdapter as XcmCurrencyAdapter,
ChildParachainAsNative, SignedAccountId32AsNative, ChildSystemParachainAsSuperuser, LocationInverter,
IsConcrete, FixedWeightBounds, TakeWeightCredit, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
IsChildSystemParachain, UsingComponents, BackingToPlurality, SignedToAccountId32,
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
construct_runtime, parameter_types,
traits::{All, Filter, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, OnRuntimeUpgrade},
weights::Weight,
PalletId, RuntimeDebug,
};
use xcm_executor::XcmExecutor;
use frame_system::{EnsureOneOf, EnsureRoot};
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_arithmetic::Perquintill;
use sp_core::OpaqueMetadata;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult, KeyTypeId, Percent,
Permill, Perbill,
transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
create_runtime_str, generic, impl_opaque_keys,
traits::{
BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
OpaqueKeys, SaturatedConversion, Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
};
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
use sp_staking::SessionIndex;
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
use frame_support::{
parameter_types, construct_runtime, RuntimeDebug, PalletId,
traits::{KeyOwnerProofSystem, LockIdentifier, Filter, InstanceFilter, All, OnRuntimeUpgrade},
weights::Weight,
};
use frame_system::{EnsureRoot, EnsureOneOf};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_session::historical as session_historical;
use sp_version::RuntimeVersion;
use static_assertions::const_assert;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use pallet_mmr_primitives as mmr;
use xcm::v0::{
BodyId,
Junction::Parachain,
MultiAsset::{self, AllConcreteFungible},
MultiLocation::{self, Null, X1},
NetworkId, Xcm,
};
use xcm_builder::{
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
BackingToPlurality, ChildParachainAsNative, ChildParachainConvertsVia,
ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds,
IsChildSystemParachain, IsConcrete, LocationInverter, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
};
use xcm_executor::XcmExecutor;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};
use constants::{currency::*, fee::*, time::*};
// Weights used in the runtime.
mod weights;
@@ -133,32 +131,27 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
babe_primitives::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
/// Don't allow swaps until parathread story is more mature.
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
fn filter(c: &Call) -> bool {
!matches!(c,
Call::Registrar(paras_registrar::Call::swap(..))
)
!matches!(c, Call::Registrar(paras_registrar::Call::swap(..)))
}
}
type MoreThanHalfCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
>;
parameter_types! {
@@ -201,7 +194,7 @@ parameter_types! {
type ScheduleOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
>;
impl pallet_scheduler::Config for Runtime {
@@ -420,8 +413,8 @@ fn era_payout(
period_fraction: Perquintill,
auctioned_slots: u64,
) -> (Balance, Balance) {
use sp_arithmetic::traits::Saturating;
use pallet_staking_reward_fn::compute_inflation;
use sp_arithmetic::traits::Saturating;
let min_annual_inflation = Perquintill::from_rational(25u64, 1000u64);
let delta_annual_inflation = max_annual_inflation.saturating_sub(min_annual_inflation);
@@ -431,13 +424,13 @@ fn era_payout(
// Therefore the ideal amount at stake (as a percentage of total issuance) is 75% less the amount that we expect
// to be taken up with auctions.
let ideal_stake = Perquintill::from_percent(75)
.saturating_sub(auction_proportion);
let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
let stake = Perquintill::from_rational(total_staked, non_gilt_issuance);
let falloff = Perquintill::from_percent(5);
let adjustment = compute_inflation(stake, ideal_stake, falloff);
let staking_inflation = min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
let staking_inflation =
min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
let max_payout = period_fraction * max_annual_inflation * non_gilt_issuance;
let staking_payout = (period_fraction * staking_inflation) * non_gilt_issuance;
@@ -488,18 +481,19 @@ parameter_types! {
type SlashCancelOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
>;
impl pallet_staking::Config for Runtime {
const MAX_NOMINATIONS: u32 = <NposCompactSolution24 as sp_npos_elections::CompactSolution>::LIMIT as u32;
const MAX_NOMINATIONS: u32 =
<NposCompactSolution24 as sp_npos_elections::CompactSolution>::LIMIT as u32;
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVote;
type ElectionProvider = ElectionProviderMultiPhase;
type GenesisElectionProvider =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<
pallet_election_provider_multi_phase::OnChainConfig<Self>
pallet_election_provider_multi_phase::OnChainConfig<Self>,
>;
type RewardRemainder = Treasury;
type Event = Event;
@@ -540,16 +534,21 @@ impl pallet_democracy::Config for Runtime {
type VotingPeriod = VotingPeriod;
type MinimumDeposit = MinimumDeposit;
/// A straight majority of the council can decide what their next motion is.
type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
type ExternalOrigin =
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
/// A majority can have the next scheduled referendum be a straight majority-carries vote.
type ExternalMajorityOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
type ExternalMajorityOrigin =
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
/// A unanimous council can have the next scheduled referendum be a straight default-carries
/// (NTB) vote.
type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>;
type ExternalDefaultOrigin =
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>;
/// Two thirds of the technical committee can have an `ExternalMajority/ExternalDefault` vote
/// be tabled immediately and with a shorter voting/enactment period.
type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>;
type FastTrackOrigin =
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
type InstantOrigin =
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>;
type InstantAllowed = InstantAllowed;
type FastTrackVotingPeriod = FastTrackVotingPeriod;
// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
@@ -686,7 +685,7 @@ parameter_types! {
type ApproveOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
>;
impl pallet_treasury::Config for Runtime {
@@ -767,15 +766,19 @@ impl pallet_grandpa::Config for Runtime {
type KeyOwnerProofSystem = Historical;
type HandleEquivocation =
pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
type HandleEquivocation = pallet_grandpa::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ReportLongevity,
>;
type WeightInfo = ();
}
/// Submits transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
@@ -786,10 +789,8 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
use sp_runtime::traits::StaticLookup;
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
@@ -801,17 +802,20 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
);
let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
}).ok()?;
let signature = raw_payload.using_encoded(|payload| {
C::sign(payload, public)
})?;
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
Some((call, (address, signature, extra)))
@@ -823,7 +827,8 @@ impl frame_system::offchain::SigningTypes for Runtime {
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
@@ -838,7 +843,8 @@ impl claims::Config for Runtime {
type Event = Event;
type VestingSchedule = Vesting;
type Prefix = Prefix;
type MoveClaimOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type MoveClaimOrigin =
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type WeightInfo = weights::runtime_common_claims::WeightInfo<Runtime>;
}
@@ -931,7 +937,8 @@ impl pallet_society::Config for Runtime {
type MembershipChanged = ();
type RotationPeriod = RotationPeriod;
type MaxLockDuration = MaxLockDuration;
type FounderSetOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type FounderSetOrigin =
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type SuspensionJudgementOrigin = pallet_society::EnsureFounder<Runtime>;
type ChallengePeriod = ChallengePeriod;
type MaxCandidateIntake = MaxCandidateIntake;
@@ -962,7 +969,9 @@ parameter_types! {
}
/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen)]
#[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen,
)]
pub enum ProxyType {
Any,
NonTransfer,
@@ -971,12 +980,17 @@ pub enum ProxyType {
IdentityJudgement,
CancelProxy,
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<Call> for ProxyType {
fn filter(&self, c: &Call) -> bool {
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => matches!(c,
ProxyType::NonTransfer => matches!(
c,
Call::System(..) |
Call::Babe(..) |
Call::Timestamp(..) |
@@ -1022,31 +1036,24 @@ impl InstanceFilter<Call> for ProxyType {
Call::Registrar(paras_registrar::Call::reserve(..)) |
Call::Crowdloan(..) |
Call::Slots(..) |
Call::Auctions(..)
// Specifically omitting the entire XCM Pallet
Call::Auctions(..) // Specifically omitting the entire XCM Pallet
),
ProxyType::Governance => matches!(c,
ProxyType::Governance => matches!(
c,
Call::Democracy(..) |
Call::Council(..) |
Call::TechnicalCommittee(..) |
Call::Council(..) | Call::TechnicalCommittee(..) |
Call::PhragmenElection(..) |
Call::Treasury(..) |
Call::Bounties(..) |
Call::Tips(..) |
Call::Utility(..)
Call::Treasury(..) | Call::Bounties(..) |
Call::Tips(..) | Call::Utility(..)
),
ProxyType::Staking => matches!(c,
Call::Staking(..) |
Call::Session(..) |
Call::Utility(..)
ProxyType::Staking =>
matches!(c, Call::Staking(..) | Call::Session(..) | Call::Utility(..)),
ProxyType::IdentityJudgement => matches!(
c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) | Call::Utility(..)
),
ProxyType::IdentityJudgement => matches!(c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) |
Call::Utility(..)
),
ProxyType::CancelProxy => matches!(c,
Call::Proxy(pallet_proxy::Call::reject_announcement(..))
)
ProxyType::CancelProxy =>
matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))),
}
}
fn is_superset(&self, o: &Self) -> bool {
@@ -1180,7 +1187,7 @@ parameter_types! {
type AuctionInitiate = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
>;
impl auctions::Config for Runtime {
@@ -1221,8 +1228,7 @@ pub type SovereignAccountOf = (
/// view of XCM-only concepts like `MultiLocation` and `MultiAsset`.
///
/// Ours is only aware of the Balances pallet, which is mapped to `KsmLocation`.
pub type LocalAssetTransactor =
XcmCurrencyAdapter<
pub type LocalAssetTransactor = XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
@@ -1233,7 +1239,7 @@ pub type LocalAssetTransactor =
AccountId,
// We track our teleports in/out to keep total issuance correct.
CheckAccount,
>;
>;
/// The means that we convert an the XCM message origin location into a local dispatch origin.
type LocalOriginConverter = (
@@ -1263,9 +1269,7 @@ parameter_types! {
pub const KusamaForStatemint: (MultiAsset, MultiLocation) =
(AllConcreteFungible { id: Null }, X1(Parachain(1000)));
}
pub type TrustedTeleporters = (
xcm_builder::Case<KusamaForStatemint>,
);
pub type TrustedTeleporters = (xcm_builder::Case<KusamaForStatemint>,);
/// The barriers one of which must be passed for an XCM message to be executed.
pub type Barrier = (
@@ -1302,17 +1306,25 @@ parameter_types! {
pub type LocalOriginToLocation = (
// We allow an origin from the Collective pallet to be used in XCM as a corresponding Plurality of the
// `Unit` body.
BackingToPlurality<Origin, pallet_collective::Origin<Runtime, CouncilCollective>, CouncilBodyId>,
BackingToPlurality<
Origin,
pallet_collective::Origin<Runtime, CouncilCollective>,
CouncilBodyId,
>,
// And a usual Signed origin to be used in XCM as a corresponding AccountId32
SignedToAccountId32<Origin, AccountId, KusamaNetwork>,
);
pub struct OnlyWithdrawTeleportForAccounts;
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdrawTeleportForAccounts {
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)>
for OnlyWithdrawTeleportForAccounts
{
fn contains((ref origin, ref msg): &(MultiLocation, Xcm<Call>)) -> bool {
use xcm::v0::{
Xcm::WithdrawAsset, Order::{BuyExecution, InitiateTeleport, DepositAsset},
MultiAsset::{All, ConcreteFungible}, Junction::{AccountId32, Plurality},
Junction::{AccountId32, Plurality},
MultiAsset::{All, ConcreteFungible},
Order::{BuyExecution, DepositAsset, InitiateTeleport},
Xcm::WithdrawAsset,
};
match origin {
// Root and council are are allowed to execute anything.
@@ -1347,7 +1359,7 @@ impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdra
)
)
)
}
},
// Nobody else is allowed to execute anything.
_ => false,
}
@@ -1535,9 +1547,9 @@ pub struct MigratePalletVersionToStorageVersion;
impl OnRuntimeUpgrade for MigratePalletVersionToStorageVersion {
fn on_runtime_upgrade() -> frame_support::weights::Weight {
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<AllPalletsWithSystem>(
&RocksDbWeight::get()
)
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<
AllPalletsWithSystem,
>(&RocksDbWeight::get())
}
}
@@ -1842,17 +1854,66 @@ sp_api::impl_runtime_apis! {
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
let mut list = Vec::<BenchmarkList>::new();
// Polkadot
// NOTE: Make sure to prefix these `runtime_common::` so that path resolves correctly
// in the generated file.
list_benchmark!(list, extra, runtime_common::auctions, Auctions);
list_benchmark!(list, extra, runtime_common::crowdloan, Crowdloan);
list_benchmark!(list, extra, runtime_common::claims, Claims);
list_benchmark!(list, extra, runtime_common::slots, Slots);
list_benchmark!(list, extra, runtime_common::paras_registrar, Registrar);
// Substrate
list_benchmark!(list, extra, pallet_balances, Balances);
list_benchmark!(list, extra, pallet_bounties, Bounties);
list_benchmark!(list, extra, pallet_collective, Council);
list_benchmark!(list, extra, pallet_democracy, Democracy);
list_benchmark!(list, extra, pallet_elections_phragmen, PhragmenElection);
list_benchmark!(list, extra, pallet_election_provider_multi_phase, ElectionProviderMultiPhase);
list_benchmark!(list, extra, pallet_gilt, Gilt);
list_benchmark!(list, extra, pallet_identity, Identity);
list_benchmark!(list, extra, pallet_im_online, ImOnline);
list_benchmark!(list, extra, pallet_indices, Indices);
list_benchmark!(list, extra, pallet_membership, TechnicalMembership);
list_benchmark!(list, extra, pallet_multisig, Multisig);
list_benchmark!(list, extra, pallet_offences, OffencesBench::<Runtime>);
list_benchmark!(list, extra, pallet_proxy, Proxy);
list_benchmark!(list, extra, pallet_scheduler, Scheduler);
list_benchmark!(list, extra, pallet_session, SessionBench::<Runtime>);
list_benchmark!(list, extra, pallet_staking, Staking);
list_benchmark!(list, extra, frame_system, SystemBench::<Runtime>);
list_benchmark!(list, extra, pallet_timestamp, Timestamp);
list_benchmark!(list, extra, pallet_tips, Tips);
list_benchmark!(list, extra, pallet_treasury, Treasury);
list_benchmark!(list, extra, pallet_utility, Utility);
list_benchmark!(list, extra, pallet_vesting, Vesting);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<
(Vec<frame_benchmarking::BenchmarkBatch>, Vec<frame_support::traits::StorageInfo>),
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
use frame_support::traits::StorageInfoTrait;
// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency issues.
// To get around that, we separated the Session benchmarks into its own crate, which is why
// we need these two lines below.
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
@@ -1912,8 +1973,7 @@ sp_api::impl_runtime_apis! {
add_benchmark!(params, batches, pallet_vesting, Vesting);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
let storage_info = AllPalletsWithSystem::storage_info();
Ok((batches, storage_info))
Ok(batches)
}
}
}
+200 -121
View File
@@ -22,63 +22,65 @@
use pallet_transaction_payment::CurrencyAdapter;
use runtime_common::{
claims, SlowAdjustingFeeUpdate, CurrencyToVote,
impls::DealWithFees,
BlockHashCount, RocksDbWeight, BlockWeights, BlockLength,
OffchainSolutionWeightLimit, OffchainSolutionLengthLimit,
ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
claims, impls::DealWithFees, AssignmentSessionKeyPlaceholder, BlockHashCount, BlockLength,
BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit, OffchainSolutionWeightLimit,
ParachainSessionKeyPlaceholder, RocksDbWeight, SlowAdjustingFeeUpdate,
};
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use sp_core::u32_trait::{_1, _2, _3, _4, _5};
use parity_scale_codec::{Encode, Decode, MaxEncodedLen};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
construct_runtime, parameter_types,
traits::{Filter, KeyOwnerProofSystem, LockIdentifier, OnRuntimeUpgrade},
weights::Weight,
PalletId, RuntimeDebug,
};
use frame_system::{EnsureOneOf, EnsureRoot};
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment,
Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex,
};
use sp_core::{
u32_trait::{_1, _2, _3, _4, _5},
OpaqueMetadata,
};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult,
KeyTypeId, Percent, Permill, Perbill, curve::PiecewiseLinear,
transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
create_runtime_str,
curve::PiecewiseLinear,
generic, impl_opaque_keys,
traits::{
BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
OpaqueKeys, SaturatedConversion, Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
};
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
use sp_staking::SessionIndex;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
use frame_support::{
parameter_types, construct_runtime, RuntimeDebug, PalletId,
traits::{KeyOwnerProofSystem, LockIdentifier, Filter, OnRuntimeUpgrade},
weights::Weight,
};
use frame_system::{EnsureRoot, EnsureOneOf};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_session::historical as session_historical;
use sp_version::RuntimeVersion;
use static_assertions::const_assert;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use pallet_mmr_primitives as mmr;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};
use constants::{currency::*, fee::*, time::*};
use frame_support::traits::InstanceFilter;
// Weights used in the runtime.
@@ -107,16 +109,13 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
babe_primitives::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
pub struct BaseFilter;
@@ -124,16 +123,32 @@ impl Filter<Call> for BaseFilter {
fn filter(call: &Call) -> bool {
match call {
// These modules are all allowed to be called by transactions:
Call::Democracy(_) | Call::Council(_) | Call::TechnicalCommittee(_) |
Call::TechnicalMembership(_) | Call::Treasury(_) | Call::PhragmenElection(_) |
Call::System(_) | Call::Scheduler(_) | Call::Indices(_) |
Call::Babe(_) | Call::Timestamp(_) | Call::Balances(_) |
Call::Authorship(_) | Call::Staking(_) |
Call::Session(_) | Call::Grandpa(_) | Call::ImOnline(_) |
Call::Utility(_) | Call::Claims(_) | Call::Vesting(_) |
Call::Identity(_) | Call::Proxy(_) | Call::Multisig(_) |
Call::Bounties(_) | Call::Tips(_) | Call::ElectionProviderMultiPhase(_)
=> true,
Call::Democracy(_) |
Call::Council(_) |
Call::TechnicalCommittee(_) |
Call::TechnicalMembership(_) |
Call::Treasury(_) |
Call::PhragmenElection(_) |
Call::System(_) |
Call::Scheduler(_) |
Call::Indices(_) |
Call::Babe(_) |
Call::Timestamp(_) |
Call::Balances(_) |
Call::Authorship(_) |
Call::Staking(_) |
Call::Session(_) |
Call::Grandpa(_) |
Call::ImOnline(_) |
Call::Utility(_) |
Call::Claims(_) |
Call::Vesting(_) |
Call::Identity(_) |
Call::Proxy(_) |
Call::Multisig(_) |
Call::Bounties(_) |
Call::Tips(_) |
Call::ElectionProviderMultiPhase(_) => true,
}
}
}
@@ -141,7 +156,7 @@ impl Filter<Call> for BaseFilter {
type MoreThanHalfCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>
pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
>;
parameter_types! {
@@ -184,7 +199,7 @@ parameter_types! {
type ScheduleOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
>;
impl pallet_scheduler::Config for Runtime {
@@ -421,11 +436,12 @@ parameter_types! {
type SlashCancelOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>,
>;
impl pallet_staking::Config for Runtime {
const MAX_NOMINATIONS: u32 = <NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
const MAX_NOMINATIONS: u32 =
<NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVote;
@@ -445,7 +461,7 @@ impl pallet_staking::Config for Runtime {
type ElectionProvider = ElectionProviderMultiPhase;
type GenesisElectionProvider =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<
pallet_election_provider_multi_phase::OnChainConfig<Self>
pallet_election_provider_multi_phase::OnChainConfig<Self>,
>;
type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
}
@@ -498,41 +514,48 @@ impl pallet_democracy::Config for Runtime {
type VotingPeriod = VotingPeriod;
type MinimumDeposit = MinimumDeposit;
/// A straight majority of the council can decide what their next motion is.
type ExternalOrigin = frame_system::EnsureOneOf<AccountId,
type ExternalOrigin = frame_system::EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
frame_system::EnsureRoot<AccountId>,
>;
/// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote.
type ExternalMajorityOrigin = frame_system::EnsureOneOf<AccountId,
type ExternalMajorityOrigin = frame_system::EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
frame_system::EnsureRoot<AccountId>,
>;
/// A unanimous council can have the next scheduled referendum be a straight default-carries
/// (NTB) vote.
type ExternalDefaultOrigin = frame_system::EnsureOneOf<AccountId,
type ExternalDefaultOrigin = frame_system::EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>,
frame_system::EnsureRoot<AccountId>,
>;
/// Two thirds of the technical committee can have an `ExternalMajority/ExternalDefault` vote
/// be tabled immediately and with a shorter voting/enactment period.
type FastTrackOrigin = frame_system::EnsureOneOf<AccountId,
type FastTrackOrigin = frame_system::EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>,
frame_system::EnsureRoot<AccountId>,
>;
type InstantOrigin = frame_system::EnsureOneOf<AccountId,
type InstantOrigin = frame_system::EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
frame_system::EnsureRoot<AccountId>,
>;
type InstantAllowed = InstantAllowed;
type FastTrackVotingPeriod = FastTrackVotingPeriod;
// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
type CancellationOrigin = EnsureOneOf<AccountId,
type CancellationOrigin = EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
EnsureRoot<AccountId>,
>;
// To cancel a proposal before it has been passed, the technical committee must be unanimous or
// Root must agree.
type CancelProposalOrigin = EnsureOneOf<AccountId,
type CancelProposalOrigin = EnsureOneOf<
AccountId,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
EnsureRoot<AccountId>,
>;
@@ -657,7 +680,7 @@ parameter_types! {
type ApproveOrigin = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
>;
impl pallet_treasury::Config for Runtime {
@@ -738,15 +761,19 @@ impl pallet_grandpa::Config for Runtime {
type KeyOwnerProofSystem = Historical;
type HandleEquivocation =
pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
type HandleEquivocation = pallet_grandpa::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ReportLongevity,
>;
type WeightInfo = ();
}
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
@@ -757,10 +784,8 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
use sp_runtime::traits::StaticLookup;
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
@@ -772,18 +797,21 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
claims::PrevalidateAttests::<Runtime>::new(),
);
let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
}).ok()?;
let signature = raw_payload.using_encoded(|payload| {
C::sign(payload, public)
})?;
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
Some((call, (address, signature, extra)))
@@ -795,7 +823,10 @@ impl frame_system::offchain::SigningTypes for Runtime {
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where Call: From<C> {
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = Call;
}
@@ -815,7 +846,8 @@ impl claims::Config for Runtime {
type VestingSchedule = Vesting;
type Prefix = Prefix;
/// At least 3/4 of the council must agree to a claim move before it can happen.
type MoveClaimOrigin = pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>;
type MoveClaimOrigin =
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>;
type WeightInfo = weights::runtime_common_claims::WeightInfo<Runtime>;
}
@@ -867,7 +899,9 @@ parameter_types! {
}
/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen)]
#[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen,
)]
pub enum ProxyType {
Any = 0,
NonTransfer = 1,
@@ -900,19 +934,26 @@ mod proxy_type_tests {
(OldProxyType::Governance, ProxyType::Governance),
(OldProxyType::Staking, ProxyType::Staking),
(OldProxyType::IdentityJudgement, ProxyType::IdentityJudgement),
].into_iter() {
]
.into_iter()
{
assert_eq!(i.encode(), j.encode());
}
assert!(ProxyType::decode(&mut &OldProxyType::SudoBalances.encode()[..]).is_err());
}
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<Call> for ProxyType {
fn filter(&self, c: &Call) -> bool {
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => matches!(c,
ProxyType::NonTransfer => matches!(
c,
Call::System(..) |
Call::Scheduler(..) |
Call::Babe(..) |
@@ -944,28 +985,22 @@ impl InstanceFilter<Call> for ProxyType {
Call::Proxy(..) |
Call::Multisig(..)
),
ProxyType::Governance => matches!(c,
ProxyType::Governance => matches!(
c,
Call::Democracy(..) |
Call::Council(..) |
Call::TechnicalCommittee(..) |
Call::Council(..) | Call::TechnicalCommittee(..) |
Call::PhragmenElection(..) |
Call::Treasury(..) |
Call::Bounties(..) |
Call::Tips(..) |
Call::Utility(..)
Call::Treasury(..) | Call::Bounties(..) |
Call::Tips(..) | Call::Utility(..)
),
ProxyType::Staking => matches!(c,
Call::Staking(..) |
Call::Session(..) |
Call::Utility(..)
ProxyType::Staking =>
matches!(c, Call::Staking(..) | Call::Session(..) | Call::Utility(..)),
ProxyType::IdentityJudgement => matches!(
c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) | Call::Utility(..)
),
ProxyType::IdentityJudgement => matches!(c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) |
Call::Utility(..)
),
ProxyType::CancelProxy => matches!(c,
Call::Proxy(pallet_proxy::Call::reject_announcement(..))
)
ProxyType::CancelProxy =>
matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))),
}
}
fn is_superset(&self, o: &Self) -> bool {
@@ -1098,9 +1133,9 @@ pub struct MigratePalletVersionToStorageVersion;
impl OnRuntimeUpgrade for MigratePalletVersionToStorageVersion {
fn on_runtime_upgrade() -> frame_support::weights::Weight {
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<AllPalletsWithSystem>(
&RocksDbWeight::get()
)
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<
AllPalletsWithSystem,
>(&RocksDbWeight::get())
}
}
@@ -1396,17 +1431,61 @@ sp_api::impl_runtime_apis! {
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
let mut list = Vec::<BenchmarkList>::new();
// Polkadot
// NOTE: Make sure to prefix these `runtime_common::` so that path resolves correctly
// in the generated file.
list_benchmark!(list, extra, runtime_common::claims, Claims);
// Substrate
list_benchmark!(list, extra, pallet_balances, Balances);
list_benchmark!(list, extra, pallet_bounties, Bounties);
list_benchmark!(list, extra, pallet_collective, Council);
list_benchmark!(list, extra, pallet_democracy, Democracy);
list_benchmark!(list, extra, pallet_elections_phragmen, PhragmenElection);
list_benchmark!(list, extra, pallet_election_provider_multi_phase, ElectionProviderMultiPhase);
list_benchmark!(list, extra, pallet_identity, Identity);
list_benchmark!(list, extra, pallet_im_online, ImOnline);
list_benchmark!(list, extra, pallet_indices, Indices);
list_benchmark!(list, extra, pallet_membership, TechnicalMembership);
list_benchmark!(list, extra, pallet_multisig, Multisig);
list_benchmark!(list, extra, pallet_offences, OffencesBench::<Runtime>);
list_benchmark!(list, extra, pallet_proxy, Proxy);
list_benchmark!(list, extra, pallet_scheduler, Scheduler);
list_benchmark!(list, extra, pallet_session, SessionBench::<Runtime>);
list_benchmark!(list, extra, pallet_staking, Staking);
list_benchmark!(list, extra, frame_system, SystemBench::<Runtime>);
list_benchmark!(list, extra, pallet_timestamp, Timestamp);
list_benchmark!(list, extra, pallet_tips, Tips);
list_benchmark!(list, extra, pallet_treasury, Treasury);
list_benchmark!(list, extra, pallet_utility, Utility);
list_benchmark!(list, extra, pallet_vesting, Vesting);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<
(Vec<frame_benchmarking::BenchmarkBatch>, Vec<frame_support::traits::StorageInfo>),
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
use frame_support::traits::StorageInfoTrait;
// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency issues.
// To get around that, we separated the Session benchmarks into its own crate, which is why
// we need these two lines below.
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
@@ -1461,8 +1540,7 @@ sp_api::impl_runtime_apis! {
add_benchmark!(params, batches, pallet_vesting, Vesting);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
let storage_info = AllPalletsWithSystem::storage_info();
Ok((batches, storage_info))
Ok(batches)
}
}
}
@@ -1470,12 +1548,11 @@ sp_api::impl_runtime_apis! {
#[cfg(test)]
mod test_fees {
use super::*;
use frame_support::weights::WeightToFeePolynomial;
use sp_runtime::FixedPointNumber;
use frame_support::weights::GetDispatchInfo;
use parity_scale_codec::Encode;
use frame_support::weights::{GetDispatchInfo, WeightToFeePolynomial};
use pallet_transaction_payment::Multiplier;
use parity_scale_codec::Encode;
use separator::Separatable;
use sp_runtime::FixedPointNumber;
#[test]
fn payout_weight_portion() {
@@ -1512,7 +1589,10 @@ mod test_fees {
#[ignore]
fn transfer_cost_min_multiplier() {
let min_multiplier = runtime_common::MinimumMultiplier::get();
let call = <pallet_balances::Call<Runtime>>::transfer_keep_alive(Default::default(), Default::default());
let call = <pallet_balances::Call<Runtime>>::transfer_keep_alive(
Default::default(),
Default::default(),
);
let info = call.get_dispatch_info();
// convert to outer call.
let call = Call::Balances(call);
@@ -1566,8 +1646,7 @@ mod test_fees {
let cost_dollars = cost / DOLLARS;
println!(
"can support {} voters in a single block for council elections; total bond {}",
voters,
cost_dollars,
voters, cost_dollars,
);
assert!(cost_dollars > 150_000); // DOLLAR ~ new DOT ~ 10e10
}
+169 -125
View File
@@ -21,87 +21,86 @@
#![recursion_limit = "256"]
use pallet_transaction_payment::CurrencyAdapter;
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use parity_scale_codec::{Encode, Decode, MaxEncodedLen};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature,
ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
};
use runtime_common::{
paras_sudo_wrapper, paras_registrar, xcm_sender, slots, crowdloan, auctions,
SlowAdjustingFeeUpdate, CurrencyToVote,
impls::ToAuthor,
BlockHashCount, BlockWeights, BlockLength, RocksDbWeight,
OffchainSolutionWeightLimit, OffchainSolutionLengthLimit,
auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper, slots, xcm_sender,
BlockHashCount, BlockLength, BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit,
OffchainSolutionWeightLimit, RocksDbWeight, SlowAdjustingFeeUpdate,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use runtime_parachains::{
configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp,
inclusion as parachains_inclusion, initializer as parachains_initializer,
origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler,
session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
};
use runtime_parachains::origin as parachains_origin;
use runtime_parachains::configuration as parachains_configuration;
use runtime_parachains::shared as parachains_shared;
use runtime_parachains::inclusion as parachains_inclusion;
use runtime_parachains::paras_inherent as parachains_paras_inherent;
use runtime_parachains::initializer as parachains_initializer;
use runtime_parachains::session_info as parachains_session_info;
use runtime_parachains::paras as parachains_paras;
use runtime_parachains::dmp as parachains_dmp;
use runtime_parachains::ump as parachains_ump;
use runtime_parachains::hrmp as parachains_hrmp;
use runtime_parachains::scheduler as parachains_scheduler;
use runtime_parachains::reward_points as parachains_reward_points;
use runtime_parachains::runtime_api_impl::v1 as parachains_runtime_api_impl;
use xcm::v0::{MultiLocation::{self, Null, X1}, NetworkId, Xcm, Junction::Parachain};
use xcm::v0::MultiAsset::{self, AllConcreteFungible};
use xcm_executor::XcmExecutor;
use xcm::v0::{
Junction::Parachain,
MultiAsset::{self, AllConcreteFungible},
MultiLocation::{self, Null, X1},
NetworkId, Xcm,
};
use xcm_builder::{
AccountId32Aliases, ChildParachainConvertsVia, SovereignSignedViaLocation, CurrencyAdapter as XcmCurrencyAdapter,
ChildParachainAsNative, SignedAccountId32AsNative, ChildSystemParachainAsSuperuser, LocationInverter, IsConcrete,
FixedWeightBounds, TakeWeightCredit, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
IsChildSystemParachain, UsingComponents, SignedToAccountId32,
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser,
CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds, IsChildSystemParachain, IsConcrete,
LocationInverter, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
TakeWeightCredit, UsingComponents,
};
use xcm_executor::XcmExecutor;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
ApplyExtrinsicResult, KeyTypeId, Perbill, curve::PiecewiseLinear,
transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
traits::{
BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
},
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
construct_runtime, parameter_types,
traits::{All, Filter, InstanceFilter, KeyOwnerProofSystem, OnRuntimeUpgrade},
weights::Weight,
PalletId, RuntimeDebug,
};
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
use frame_system::EnsureRoot;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_core::OpaqueMetadata;
use sp_runtime::{
create_runtime_str,
curve::PiecewiseLinear,
generic, impl_opaque_keys,
traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
OpaqueKeys, SaturatedConversion, Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, KeyTypeId, Perbill,
};
use sp_staking::SessionIndex;
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
use frame_support::{
parameter_types, construct_runtime, RuntimeDebug, PalletId,
traits::{KeyOwnerProofSystem, Filter, InstanceFilter, All, OnRuntimeUpgrade},
weights::Weight,
};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_session::historical as session_historical;
use frame_system::{EnsureRoot};
use beefy_primitives::crypto::AuthorityId as BeefyId;
use pallet_mmr_primitives as mmr;
use sp_version::RuntimeVersion;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};
use constants::{currency::*, fee::*, time::*};
// Weights used in the runtime
mod weights;
@@ -131,16 +130,13 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
babe_primitives::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
/// Allow everything.
@@ -417,7 +413,8 @@ parameter_types! {
}
impl pallet_staking::Config for Runtime {
const MAX_NOMINATIONS: u32 = <NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
const MAX_NOMINATIONS: u32 =
<NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVote;
@@ -437,7 +434,7 @@ impl pallet_staking::Config for Runtime {
type ElectionProvider = ElectionProviderMultiPhase;
type GenesisElectionProvider =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<
pallet_election_provider_multi_phase::OnChainConfig<Self>
pallet_election_provider_multi_phase::OnChainConfig<Self>,
>;
type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
}
@@ -491,15 +488,19 @@ impl pallet_grandpa::Config for Runtime {
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation =
pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
type HandleEquivocation = pallet_grandpa::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ReportLongevity,
>;
type WeightInfo = ();
}
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
@@ -510,10 +511,8 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
use sp_runtime::traits::StaticLookup;
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
@@ -525,17 +524,20 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
);
let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
}).ok()?;
let signature = raw_payload.using_encoded(|payload| {
C::sign(payload, public)
})?;
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
Some((call, (address, signature, extra)))
@@ -547,7 +549,8 @@ impl frame_system::offchain::SigningTypes for Runtime {
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type OverarchingCall = Call;
@@ -649,7 +652,9 @@ parameter_types! {
}
/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen)]
#[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen,
)]
pub enum ProxyType {
Any,
NonTransfer,
@@ -658,12 +663,17 @@ pub enum ProxyType {
IdentityJudgement,
CancelProxy,
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<Call> for ProxyType {
fn filter(&self, c: &Call) -> bool {
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => matches!(c,
ProxyType::NonTransfer => matches!(
c,
Call::System(..) |
Call::Babe(..) |
Call::Timestamp(..) |
@@ -699,26 +709,22 @@ impl InstanceFilter<Call> for ProxyType {
Call::Registrar(paras_registrar::Call::reserve(..)) |
Call::Crowdloan(..) |
Call::Slots(..) |
Call::Auctions(..)
// Specifically omitting the entire XCM Pallet
),
ProxyType::Staking => matches!(c,
Call::Staking(..) |
Call::Session(..) |
Call::Utility(..)
Call::Auctions(..) // Specifically omitting the entire XCM Pallet
),
ProxyType::Staking =>
matches!(c, Call::Staking(..) | Call::Session(..) | Call::Utility(..)),
ProxyType::SudoBalances => match c {
Call::Sudo(pallet_sudo::Call::sudo(ref x)) => matches!(x.as_ref(), &Call::Balances(..)),
Call::Sudo(pallet_sudo::Call::sudo(ref x)) =>
matches!(x.as_ref(), &Call::Balances(..)),
Call::Utility(..) => true,
_ => false,
},
ProxyType::IdentityJudgement => matches!(c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) |
Call::Utility(..)
ProxyType::IdentityJudgement => matches!(
c,
Call::Identity(pallet_identity::Call::provide_judgement(..)) | Call::Utility(..)
),
ProxyType::CancelProxy => matches!(c,
Call::Proxy(pallet_proxy::Call::reject_announcement(..))
)
ProxyType::CancelProxy =>
matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))),
}
}
fn is_superset(&self, o: &Self) -> bool {
@@ -869,13 +875,10 @@ parameter_types! {
pub CheckAccount: AccountId = XcmPallet::check_account();
}
pub type LocationConverter = (
ChildParachainConvertsVia<ParaId, AccountId>,
AccountId32Aliases<WestendNetwork, AccountId>,
);
pub type LocationConverter =
(ChildParachainConvertsVia<ParaId, AccountId>, AccountId32Aliases<WestendNetwork, AccountId>);
pub type LocalAssetTransactor =
XcmCurrencyAdapter<
pub type LocalAssetTransactor = XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
@@ -886,7 +889,7 @@ pub type LocalAssetTransactor =
AccountId,
// It's a native asset so we keep track of the teleports to maintain total issuance.
CheckAccount,
>;
>;
type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, Origin>,
@@ -910,9 +913,7 @@ parameter_types! {
pub const WestendForWestmint: (MultiAsset, MultiLocation) =
(AllConcreteFungible { id: Null }, X1(Parachain(1000)));
}
pub type TrustedTeleporters = (
xcm_builder::Case<WestendForWestmint>,
);
pub type TrustedTeleporters = (xcm_builder::Case<WestendForWestmint>,);
/// The barriers one of which must be passed for an XCM message to be executed.
pub type Barrier = (
@@ -947,11 +948,15 @@ pub type LocalOriginToLocation = (
);
pub struct OnlyWithdrawTeleportForAccounts;
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdrawTeleportForAccounts {
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)>
for OnlyWithdrawTeleportForAccounts
{
fn contains((ref origin, ref msg): &(MultiLocation, Xcm<Call>)) -> bool {
use xcm::v0::{
Xcm::WithdrawAsset, Order::{BuyExecution, InitiateTeleport, DepositAsset},
MultiAsset::{All, ConcreteFungible}, Junction::AccountId32,
Junction::AccountId32,
MultiAsset::{All, ConcreteFungible},
Order::{BuyExecution, DepositAsset, InitiateTeleport},
Xcm::WithdrawAsset,
};
match origin {
// Root is allowed to execute anything.
@@ -986,7 +991,7 @@ impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdra
)
)
)
}
},
// Nobody else is allowed to execute anything.
_ => false,
}
@@ -1126,9 +1131,9 @@ pub struct MigratePalletVersionToStorageVersion;
impl OnRuntimeUpgrade for MigratePalletVersionToStorageVersion {
fn on_runtime_upgrade() -> frame_support::weights::Weight {
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<AllPalletsWithSystem>(
&RocksDbWeight::get()
)
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<
AllPalletsWithSystem,
>(&RocksDbWeight::get())
}
}
@@ -1433,17 +1438,57 @@ sp_api::impl_runtime_apis! {
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
let mut list = Vec::<BenchmarkList>::new();
// Polkadot
// NOTE: Make sure to prefix these `runtime_common::` so that path resolves correctly
// in the generated file.
list_benchmark!(list, extra, runtime_common::auctions, Auctions);
list_benchmark!(list, extra, runtime_common::crowdloan, Crowdloan);
list_benchmark!(list, extra, runtime_common::paras_registrar, Registrar);
list_benchmark!(list, extra, runtime_common::slots, Slots);
// Substrate
list_benchmark!(list, extra, pallet_balances, Balances);
list_benchmark!(list, extra, pallet_election_provider_multi_phase, ElectionProviderMultiPhase);
list_benchmark!(list, extra, pallet_identity, Identity);
list_benchmark!(list, extra, pallet_im_online, ImOnline);
list_benchmark!(list, extra, pallet_indices, Indices);
list_benchmark!(list, extra, pallet_multisig, Multisig);
list_benchmark!(list, extra, pallet_offences, OffencesBench::<Runtime>);
list_benchmark!(list, extra, pallet_proxy, Proxy);
list_benchmark!(list, extra, pallet_scheduler, Scheduler);
list_benchmark!(list, extra, pallet_session, SessionBench::<Runtime>);
list_benchmark!(list, extra, pallet_staking, Staking);
list_benchmark!(list, extra, frame_system, SystemBench::<Runtime>);
list_benchmark!(list, extra, pallet_timestamp, Timestamp);
list_benchmark!(list, extra, pallet_utility, Utility);
list_benchmark!(list, extra, pallet_vesting, Vesting);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig,
) -> Result<
(Vec<frame_benchmarking::BenchmarkBatch>, Vec<frame_support::traits::StorageInfo>),
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
use frame_support::traits::StorageInfoTrait;
// Trying to add benchmarks directly to the Session Pallet caused cyclic dependency issues.
// To get around that, we separated the Session benchmarks into its own crate, which is why
// we need these two lines below.
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
use frame_system_benchmarking::Pallet as SystemBench;
@@ -1495,8 +1540,7 @@ sp_api::impl_runtime_apis! {
add_benchmark!(params, batches, pallet_vesting, Vesting);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
let storage_info = AllPalletsWithSystem::storage_info();
Ok((batches, storage_info))
Ok(batches)
}
}
}