Runtime lib restructure (#202)

* impl apis exported

* runtime version test moved to constants

* constants exported

* constant related errors fixed

* pallet configs exported

* xmc_config moved to configs

* types extracted
This commit is contained in:
Özgün Özerk
2024-05-31 20:06:18 +03:00
committed by GitHub
parent 64d64b88d0
commit dc4f0129f1
26 changed files with 2608 additions and 2442 deletions
@@ -0,0 +1,78 @@
//! OpenGov governance config
pub mod origins;
pub use origins::{Spender, WhitelistedCaller};
mod tracks;
use frame_support::{
parameter_types,
traits::{ConstU32, EitherOf},
};
use frame_system::{EnsureRoot, EnsureRootWithSuccess, EnsureSigned};
use crate::{
constants::{
currency::{CENTS, GRAND},
DAYS,
},
types::{AccountId, Balance, BlockNumber},
Balances, Preimage, Referenda, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Scheduler,
Treasury,
};
parameter_types! {
pub const VoteLockingPeriod: BlockNumber = 7 * DAYS;
}
impl pallet_conviction_voting::Config for Runtime {
type Currency = Balances;
type MaxTurnout =
frame_support::traits::tokens::currency::ActiveIssuanceOf<Balances, Self::AccountId>;
type MaxVotes = ConstU32<512>;
type Polls = Referenda;
type RuntimeEvent = RuntimeEvent;
type VoteLockingPeriod = VoteLockingPeriod;
type WeightInfo = pallet_conviction_voting::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const MaxBalance: Balance = Balance::max_value();
}
pub type TreasurySpender = EitherOf<EnsureRootWithSuccess<AccountId, MaxBalance>, Spender>;
impl origins::pallet_custom_origins::Config for Runtime {}
impl pallet_whitelist::Config for Runtime {
type DispatchWhitelistedOrigin = EitherOf<EnsureRoot<Self::AccountId>, WhitelistedCaller>;
type Preimages = Preimage;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_whitelist::weights::SubstrateWeight<Runtime>;
type WhitelistOrigin = EnsureRoot<Self::AccountId>;
}
parameter_types! {
pub const AlarmInterval: BlockNumber = 1;
pub const SubmissionDeposit: Balance = 3 * CENTS;
pub const UndecidingTimeout: BlockNumber = 14 * DAYS;
}
impl pallet_referenda::Config for Runtime {
type AlarmInterval = AlarmInterval;
type CancelOrigin = EnsureRoot<AccountId>;
type Currency = Balances;
type KillOrigin = EnsureRoot<AccountId>;
type MaxQueued = ConstU32<20>;
type Preimages = Preimage;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type Scheduler = Scheduler;
type Slash = Treasury;
type SubmissionDeposit = SubmissionDeposit;
type SubmitOrigin = EnsureSigned<AccountId>;
type Tally = pallet_conviction_voting::TallyOf<Runtime>;
type Tracks = tracks::TracksInfo;
type UndecidingTimeout = UndecidingTimeout;
type Votes = pallet_conviction_voting::VotesOf<Runtime>;
type WeightInfo = pallet_referenda::weights::SubstrateWeight<Runtime>;
}
@@ -0,0 +1,115 @@
//! Custom origins for governance interventions.
pub use pallet_custom_origins::*;
#[frame_support::pallet]
pub mod pallet_custom_origins {
use frame_support::pallet_prelude::*;
use crate::configs::governance::{Balance, CENTS, GRAND};
#[pallet::config]
pub trait Config: frame_system::Config {}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)]
#[pallet::origin]
pub enum Origin {
/// Origin for spending (any amount of) funds.
Treasurer,
/// Origin able to cancel referenda.
ReferendumCanceller,
/// Origin able to kill referenda.
ReferendumKiller,
/// Origin able to spend the amount specified in Spender.
SmallTipper,
/// Origin able to spend the amount specified in Spender.
BigTipper,
/// Origin able to spend the amount specified in Spender.
SmallSpender,
/// Origin able to spend the amount specified in Spender.
MediumSpender,
/// Origin able to spend the amount specified in Spender.
BigSpender,
/// Origin able to dispatch a whitelisted call.
WhitelistedCaller,
}
macro_rules! decl_unit_ensures {
( $name:ident: $success_type:ty = $success:expr ) => {
pub struct $name;
impl<O: Into<Result<Origin, O>> + From<Origin>>
EnsureOrigin<O> for $name
{
type Success = $success_type;
fn try_origin(o: O) -> Result<Self::Success, O> {
o.into().and_then(|o| match o {
Origin::$name => Ok($success),
r => Err(O::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
Ok(O::from(Origin::$name))
}
}
};
( $name:ident ) => { decl_unit_ensures! { $name : () = () } };
( $name:ident: $success_type:ty = $success:expr, $( $rest:tt )* ) => {
decl_unit_ensures! { $name: $success_type = $success }
decl_unit_ensures! { $( $rest )* }
};
( $name:ident, $( $rest:tt )* ) => {
decl_unit_ensures! { $name }
decl_unit_ensures! { $( $rest )* }
};
() => {}
}
decl_unit_ensures!(Treasurer, ReferendumCanceller, ReferendumKiller, WhitelistedCaller,);
macro_rules! decl_ensure {
(
$vis:vis type $name:ident: EnsureOrigin<Success = $success_type:ty> {
$( $item:ident = $success:expr, )*
}
) => {
$vis struct $name;
impl<O: Into<Result<Origin, O>> + From<Origin>>
EnsureOrigin<O> for $name
{
type Success = $success_type;
fn try_origin(o: O) -> Result<Self::Success, O> {
o.into().and_then(|o| match o {
$(
Origin::$item => Ok($success),
)*
r => Err(O::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
// By convention the more privileged origins go later, so for greatest chance
// of success, we want the last one.
let _result: Result<O, ()> = Err(());
$(
let _result: Result<O, ()> = Ok(O::from(Origin::$item));
)*
_result
}
}
}
}
decl_ensure! {
pub type Spender: EnsureOrigin<Success = Balance> {
SmallTipper = 250 * 3 * CENTS,
BigTipper = GRAND,
SmallSpender = 10 * GRAND,
MediumSpender = 100 * GRAND,
BigSpender = 1_000 * GRAND,
Treasurer = 10_000 * GRAND,
}
}
}
@@ -0,0 +1,214 @@
//! Track configurations for governance.
use super::*;
use crate::constants::MINUTES;
const fn percent(x: i32) -> sp_arithmetic::FixedI64 {
sp_arithmetic::FixedI64::from_rational(x as u128, 100)
}
use pallet_referenda::Curve;
const APP_ROOT: Curve = Curve::make_reciprocal(4, 28, percent(80), percent(50), percent(100));
const SUP_ROOT: Curve = Curve::make_linear(28, 28, percent(0), percent(50));
const APP_TREASURER: Curve = Curve::make_reciprocal(4, 28, percent(80), percent(50), percent(100));
const SUP_TREASURER: Curve = Curve::make_linear(28, 28, percent(0), percent(50));
const APP_REFERENDUM_CANCELLER: Curve = Curve::make_linear(17, 28, percent(50), percent(100));
const SUP_REFERENDUM_CANCELLER: Curve =
Curve::make_reciprocal(12, 28, percent(1), percent(0), percent(50));
const APP_REFERENDUM_KILLER: Curve = Curve::make_linear(17, 28, percent(50), percent(100));
const SUP_REFERENDUM_KILLER: Curve =
Curve::make_reciprocal(12, 28, percent(1), percent(0), percent(50));
const APP_SMALL_TIPPER: Curve = Curve::make_linear(10, 28, percent(50), percent(100));
const SUP_SMALL_TIPPER: Curve = Curve::make_reciprocal(1, 28, percent(4), percent(0), percent(50));
const APP_BIG_TIPPER: Curve = Curve::make_linear(10, 28, percent(50), percent(100));
const SUP_BIG_TIPPER: Curve = Curve::make_reciprocal(8, 28, percent(1), percent(0), percent(50));
const APP_SMALL_SPENDER: Curve = Curve::make_linear(17, 28, percent(50), percent(100));
const SUP_SMALL_SPENDER: Curve =
Curve::make_reciprocal(12, 28, percent(1), percent(0), percent(50));
const APP_MEDIUM_SPENDER: Curve = Curve::make_linear(23, 28, percent(50), percent(100));
const SUP_MEDIUM_SPENDER: Curve =
Curve::make_reciprocal(16, 28, percent(1), percent(0), percent(50));
const APP_BIG_SPENDER: Curve = Curve::make_linear(28, 28, percent(50), percent(100));
const SUP_BIG_SPENDER: Curve = Curve::make_reciprocal(20, 28, percent(1), percent(0), percent(50));
const APP_WHITELISTED_CALLER: Curve =
Curve::make_reciprocal(16, 28 * 24, percent(96), percent(50), percent(100));
const SUP_WHITELISTED_CALLER: Curve =
Curve::make_reciprocal(1, 28, percent(20), percent(5), percent(50));
const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo<Balance, BlockNumber>); 10] = [
(
0,
pallet_referenda::TrackInfo {
name: "root",
max_deciding: 1,
decision_deposit: 100 * GRAND,
prepare_period: 8 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 12 * MINUTES,
min_enactment_period: 5 * MINUTES,
min_approval: APP_ROOT,
min_support: SUP_ROOT,
},
),
(
1,
pallet_referenda::TrackInfo {
name: "whitelisted_caller",
max_deciding: 100,
decision_deposit: 10 * GRAND,
prepare_period: 6 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 4 * MINUTES,
min_enactment_period: 3 * MINUTES,
min_approval: APP_WHITELISTED_CALLER,
min_support: SUP_WHITELISTED_CALLER,
},
),
(
11,
pallet_referenda::TrackInfo {
name: "treasurer",
max_deciding: 10,
decision_deposit: GRAND,
prepare_period: 8 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 8 * MINUTES,
min_enactment_period: 5 * MINUTES,
min_approval: APP_TREASURER,
min_support: SUP_TREASURER,
},
),
(
20,
pallet_referenda::TrackInfo {
name: "referendum_canceller",
max_deciding: 1_000,
decision_deposit: 10 * GRAND,
prepare_period: 8 * MINUTES,
decision_period: 14 * MINUTES,
confirm_period: 8 * MINUTES,
min_enactment_period: 3 * MINUTES,
min_approval: APP_REFERENDUM_CANCELLER,
min_support: SUP_REFERENDUM_CANCELLER,
},
),
(
21,
pallet_referenda::TrackInfo {
name: "referendum_killer",
max_deciding: 1_000,
decision_deposit: 50 * GRAND,
prepare_period: 8 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 8 * MINUTES,
min_enactment_period: 3 * MINUTES,
min_approval: APP_REFERENDUM_KILLER,
min_support: SUP_REFERENDUM_KILLER,
},
),
(
30,
pallet_referenda::TrackInfo {
name: "small_tipper",
max_deciding: 200,
decision_deposit: 3 * CENTS,
prepare_period: MINUTES,
decision_period: 14 * MINUTES,
confirm_period: 4 * MINUTES,
min_enactment_period: MINUTES,
min_approval: APP_SMALL_TIPPER,
min_support: SUP_SMALL_TIPPER,
},
),
(
31,
pallet_referenda::TrackInfo {
name: "big_tipper",
max_deciding: 100,
decision_deposit: 10 * 3 * CENTS,
prepare_period: 4 * MINUTES,
decision_period: 14 * MINUTES,
confirm_period: 12 * MINUTES,
min_enactment_period: 3 * MINUTES,
min_approval: APP_BIG_TIPPER,
min_support: SUP_BIG_TIPPER,
},
),
(
32,
pallet_referenda::TrackInfo {
name: "small_spender",
max_deciding: 50,
decision_deposit: 100 * 3 * CENTS,
prepare_period: 10 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 10 * MINUTES,
min_enactment_period: 5 * MINUTES,
min_approval: APP_SMALL_SPENDER,
min_support: SUP_SMALL_SPENDER,
},
),
(
33,
pallet_referenda::TrackInfo {
name: "medium_spender",
max_deciding: 50,
decision_deposit: 200 * 3 * CENTS,
prepare_period: 10 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 12 * MINUTES,
min_enactment_period: 5 * MINUTES,
min_approval: APP_MEDIUM_SPENDER,
min_support: SUP_MEDIUM_SPENDER,
},
),
(
34,
pallet_referenda::TrackInfo {
name: "big_spender",
max_deciding: 50,
decision_deposit: 400 * 3 * CENTS,
prepare_period: 10 * MINUTES,
decision_period: 20 * MINUTES,
confirm_period: 14 * MINUTES,
min_enactment_period: 5 * MINUTES,
min_approval: APP_BIG_SPENDER,
min_support: SUP_BIG_SPENDER,
},
),
];
pub struct TracksInfo;
impl pallet_referenda::TracksInfo<Balance, BlockNumber> for TracksInfo {
type Id = u16;
type RuntimeOrigin = <RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin;
fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo<Balance, BlockNumber>)] {
&TRACKS_DATA[..]
}
fn track_for(id: &Self::RuntimeOrigin) -> Result<Self::Id, ()> {
if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) {
match system_origin {
frame_system::RawOrigin::Root => Ok(0),
_ => Err(()),
}
} else if let Ok(custom_origin) = origins::Origin::try_from(id.clone()) {
match custom_origin {
origins::Origin::WhitelistedCaller => Ok(1),
origins::Origin::Treasurer => Ok(11),
// Referendum admins
origins::Origin::ReferendumCanceller => Ok(20),
origins::Origin::ReferendumKiller => Ok(21),
// Limited treasury spenders
origins::Origin::SmallTipper => Ok(30),
origins::Origin::BigTipper => Ok(31),
origins::Origin::SmallSpender => Ok(32),
origins::Origin::MediumSpender => Ok(33),
origins::Origin::BigSpender => Ok(34),
}
} else {
Err(())
}
}
}
pallet_referenda::impl_tracksinfo_get!(TracksInfo, Balance, BlockNumber);
+706
View File
@@ -0,0 +1,706 @@
pub mod governance;
pub mod xcm_config;
#[cfg(feature = "async-backing")]
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
#[cfg(not(feature = "async-backing"))]
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
use frame_support::{
derive_impl,
dispatch::DispatchClass,
parameter_types,
traits::{
AsEnsureOriginWithArg, ConstU32, ConstU64, Contains, EitherOfDiverse, FindAuthor,
InstanceFilter, TransformOrigin,
},
weights::{ConstantMultiplier, Weight},
PalletId,
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned,
};
pub use governance::origins::pallet_custom_origins;
use governance::{origins::Treasurer, TreasurySpender};
use pallet_ethereum::PostLogContent;
use pallet_evm::{EVMCurrencyAdapter, EnsureAccountId20, IdentityAddressMapping};
use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use polkadot_runtime_common::{
impls::{LocatableAssetConverter, VersionedLocatableAsset, VersionedLocationConverter},
xcm_sender::NoPriceForMessageDelivery,
BlockHashCount, SlowAdjustingFeeUpdate,
};
use scale_info::TypeInfo;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{H160, U256};
use sp_runtime::{
traits::{AccountIdLookup, BlakeTwo256, IdentityLookup},
ConsensusEngineId, Perbill, Permill, RuntimeDebug,
};
use sp_std::marker::PhantomData;
use sp_version::RuntimeVersion;
// XCM Imports
use xcm::{
latest::{prelude::BodyId, InteriorLocation, Junction::PalletInstance},
VersionedLocation,
};
use xcm_builder::PayOverXcm;
#[cfg(not(feature = "runtime-benchmarks"))]
use xcm_builder::ProcessXcmMessage;
use xcm_config::XcmOriginToTransactDispatchOrigin;
use crate::{
constants::{
currency::{deposit, CENTS, EXISTENTIAL_DEPOSIT, MICROCENTS, MILLICENTS},
AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MAX_BLOCK_LENGTH,
MAX_POV_SIZE, NORMAL_DISPATCH_RATIO, SLOT_DURATION, VERSION, WEIGHT_PER_GAS,
},
opaque,
types::{
AccountId, Balance, Block, BlockNumber, CollatorSelectionUpdateOrigin, ConsensusHook, Hash,
Nonce,
},
weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
Aura, Balances, BaseFee, CollatorSelection, EVMChainId, MessageQueue, OriginCaller, PalletInfo,
ParachainSystem, Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeFreezeReason,
RuntimeHoldReason, RuntimeOrigin, RuntimeTask, Session, SessionKeys, System, Timestamp,
Treasury, UncheckedExtrinsic, WeightToFee, XcmpQueue,
};
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
// This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
// The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
// the lazy contract deletion.
pub RuntimeBlockLength: BlockLength =
BlockLength::max_with_normal_ratio(MAX_BLOCK_LENGTH, NORMAL_DISPATCH_RATIO);
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have some extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
pub const SS58Prefix: u16 = 42;
}
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
fn contains(c: &RuntimeCall) -> bool {
match c {
// We filter anonymous proxy as they make "reserve" inconsistent
// See: https://github.com/paritytech/substrate/blob/37cca710eed3dadd4ed5364c7686608f5175cce1/frame/proxy/src/lib.rs#L270
RuntimeCall::Proxy(method) => !matches!(
method,
pallet_proxy::Call::create_pure { .. } | pallet_proxy::Call::kill_pure { .. }
),
_ => true,
}
}
}
/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from
/// [`ParaChainDefaultConfig`](`struct@frame_system::config_preludes::ParaChainDefaultConfig`),
/// but overridden as needed.
#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The basic call filter to use in dispatchable.
type BaseCallFilter = NormalFilter;
/// The block type.
type Block = Block;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The maximum length of a block (in bytes).
type BlockLength = RuntimeBlockLength;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The lookup mechanism to get account ID from whatever is passed in
/// dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The maximum number of consumers allowed on a single account.
type MaxConsumers = ConstU32<16>;
/// The index type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The action to take on a Runtime Upgrade
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
/// Converts a module to an index of this module in the runtime.
type PalletInfo = PalletInfo;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
/// Runtime version.
type Version = Version;
}
parameter_types! {
pub MaximumSchedulerWeight: frame_support::weights::Weight = Perbill::from_percent(80) *
RuntimeBlockWeights::get().max_block;
pub const MaxScheduledPerBlock: u32 = 50;
pub const NoPreimagePostponement: Option<u32> = Some(10);
}
impl pallet_scheduler::Config for Runtime {
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type MaximumWeight = MaximumSchedulerWeight;
type OriginPrivilegeCmp = frame_support::traits::EqualPrivilegeOnly;
type PalletsOrigin = OriginCaller;
type Preimages = Preimage;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type ScheduleOrigin = EnsureRoot<AccountId>;
type WeightInfo = pallet_scheduler::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const PreimageBaseDeposit: Balance = deposit(2, 64);
pub const PreimageByteDeposit: Balance = deposit(0, 1);
pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
}
impl pallet_preimage::Config for Runtime {
type Consideration = frame_support::traits::fungible::HoldConsideration<
AccountId,
Balances,
PreimageHoldReason,
frame_support::traits::LinearStoragePrice<
PreimageBaseDeposit,
PreimageByteDeposit,
Balance,
>,
>;
type Currency = Balances;
type ManagerOrigin = EnsureRoot<AccountId>;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_preimage::weights::SubstrateWeight<Runtime>;
}
impl pallet_timestamp::Config for Runtime {
#[cfg(feature = "experimental")]
type MinimumPeriod = ConstU64<0>;
#[cfg(not(feature = "experimental"))]
type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
}
impl pallet_authorship::Config for Runtime {
type EventHandler = (CollatorSelection,);
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
}
parameter_types! {
pub const MaxProxies: u32 = 32;
pub const MaxPending: u32 = 32;
pub const ProxyDepositBase: Balance = deposit(1, 40);
pub const AnnouncementDepositBase: Balance = deposit(1, 48);
pub const ProxyDepositFactor: Balance = deposit(0, 33);
pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
}
/// The type used to represent the kinds of proxying allowed.
/// If you are adding new pallets, consider adding new ProxyType variant
#[derive(
Copy,
Clone,
Decode,
Default,
Encode,
Eq,
MaxEncodedLen,
Ord,
PartialEq,
PartialOrd,
RuntimeDebug,
TypeInfo,
)]
pub enum ProxyType {
/// Allows to proxy all calls
#[default]
Any,
/// Allows all non-transfer calls
NonTransfer,
/// Allows to finish the proxy
CancelProxy,
/// Allows to operate with collators list (invulnerables, candidates, etc.)
Collator,
}
impl InstanceFilter<RuntimeCall> for ProxyType {
fn filter(&self, c: &RuntimeCall) -> bool {
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => !matches!(c, RuntimeCall::Balances { .. }),
ProxyType::CancelProxy => matches!(
c,
RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
| RuntimeCall::Multisig { .. }
),
ProxyType::Collator => {
matches!(c, RuntimeCall::CollatorSelection { .. } | RuntimeCall::Multisig { .. })
}
}
}
}
impl pallet_proxy::Config for Runtime {
type AnnouncementDepositBase = AnnouncementDepositBase;
type AnnouncementDepositFactor = AnnouncementDepositFactor;
type CallHasher = BlakeTwo256;
type Currency = Balances;
type MaxPending = MaxPending;
type MaxProxies = MaxProxies;
type ProxyDepositBase = ProxyDepositBase;
type ProxyDepositFactor = ProxyDepositFactor;
type ProxyType = ProxyType;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
pub const MaxFreezes: u32 = 0;
pub const MaxLocks: u32 = 50;
pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type AccountStore = System;
/// The type for recording an account's balance.
type Balance = Balance;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type FreezeIdentifier = ();
type MaxFreezes = MaxFreezes;
type MaxLocks = MaxLocks;
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type RuntimeFreezeReason = RuntimeFreezeReason;
type RuntimeHoldReason = RuntimeHoldReason;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const AssetDeposit: Balance = 10 * CENTS;
pub const AssetAccountDeposit: Balance = deposit(1, 16);
pub const ApprovalDeposit: Balance = MILLICENTS;
pub const StringLimit: u32 = 50;
pub const MetadataDepositBase: Balance = deposit(1, 68);
pub const MetadataDepositPerByte: Balance = deposit(0, 1);
pub const RemoveItemsLimit: u32 = 1000;
}
impl pallet_assets::Config for Runtime {
type ApprovalDeposit = ApprovalDeposit;
type AssetAccountDeposit = AssetAccountDeposit;
type AssetDeposit = AssetDeposit;
type AssetId = u32;
type AssetIdParameter = parity_scale_codec::Compact<u32>;
type Balance = Balance;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
type CallbackHandle = ();
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type Currency = Balances;
type Extra = ();
type ForceOrigin = EnsureRoot<AccountId>;
type Freezer = ();
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type RemoveItemsLimit = RemoveItemsLimit;
type RuntimeEvent = RuntimeEvent;
type StringLimit = StringLimit;
type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
/// Relay Chain `TransactionByteFee` / 10
pub const TransactionByteFee: Balance = 10 * MICROCENTS;
pub const OperationalFeeMultiplier: u8 = 5;
}
impl pallet_transaction_payment::Config for Runtime {
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type RuntimeEvent = RuntimeEvent;
type WeightToFee = WeightToFee;
}
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
}
impl cumulus_pallet_parachain_system::Config for Runtime {
#[cfg(not(feature = "async-backing"))]
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
#[cfg(feature = "async-backing")]
type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
type ConsensusHook = ConsensusHook;
type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
type OnSystemEvent = ();
type OutboundXcmpMessageSource = XcmpQueue;
type ReservedDmpWeight = ReservedDmpWeight;
type ReservedXcmpWeight = ReservedXcmpWeight;
type RuntimeEvent = RuntimeEvent;
type SelfParaId = parachain_info::Pallet<Runtime>;
type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight<Runtime>;
type XcmpMessageHandler = XcmpQueue;
}
impl parachain_info::Config for Runtime {}
parameter_types! {
pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
pub const HeapSize: u32 = 64 * 1024;
pub const MaxStale: u32 = 8;
}
impl pallet_message_queue::Config for Runtime {
type HeapSize = HeapSize;
type IdleMaxServiceWeight = MessageQueueServiceWeight;
type MaxStale = MaxStale;
#[cfg(feature = "runtime-benchmarks")]
type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
cumulus_primitives_core::AggregateMessageOrigin,
>;
#[cfg(not(feature = "runtime-benchmarks"))]
type MessageProcessor = ProcessXcmMessage<
AggregateMessageOrigin,
xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
RuntimeCall,
>;
// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
type RuntimeEvent = RuntimeEvent;
type ServiceWeight = MessageQueueServiceWeight;
type Size = u32;
type WeightInfo = pallet_message_queue::weights::SubstrateWeight<Runtime>;
}
impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
pub const MaxInboundSuspended: u32 = 1000;
}
impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ChannelInfo = ParachainSystem;
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type MaxInboundSuspended = MaxInboundSuspended;
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
type RuntimeEvent = RuntimeEvent;
type VersionWrapper = ();
type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight<Runtime>;
// Enqueue XCMP messages from siblings for later processing.
type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
}
parameter_types! {
// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
pub const DepositBase: Balance = deposit(1, 88);
// Additional storage item size of 32 bytes.
pub const DepositFactor: Balance = deposit(0, 32);
pub const MaxSignatories: u16 = 100;
}
impl pallet_multisig::Config for Runtime {
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = MaxSignatories;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_multisig::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const Period: u32 = 6 * HOURS;
pub const Offset: u32 = 0;
}
impl pallet_session::Config for Runtime {
type Keys = SessionKeys;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type RuntimeEvent = RuntimeEvent;
// Essentially just Aura, but let's be pedantic.
type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
type SessionManager = CollatorSelection;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type ValidatorId = <Self as frame_system::Config>::AccountId;
// we don't have stash and controller, thus we don't need the convert as well.
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
#[cfg(not(feature = "async-backing"))]
parameter_types! {
pub const AllowMultipleBlocksPerSlot: bool = false;
pub const MaxAuthorities: u32 = 100_000;
}
#[cfg(feature = "async-backing")]
parameter_types! {
pub const AllowMultipleBlocksPerSlot: bool = true;
pub const MaxAuthorities: u32 = 100_000;
}
impl pallet_aura::Config for Runtime {
type AllowMultipleBlocksPerSlot = AllowMultipleBlocksPerSlot;
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = MaxAuthorities;
#[cfg(feature = "async-backing")]
type SlotDuration = ConstU64<SLOT_DURATION>;
#[cfg(not(feature = "async-backing"))]
type SlotDuration = pallet_aura::MinimumPeriodTimesTwo<Self>;
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const SessionLength: BlockNumber = 6 * HOURS;
// StakingAdmin pluralistic body.
pub const StakingAdminBodyId: BodyId = BodyId::Defense;
}
parameter_types! {
pub const MaxCandidates: u32 = 100;
pub const MaxInvulnerables: u32 = 20;
pub const MinEligibleCollators: u32 = 4;
}
impl pallet_collator_selection::Config for Runtime {
type Currency = Balances;
// should be a multiple of session or things will get inconsistent
type KickThreshold = Period;
type MaxCandidates = MaxCandidates;
type MaxInvulnerables = MaxInvulnerables;
type MinEligibleCollators = MinEligibleCollators;
type PotId = PotId;
type RuntimeEvent = RuntimeEvent;
type UpdateOrigin = CollatorSelectionUpdateOrigin;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
type ValidatorRegistration = Session;
type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);
pub const ProposalBondMinimum: Balance = 2000; // * CENTS
pub const ProposalBondMaximum: Balance = 1;// * GRAND;
pub const SpendPeriod: BlockNumber = 6 * DAYS;
pub const Burn: Permill = Permill::from_perthousand(2);
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
// The asset's interior location for the paying account. This is the Treasury
// pallet instance (which sits at index 13).
pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(13).into();
pub const MaxApprovals: u32 = 100;
}
parameter_types! {
pub TreasuryAccount: AccountId = Treasury::account_id();
}
impl pallet_treasury::Config for Runtime {
type ApproveOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
type AssetKind = VersionedLocatableAsset;
type BalanceConverter = frame_support::traits::tokens::UnityAssetBalanceConversion;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments;
type Beneficiary = VersionedLocation;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Burn = ();
type BurnDestination = ();
type Currency = Balances;
type MaxApprovals = MaxApprovals;
type OnSlash = Treasury;
type PalletId = TreasuryPalletId;
type Paymaster = PayOverXcm<
TreasuryInteriorLocation,
xcm_config::XcmRouter,
crate::PolkadotXcm,
ConstU32<{ 6 * HOURS }>,
Self::Beneficiary,
Self::AssetKind,
LocatableAssetConverter,
VersionedLocationConverter,
>;
type PayoutPeriod = PayoutSpendPeriod;
type ProposalBond = ProposalBond;
type ProposalBondMaximum = ProposalBondMaximum;
type ProposalBondMinimum = ProposalBondMinimum;
type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
type RuntimeEvent = RuntimeEvent;
type SpendFunds = ();
type SpendOrigin = TreasurySpender;
type SpendPeriod = SpendPeriod;
type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}
impl pallet_ethereum::Config for Runtime {
type ExtraDataLength = ConstU32<30>;
type PostLogContent = PostBlockAndTxnHashes;
type RuntimeEvent = RuntimeEvent;
type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
}
parameter_types! {
pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
pub GasLimitPovSizeRatio: u64 = BlockGasLimit::get().as_u64().saturating_div(MAX_POV_SIZE);
pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
pub SuicideQuickClearLimit: u32 = 0;
}
impl pallet_evm::Config for Runtime {
type AddressMapping = IdentityAddressMapping;
type BlockGasLimit = BlockGasLimit;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAccountId20;
type ChainId = EVMChainId;
type Currency = Balances;
type FeeCalculator = BaseFee;
type FindAuthor = FindAuthorSession<Aura>;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type OnChargeTransaction = EVMCurrencyAdapter<Balances, ()>;
type OnCreate = ();
// FIXME: Will be implemented in #11
type PrecompilesType = ();
// FIXME: Will be implemented in #11
type PrecompilesValue = ();
type Runner = pallet_evm::runner::stack::Runner<Self>;
type RuntimeEvent = RuntimeEvent;
type SuicideQuickClearLimit = SuicideQuickClearLimit;
type Timestamp = Timestamp;
// FIXME: run the benchmarks
type WeightInfo = pallet_evm::weights::SubstrateWeight<Self>;
type WeightPerGas = WeightPerGas;
type WithdrawOrigin = EnsureAccountId20;
}
impl pallet_evm_chain_id::Config for Runtime {}
parameter_types! {
/// Starting value for base fee. Set at the same value as in Ethereum.
pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000);
/// Default elasticity rate. Set at the same value as in Ethereum.
pub DefaultElasticity: Permill = Permill::from_parts(125_000);
}
/// The thresholds based on which the base fee will change.
pub struct BaseFeeThreshold;
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
fn lower() -> Permill {
Permill::zero()
}
fn ideal() -> Permill {
Permill::from_parts(500_000)
}
fn upper() -> Permill {
Permill::from_parts(1_000_000)
}
}
impl pallet_base_fee::Config for Runtime {
type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
type DefaultElasticity = DefaultElasticity;
type RuntimeEvent = RuntimeEvent;
type Threshold = BaseFeeThreshold;
}
pub struct FindAuthorSession<F>(PhantomData<F>);
impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorSession<F> {
fn find_author<'a, I>(digests: I) -> Option<H160>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
if let Some(author_index) = F::find_author(digests) {
let account_id: AccountId = Session::validators()[author_index as usize];
return Some(H160::from(account_id));
}
None
}
}
#[derive(Clone)]
pub struct TransactionConverter;
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
UncheckedExtrinsic::new_unsigned(
pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
)
}
}
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(
&self,
transaction: pallet_ethereum::Transaction,
) -> opaque::UncheckedExtrinsic {
let extrinsic = UncheckedExtrinsic::new_unsigned(
pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
);
let encoded = extrinsic.encode();
opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
.expect("Encoded extrinsic is always valid")
}
}
@@ -0,0 +1,251 @@
use frame_support::{
parameter_types,
traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess},
weights::Weight,
};
use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use polkadot_parachain_primitives::primitives::Sibling;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountKey20Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom,
DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds,
FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, NativeAsset,
NoChecking, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic,
};
use xcm_executor::XcmExecutor;
use crate::{
configs::{
Balances, ParachainSystem, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee,
XcmpQueue,
},
types::{AccountId, Balance},
AllPalletsWithSystem, Assets, ParachainInfo, PolkadotXcm,
};
parameter_types! {
pub const RelayLocation: Location = Location::parent();
pub const RelayNetwork: Option<NetworkId> = None;
pub PlaceholderAccount: AccountId = PolkadotXcm::check_account();
pub AssetsPalletLocation: Location =
PalletInstance(<Assets as PalletInfoAccess>::index() as u8).into();
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorLocation = Parachain(ParachainInfo::parachain_id().into()).into();
}
/// `AssetId/Balancer` converter for `TrustBackedAssets`
pub type TrustBackedAssetsConvertedConcreteId =
assets_common::TrustBackedAssetsConvertedConcreteId<AssetsPalletLocation, Balance>;
/// Type for specifying how a `Location` can be converted into an
/// `AccountId`. This is used when determining ownership of accounts for asset
/// transacting and when attempting to use XCM `Transact` in order to determine
/// the dispatch Origin.
pub type LocationToAccountId = (
// The parent (Relay-chain) origin converts to the parent `AccountId`.
ParentIsPreset<AccountId>,
// Sibling parachain origins convert to AccountId via the `ParaId::into`.
SiblingParachainConvertsVia<Sibling, AccountId>,
// If we receive a Location of type AccountKey20, just generate a native account
AccountKey20Aliases<RelayNetwork, AccountId>,
);
/// Means for transacting assets on this chain.
pub type LocalAssetTransactor = FungibleAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Do a simple punn to convert an AccountId20 Location into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We don't track any teleports.
(),
>;
/// Means for transacting assets besides the native currency on this chain.
pub type LocalFungiblesTransactor = FungiblesAdapter<
// Use this fungibles implementation:
Assets,
// Use this currency when it is a fungible asset matching the given location or name:
TrustBackedAssetsConvertedConcreteId,
// Convert an XCM MultiLocation into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We don't track any teleports of `Assets`.
NoChecking,
// We don't track any teleports of `Assets`, but a placeholder account is provided due to trait
// bounds.
PlaceholderAccount,
>;
/// Means for transacting assets on this chain.
pub type AssetTransactors = (LocalAssetTransactor, LocalFungiblesTransactor);
/// This is the type we use to convert an (incoming) XCM origin into a local
/// `Origin` instance, ready for dispatching a transaction with Xcm's
/// `Transact`. There is an `OriginKind` which can biases the kind of local
/// `Origin` it will become.
pub type XcmOriginToTransactDispatchOrigin = (
// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
// foreign chains who want to have a local sovereign account on this chain which they control.
SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
// recognized.
RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
// recognized.
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
// Xcm Origins defined by a Multilocation of type AccountKey20 can be converted to a 20 byte-
// account local origin
SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
XcmPassthrough<RuntimeOrigin>,
);
parameter_types! {
// One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
pub const UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub struct ParentOrParentsExecutivePlurality;
impl Contains<Location> for ParentOrParentsExecutivePlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Executive, .. }]))
}
}
pub type Barrier = TrailingSetTopicAsId<
DenyThenTry<
DenyReserveTransferToRelayChain,
(
TakeWeightCredit,
WithComputedOrigin<
(
AllowTopLevelPaidExecutionFrom<Everything>,
AllowExplicitUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
// ^^^ Parent and its exec plurality get free execution
),
UniversalLocation,
ConstU32<8>,
>,
),
>,
>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
type AssetClaims = PolkadotXcm;
type AssetExchanger = ();
type AssetLocker = ();
// How to withdraw and deposit an asset.
type AssetTransactor = AssetTransactors;
type AssetTrap = PolkadotXcm;
type Barrier = Barrier;
type CallDispatcher = RuntimeCall;
type FeeManager = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type HrmpNewChannelOpenRequestHandler = ();
type IsReserve = NativeAsset;
type IsTeleporter = ();
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type MessageExporter = ();
type OriginConverter = XcmOriginToTransactDispatchOrigin;
type PalletInstancesInfo = AllPalletsWithSystem;
type ResponseHandler = PolkadotXcm;
type RuntimeCall = RuntimeCall;
type SafeCallFilter = Everything;
type SubscriptionService = PolkadotXcm;
type Trader = UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ()>;
type TransactionalProcessor = FrameTransactionalProcessor;
type UniversalAliases = Nothing;
// Teleporting is disabled.
type UniversalLocation = UniversalLocation;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type XcmSender = XcmRouter;
}
use frame_support::{pallet_prelude::Get, traits::OriginTrait};
use sp_runtime::traits::TryConvert;
// Convert a local Origin (i.e., a signed 20 byte account Origin) to a Multilocation
pub struct SignedToAccountId20<Origin, AccountId, Network>(
sp_std::marker::PhantomData<(Origin, AccountId, Network)>,
);
impl<Origin: OriginTrait + Clone, AccountId: Into<[u8; 20]>, Network: Get<Option<NetworkId>>>
TryConvert<Origin, Location> for SignedToAccountId20<Origin, AccountId, Network>
where
Origin::PalletsOrigin: From<frame_system::RawOrigin<AccountId>>
+ TryInto<frame_system::RawOrigin<AccountId>, Error = Origin::PalletsOrigin>,
{
fn try_convert(o: Origin) -> Result<Location, Origin> {
o.try_with_caller(|caller| match caller.try_into() {
Ok(frame_system::RawOrigin::Signed(who)) =>
Ok(AccountKey20 { key: who.into(), network: Network::get() }.into()),
Ok(other) => Err(other.into()),
Err(other) => Err(other),
})
}
}
// Converts a Signed Local Origin into a Location
pub type LocalOriginToLocation = SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
/// The means for routing XCM messages which are not for local execution into
/// the right message queues.
pub type XcmRouter = WithUniqueTopic<(
// Two routers - use UMP to communicate with the relay chain:
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, (), ()>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
parameter_types! {
pub const MaxLockers: u32 = 8;
pub const MaxRemoteLockConsumers: u32 = 0;
}
impl pallet_xcm::Config for Runtime {
type AdminOrigin = EnsureRoot<AccountId>;
// ^ Override for AdvertisedXcmVersion default
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type MaxLockers = MaxLockers;
type MaxRemoteLockConsumers = MaxLockers;
type RemoteLockConsumerIdentifier = ();
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type SovereignAccountOf = LocationToAccountId;
type TrustedLockers = ();
type UniversalLocation = UniversalLocation;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type WeightInfo = pallet_xcm::TestWeightInfo;
type XcmExecuteFilter = Nothing;
// ^ Disable dispatchable execute on the XCM pallet.
// Needs to be `Everything` for local testing.
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmReserveTransferFilter = Nothing;
type XcmRouter = XcmRouter;
type XcmTeleportFilter = Everything;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
}
impl cumulus_pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}