Pallet grouping macros (#300)

* init using relative paths for now

* not working

* cannot define same types with alias names in 2 places relalias todo

* node compiles using impl oz system to abstract over frame system

* clean

* timestamp

* parachain info

* preimage and scheduler

* proxy and balances

* utility and parachain system

* use construct openzeppelin runtime

* generic runtime apis

* pause construct runtime until other macros validated by cross template usage

* hold runtime construction until inner macros validated

* evm template impl openzeppelin system

* revert back to generic construct runtime minimal wrapper for now

* use the trivial versions for the construct runtime and impl runtime api macros for now

* fix system grouping macro name

* consensus wrapper in generic template

* include ExistentialDeposit as explicit system parameter and add asset grouping for generic

* wip governance

* wip governnace for generic

* rm placeholders for runtime api and construct runtime until implemented

* fix evm template after latest changes to system grouping

* whitelist

* custom origins and referenda to finish governance grouping in generic template

* init xcm grouping for generic template queue pallets first

* more xcm

* replace direct paths with git url and branch for the macro dep

* update cargo locks and template fuzzer paths used for constants

* use consensus macro for evm template

* fix path in generic templates constant tests

* fix more test imports for the generic template

* fix template fuzzer build for generic template

* evm template governance and clean generic governance config as well

* impl xcm for evm template compiles w unused imports

* clean evm template commented out code and init assets impl for evm template

* progress on using impl assets for evm template

* error persists despite moving from impls into scope of macro expansion

* fix imports to fix errors for assets impl for evm template

* init evm works

* generic runtime compiles with most recent changeset

* update to latest macro changes

* move asset manager config into macro expansion as much as possible

* fix and clean

* update package name use git url and rename marker struct to OpenZeppelinRuntime

* compiles

* batch merge comment suggestions

* expose ProxyType and move defn from macro expansion to types file for each runtime

* generic single file config and minimal type aliases

* single file evm config need to clean imports and minimize type aliasing next

* clean evm template

* evm compilation post macro updates

* clean evm runtimes

* clean generic

* toml sort

* fix

* fmt fixes, supported the last changes

---------

Co-authored-by: Nikita Khateev <nikita.khateev@openzeppelin.com>
This commit is contained in:
Amar Singh
2024-11-04 08:59:47 -05:00
committed by GitHub
parent 2515d4ea2a
commit 8e0feecc14
20 changed files with 555 additions and 1850 deletions
@@ -1,8 +1,5 @@
use frame_support::{
dispatch::GetDispatchInfo, parameter_types, traits::AsEnsureOriginWithArg, weights::Weight,
};
use frame_system::{EnsureRoot, EnsureSigned};
use parity_scale_codec::{Compact, Decode, Encode};
use frame_support::{dispatch::GetDispatchInfo, weights::Weight};
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::H256;
use sp_runtime::traits::Hash as THash;
@@ -13,59 +10,10 @@ use sp_std::{
use xcm::latest::Location;
use crate::{
constants::currency::{deposit, CENTS, MILLICENTS},
types::{AccountId, AssetId, Balance},
weights, AssetManager, Assets, Balances, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
AssetManager, Assets, Runtime, RuntimeCall, RuntimeOrigin,
};
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;
}
// Required for runtime benchmarks
pallet_assets::runtime_benchmarks_enabled! {
pub struct BenchmarkHelper;
impl<AssetIdParameter> pallet_assets::BenchmarkHelper<AssetIdParameter> for BenchmarkHelper
where
AssetIdParameter: From<u32>,
{
fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
(id as u32).into()
}
}
}
// Foreign assets
impl pallet_assets::Config for Runtime {
type ApprovalDeposit = ApprovalDeposit;
type AssetAccountDeposit = AssetAccountDeposit;
type AssetDeposit = AssetDeposit;
type AssetId = AssetId;
type AssetIdParameter = Compact<AssetId>;
type Balance = Balance;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = 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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_assets::WeightInfo<Runtime>;
}
// Our AssetType. For now we only handle Xcm Assets
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
pub enum AssetType {
@@ -114,6 +62,52 @@ impl From<AssetType> for AssetId {
}
}
/// This trait ensure we can convert AccountIds to AssetIds.
pub trait AccountIdAssetIdConversion<Account, AssetId> {
// Get assetId and prefix from account
fn account_to_asset_id(account: Account) -> Option<(Vec<u8>, AssetId)>;
// Get AccountId from AssetId and prefix
fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> Account;
}
const FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX: &[u8] = &[255u8; 28];
// Instruct how to go from an H256 to an AssetID
impl AccountIdAssetIdConversion<AccountId, AssetId> for Runtime {
/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
/// and by taking the lowest 128 bits as the assetId
fn account_to_asset_id(account: AccountId) -> Option<(Vec<u8>, AssetId)> {
let bytes: [u8; 32] = account.into();
let h256_account: H256 = bytes.into();
let mut data = [0u8; 4];
let (prefix_part, id_part) = h256_account.as_fixed_bytes().split_at(28);
if prefix_part == FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX {
data.copy_from_slice(id_part);
let asset_id: AssetId = u32::from_be_bytes(data);
Some((prefix_part.to_vec(), asset_id))
} else {
None
}
}
// The opposite conversion
fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> AccountId {
let mut data = [0u8; 32];
data[0..28].copy_from_slice(prefix);
data[28..32].copy_from_slice(&asset_id.to_be_bytes());
AccountId::from(data)
}
}
#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
pub struct AssetRegistrarMetadata {
pub name: Vec<u8>,
pub symbol: Vec<u8>,
pub decimals: u8,
pub is_frozen: bool,
}
// We instruct how to register the Assets
// In this case, we tell it to Create an Asset in pallet-assets
pub struct AssetRegistrar;
@@ -164,62 +158,3 @@ impl pallet_asset_manager::AssetRegistrar<Runtime> for AssetRegistrar {
.weight
}
}
#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
pub struct AssetRegistrarMetadata {
pub name: Vec<u8>,
pub symbol: Vec<u8>,
pub decimals: u8,
pub is_frozen: bool,
}
impl pallet_asset_manager::Config for Runtime {
type AssetId = AssetId;
type AssetRegistrar = AssetRegistrar;
type AssetRegistrarMetadata = AssetRegistrarMetadata;
type Balance = Balance;
type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
type ForeignAssetType = AssetType;
type RuntimeEvent = RuntimeEvent;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_asset_manager::WeightInfo<Runtime>;
}
/// This trait ensure we can convert AccountIds to AssetIds.
pub trait AccountIdAssetIdConversion<Account, AssetId> {
// Get assetId and prefix from account
fn account_to_asset_id(account: Account) -> Option<(Vec<u8>, AssetId)>;
// Get AccountId from AssetId and prefix
fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> Account;
}
// needs to be 28 bytes due to `data` is 4 bytes
const FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX: &[u8] = &[255u8; 28];
// Instruct how to go from an H256 to an AssetID
impl AccountIdAssetIdConversion<AccountId, AssetId> for Runtime {
/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
fn account_to_asset_id(account: AccountId) -> Option<(Vec<u8>, AssetId)> {
let bytes: [u8; 32] = account.into();
let h256_account: H256 = bytes.into();
let mut data = [0u8; 4];
let (prefix_part, id_part) = h256_account.as_fixed_bytes().split_at(28);
if prefix_part == FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX {
data.copy_from_slice(id_part);
// we use `data` to create a u32 -> data needs to be 4 bytes
let asset_id: AssetId = u32::from_be_bytes(data);
Some((prefix_part.to_vec(), asset_id))
} else {
None
}
}
// The opposite conversion
fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> AccountId {
let mut data = [0u8; 32];
data[0..28].copy_from_slice(prefix);
data[28..32].copy_from_slice(&asset_id.to_be_bytes());
AccountId::from(data)
}
}
@@ -2,80 +2,10 @@
pub mod origins;
pub use origins::{Spender, WhitelistedCaller};
mod tracks;
use frame_support::{
parameter_types,
traits::{ConstU32, EitherOf},
};
use frame_system::{EnsureRoot, EnsureRootWithSuccess, EnsureSigned};
pub mod tracks;
use crate::{
constants::{
currency::{CENTS, GRAND},
DAYS,
},
types::{AccountId, Balance, BlockNumber},
weights, Balances, Preimage, Referenda, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
Scheduler, Treasury,
constants::currency::{CENTS, GRAND},
types::{Balance, BlockNumber},
RuntimeOrigin,
};
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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_conviction_voting::WeightInfo<Runtime>;
}
parameter_types! {
pub const MaxBalance: Balance = Balance::MAX;
}
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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_whitelist::WeightInfo<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>;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_referenda::WeightInfo<Runtime>;
}
+118 -516
View File
@@ -3,6 +3,7 @@ pub use asset_config::AssetType;
pub mod governance;
pub mod xcm_config;
use asset_config::*;
#[cfg(feature = "async-backing")]
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
#[cfg(not(feature = "async-backing"))]
@@ -12,555 +13,156 @@ use frame_support::{
derive_impl,
dispatch::DispatchClass,
parameter_types,
traits::{ConstU32, ConstU64, Contains, EitherOfDiverse, InstanceFilter, TransformOrigin},
traits::{
AsEnsureOriginWithArg, ConstU128, ConstU16, ConstU32, ConstU64, Contains, EitherOf,
EitherOfDiverse, Everything, Nothing, TransformOrigin,
},
weights::{ConstantMultiplier, Weight},
PalletId,
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot,
EnsureRoot, EnsureRootWithSuccess, EnsureSigned,
};
pub use governance::origins::pallet_custom_origins;
use governance::{origins::Treasurer, TreasurySpender};
use governance::{origins::Treasurer, tracks, Spender, WhitelistedCaller};
use openzeppelin_polkadot_wrappers::{
impl_openzeppelin_assets, impl_openzeppelin_consensus, impl_openzeppelin_governance,
impl_openzeppelin_system, impl_openzeppelin_xcm, AssetsConfig, ConsensusConfig,
GovernanceConfig, SystemConfig, XcmConfig,
};
use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use scale_info::TypeInfo;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_runtime::{
traits::{AccountIdLookup, BlakeTwo256, IdentityLookup},
Perbill, Permill, RuntimeDebug,
};
use sp_version::RuntimeVersion;
use xcm::latest::{
prelude::{AssetId, BodyId},
InteriorLocation,
Junction::PalletInstance,
Perbill,
};
use xcm::latest::{prelude::*, InteriorLocation};
#[cfg(not(feature = "runtime-benchmarks"))]
use xcm_builder::ProcessXcmMessage;
use xcm_config::{RelayLocation, XcmOriginToTransactDispatchOrigin};
use xcm_builder::{
AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom,
DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds,
FrameTransactionalProcessor, TakeWeightCredit, TrailingSetTopicAsId, WithComputedOrigin,
WithUniqueTopic,
};
use xcm_config::*;
use xcm_executor::XcmExecutor;
use xcm_primitives::{AbsoluteAndRelativeReserve, AsAssetType};
#[cfg(feature = "runtime-benchmarks")]
use crate::benchmark::{OpenHrmpChannel, PayWithEnsure};
use crate::{
constants::{
currency::{deposit, CENTS, EXISTENTIAL_DEPOSIT, GRAND, MICROCENTS},
currency::{deposit, CENTS, EXISTENTIAL_DEPOSIT, MICROCENTS},
AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MAX_BLOCK_LENGTH,
NORMAL_DISPATCH_RATIO, SLOT_DURATION, VERSION,
NORMAL_DISPATCH_RATIO,
},
types::{
AccountId, AssetKind, Balance, Beneficiary, Block, BlockNumber,
CollatorSelectionUpdateOrigin, ConsensusHook, Hash, Nonce,
PriceForSiblingParachainDelivery, TreasuryPaymaster,
AccountId, AssetId, AssetKind, Balance, Beneficiary, Block, BlockNumber,
CollatorSelectionUpdateOrigin, ConsensusHook, Hash, MessageQueueServiceWeight, Nonce,
PriceForSiblingParachainDelivery, ProxyType, TreasuryAccount, TreasuryInteriorLocation,
TreasuryPalletId, TreasuryPaymaster, Version,
},
weights::{self, BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
Aura, Balances, CollatorSelection, MessageQueue, OriginCaller, PalletInfo, ParachainSystem,
Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeFreezeReason, RuntimeHoldReason,
RuntimeOrigin, RuntimeTask, Session, SessionKeys, System, Treasury, WeightToFee, XcmpQueue,
AllPalletsWithSystem, AssetManager, Aura, Balances, CollatorSelection, MessageQueue,
OriginCaller, PalletInfo, ParachainInfo, ParachainSystem, PolkadotXcm, Preimage, Referenda,
Runtime, RuntimeCall, RuntimeEvent, RuntimeFreezeReason, RuntimeHoldReason, RuntimeOrigin,
RuntimeTask, Scheduler, Session, SessionKeys, System, Treasury, 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();
// generic substrate prefix. For more info, see: [Polkadot Accounts In-Depth](https://wiki.polkadot.network/docs/learn-account-advanced#:~:text=The%20address%20format%20used%20in,belonging%20to%20a%20specific%20network)
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/polkadot-sdk/blob/v1.9.0-rc2/substrate/frame/proxy/src/lib.rs#L260
RuntimeCall::Proxy(method) => !matches!(
method,
pallet_proxy::Call::create_pure { .. }
| pallet_proxy::Call::kill_pure { .. }
| pallet_proxy::Call::remove_proxies { .. }
),
_ => 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.
// OpenZeppelin runtime wrappers configuration
pub struct OpenZeppelinRuntime;
impl SystemConfig for OpenZeppelinRuntime {
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 ExistentialDeposit = ConstU128<EXISTENTIAL_DEPOSIT>;
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 PreimageOrigin = EnsureRoot<AccountId>;
type ProxyType = ProxyType;
type SS58Prefix = ConstU16<42>;
type ScheduleOrigin = EnsureRoot<AccountId>;
type Version = Version;
}
parameter_types! {
pub MaximumSchedulerWeight: frame_support::weights::Weight = Perbill::from_percent(80) *
RuntimeBlockWeights::get().max_block;
pub const MaxScheduledRuntimeCallsPerBlock: u32 = 50;
impl ConsensusConfig for OpenZeppelinRuntime {
type CollatorSelectionUpdateOrigin = CollatorSelectionUpdateOrigin;
}
impl pallet_scheduler::Config for Runtime {
type MaxScheduledPerBlock = MaxScheduledRuntimeCallsPerBlock;
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>;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
impl GovernanceConfig for OpenZeppelinRuntime {
type ConvictionVoteLockingPeriod = ConstU32<{ 7 * DAYS }>;
type DispatchWhitelistedOrigin = EitherOf<EnsureRoot<AccountId>, WhitelistedCaller>;
type ReferendaAlarmInterval = ConstU32<1>;
type ReferendaCancelOrigin = EnsureRoot<AccountId>;
type ReferendaKillOrigin = EnsureRoot<AccountId>;
type ReferendaSlash = Treasury;
type ReferendaSubmissionDeposit = ConstU128<{ 3 * CENTS }>;
type ReferendaSubmitOrigin = EnsureSigned<AccountId>;
type ReferendaUndecidingTimeout = ConstU32<{ 14 * DAYS }>;
type TreasuryInteriorLocation = TreasuryInteriorLocation;
type TreasuryPalletId = TreasuryPalletId;
type TreasuryPayoutSpendPeriod = ConstU32<{ 30 * DAYS }>;
type TreasuryRejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
type TreasurySpendOrigin = TreasurySpender;
type TreasurySpendPeriod = ConstU32<{ 6 * DAYS }>;
type WhitelistOrigin = EnsureRoot<AccountId>;
}
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 XcmConfig for OpenZeppelinRuntime {
type AccountIdToLocation = AccountIdToLocation;
type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
type AssetFeesFilter = AssetFeesFilter;
type AssetTransactors = AssetTransactors;
type BaseXcmWeight = BaseXcmWeight;
type CurrencyId = CurrencyId;
type CurrencyIdToLocation = CurrencyIdToLocation<AsAssetType<AssetId, AssetType, AssetManager>>;
type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
type FeeManager = FeeManager;
type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
type HrmpOpenOrigin = EnsureRoot<AccountId>;
type LocalOriginToLocation = LocalOriginToLocation;
type LocationToAccountId = LocationToAccountId;
type MaxAssetsForTransfer = MaxAssetsForTransfer;
type MaxHrmpRelayFee = MaxHrmpRelayFee;
type MessageQueueHeapSize = ConstU32<{ 64 * 1024 }>;
type MessageQueueMaxStale = ConstU32<8>;
type MessageQueueServiceWeight = MessageQueueServiceWeight;
type ParachainMinFee = ParachainMinFee;
type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
type RelayLocation = RelayLocation;
type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
type Reserves = Reserves;
type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
type SelfLocation = SelfLocation;
type SelfReserve = SelfReserve;
type SovereignAccountDispatcherOrigin = EnsureRoot<AccountId>;
type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
type TransactorReserveProvider = AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
type Transactors = Transactors;
type UniversalLocation = UniversalLocation;
type WeightToFee = WeightToFee;
type XcmAdminOrigin = EnsureRoot<AccountId>;
type XcmFeesAccount = TreasuryAccount;
type XcmOriginToTransactDispatchOrigin = XcmOriginToTransactDispatchOrigin;
type XcmSender = XcmRouter;
type XcmWeigher = XcmWeigher;
type XcmpQueueControllerOrigin = EnsureRoot<AccountId>;
type XcmpQueueMaxInboundSuspended = ConstU32<1000>;
type XtokensReserveProviders = ReserveProviders;
}
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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
}
impl pallet_timestamp::Config for Runtime {
type MinimumPeriod = ConstU64<0>;
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_timestamp::WeightInfo<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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_proxy::WeightInfo<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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_balances::WeightInfo<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 {
/// There are two possible mechanisms available: slow and fast adjusting.
/// With slow adjusting fees stay almost constant in short periods of time, changing only in long term.
/// It may lead to long inclusion times during spikes, therefore tipping is enabled.
/// With fast adjusting fees change rapidly, but fixed for all users at each block (no tipping)
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type RuntimeEvent = RuntimeEvent;
impl AssetsConfig for OpenZeppelinRuntime {
type ApprovalDeposit = ConstU128<EXISTENTIAL_DEPOSIT>;
type AssetAccountDeposit = ConstU128<{ deposit(1, 16) }>;
type AssetDeposit = ConstU128<{ 10 * CENTS }>;
type AssetId = AssetId;
type AssetRegistrar = AssetRegistrar;
type AssetRegistrarMetadata = AssetRegistrarMetadata;
type AssetType = AssetType;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type ForceOrigin = EnsureRoot<AccountId>;
type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
type WeightToFee = WeightToFee;
}
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_sudo::WeightInfo<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>;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
}
impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
pub const MaxInboundSuspended: u32 = 1000;
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = AssetId(RelayLocation::get());
/// The base fee for the message delivery fees. Kusama is based for the reference.
pub const ToSiblingBaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ChannelInfo = ParachainSystem;
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type MaxActiveOutboundChannels = ConstU32<128>;
type MaxInboundSuspended = MaxInboundSuspended;
type MaxPageSize = ConstU32<{ 1 << 16 }>;
/// Ensure that this value is not set to null (or NoPriceForMessageDelivery) to prevent spamming
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
type RuntimeEvent = RuntimeEvent;
type VersionWrapper = ();
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
}
parameter_types! {
// pallet_session ends the session after a fixed period of blocks.
// The first session will have length of Offset,
// and the following sessions will have length of Period.
// This may prove nonsensical if Offset >= Period.
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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_session::WeightInfo<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;
type SlotDuration = ConstU64<SLOT_DURATION>;
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const SessionLength: BlockNumber = 6 * HOURS;
// StakingAdmin pluralistic body.
pub const StakingAdminBodyId: BodyId = BodyId::Defense;
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;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_collator_selection::WeightInfo<Runtime>;
}
impl pallet_utility::Config for Runtime {
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
}
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub LocationParents: u8 = 1;
pub BenchmarkParaId: u8 = 0;
}
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);
pub const ProposalBondMinimum: Balance = 2 * GRAND;
pub const ProposalBondMaximum: Balance = 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;
pub TreasuryAccount: AccountId = Treasury::account_id();
}
impl pallet_treasury::Config for Runtime {
type AssetKind = AssetKind;
type BalanceConverter = frame_support::traits::tokens::UnityAssetBalanceConversion;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments<
LocationParents,
BenchmarkParaId,
>;
type Beneficiary = Beneficiary;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Burn = ();
type BurnDestination = ();
type Currency = Balances;
type MaxApprovals = MaxApprovals;
type PalletId = TreasuryPalletId;
#[cfg(feature = "runtime-benchmarks")]
type Paymaster = PayWithEnsure<TreasuryPaymaster, OpenHrmpChannel<BenchmarkParaId>>;
#[cfg(not(feature = "runtime-benchmarks"))]
type Paymaster = TreasuryPaymaster;
type PayoutPeriod = PayoutSpendPeriod;
type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
type RuntimeEvent = RuntimeEvent;
type SpendFunds = ();
type SpendOrigin = TreasurySpender;
type SpendPeriod = SpendPeriod;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}
impl_openzeppelin_system!(OpenZeppelinRuntime);
impl_openzeppelin_consensus!(OpenZeppelinRuntime);
impl_openzeppelin_governance!(OpenZeppelinRuntime);
impl_openzeppelin_xcm!(OpenZeppelinRuntime);
impl_openzeppelin_assets!(OpenZeppelinRuntime);
@@ -1,12 +1,10 @@
use core::marker::PhantomData;
use frame_support::{
pallet_prelude::Get,
parameter_types,
traits::{ConstU32, Contains, ContainsPair, Everything, Nothing, PalletInfoAccess},
traits::{ContainsPair, Get, PalletInfoAccess},
weights::Weight,
};
use frame_system::EnsureRoot;
use orml_traits::{location::Reserve, parameter_type_with_key};
use orml_xcm_support::MultiNativeAsset;
use pallet_xcm::XcmPassthrough;
@@ -14,37 +12,30 @@ use parity_scale_codec::{Decode, Encode};
use polkadot_parachain_primitives::primitives::{self, Sibling};
use scale_info::TypeInfo;
use sp_runtime::{traits::Convert, Vec};
use xcm::latest::prelude::*;
use xcm::latest::{prelude::*, Junction::PalletInstance};
use xcm_builder::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, Case,
DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds,
FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsChildSystemParachain,
IsConcrete, NoChecking, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, WithComputedOrigin,
WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount,
AccountId32Aliases, Case, FixedWeightBounds, FungibleAdapter, FungiblesAdapter,
IsChildSystemParachain, IsConcrete, NoChecking, ParentIsPreset, RelayChainAsNative,
SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation, WithUniqueTopic, XcmFeeManagerFromComponents,
XcmFeeToAccount,
};
use xcm_executor::XcmExecutor;
use xcm_primitives::{
AbsoluteAndRelativeReserve, AsAssetType, UtilityAvailableCalls, UtilityEncodeCall, XcmTransact,
AbsoluteAndRelativeReserve, UtilityAvailableCalls, UtilityEncodeCall, XcmTransact,
};
use super::TreasuryAccount;
use crate::{
configs::{
weights, AssetType, Balances, ParachainSystem, Runtime, RuntimeCall, RuntimeEvent,
RuntimeOrigin, XcmpQueue,
},
types::{AccountId, AssetId, Balance},
AllPalletsWithSystem, AssetManager, Assets, ParachainInfo, PolkadotXcm,
configs::{MaxInstructions, ParachainSystem, Runtime, RuntimeCall, UnitWeightCost, XcmpQueue},
types::{AccountId, AssetId, Balance, TreasuryAccount},
Assets, Balances, ParachainInfo, PolkadotXcm, RuntimeOrigin,
};
parameter_types! {
pub const RelayNetwork: Option<NetworkId> = None;
pub PlaceholderAccount: AccountId = PolkadotXcm::check_account();
pub const RelayNetwork: Option<NetworkId> = None;
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
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();
// Self Reserve location, defines the multilocation identifiying the self-reserve currency
// This is used to match it also against our Balances pallet when we receive such
@@ -58,10 +49,6 @@ parameter_types! {
};
}
/// `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
@@ -89,6 +76,10 @@ pub type LocalAssetTransactor = FungibleAdapter<
(),
>;
/// `AssetId/Balancer` converter for `TrustBackedAssets`
pub type TrustBackedAssetsConvertedConcreteId =
assets_common::TrustBackedAssetsConvertedConcreteId<AssetsPalletLocation, Balance>;
/// Means for transacting assets besides the native currency on this chain.
pub type LocalFungiblesTransactor = FungiblesAdapter<
// Use this fungibles implementation:
@@ -131,36 +122,9 @@ pub type XcmOriginToTransactDispatchOrigin = (
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 type FeeManager = XcmFeeManagerFromComponents<
IsChildSystemParachain<primitives::Id>,
XcmFeeToAccount<AssetTransactors, AccountId, TreasuryAccount>,
>;
/// Matches foreign assets from a given origin.
@@ -194,7 +158,7 @@ parameter_types! {
);
}
type Reserves = (
pub type Reserves = (
// Assets bridged from different consensus systems held in reserve on Asset Hub.
IsBridgedConcreteAssetFrom<AssetHubLocation>,
// Relaychain (DOT) from Asset Hub
@@ -205,46 +169,6 @@ type Reserves = (
pub type XcmWeigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
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;
/// When changing this config, keep in mind, that you should collect fees.
type FeeManager = XcmFeeManagerFromComponents<
IsChildSystemParachain<primitives::Id>,
XcmFeeToAccount<Self::AssetTransactor, AccountId, TreasuryAccount>,
>;
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type HrmpNewChannelOpenRequestHandler = ();
/// Please, keep these two configs (`IsReserve` and `IsTeleporter`) mutually exclusive
type IsReserve = Reserves;
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 = pallet_xcm_weight_trader::Trader<Runtime>;
type TransactionalProcessor = FrameTransactionalProcessor;
type UniversalAliases = Nothing;
// Teleporting is disabled.
type UniversalLocation = UniversalLocation;
type Weigher = XcmWeigher;
type XcmRecorder = PolkadotXcm;
type XcmSender = XcmRouter;
}
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -262,44 +186,6 @@ parameter_types! {
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 = MaxRemoteLockConsumers;
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 = XcmWeigher;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_xcm::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type XcmExecuteFilter = Everything;
#[cfg(not(feature = "runtime-benchmarks"))]
type XcmExecuteFilter = Nothing;
// Needs to be `Everything` for local testing.
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmReserveTransferFilter = Everything;
type XcmRouter = XcmRouter;
type XcmTeleportFilter = Nothing;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
}
impl cumulus_pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(200_000_000u64, 0);
pub const MaxAssetsForTransfer: usize = 2;
@@ -439,25 +325,6 @@ impl Reserve for ReserveProviders {
}
}
impl orml_xtokens::Config for Runtime {
type AccountIdToLocation = AccountIdToLocation;
type Balance = Balance;
type BaseXcmWeight = BaseXcmWeight;
type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdToLocation<AsAssetType<AssetId, AssetType, AssetManager>>;
type LocationsFilter = Everything;
type MaxAssetsForTransfer = MaxAssetsForTransfer;
type MinXcmFee = ParachainMinFee;
type RateLimiter = ();
type RateLimiterId = ();
type ReserveProvider = ReserveProviders;
type RuntimeEvent = RuntimeEvent;
type SelfLocation = SelfLocation;
type UniversalLocation = UniversalLocation;
type Weigher = XcmWeigher;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
pub struct AssetFeesFilter;
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
fn contains(location: &Location) -> bool {
@@ -466,32 +333,6 @@ impl frame_support::traits::Contains<Location> for AssetFeesFilter {
}
}
// implement your own business logic for who can add/edit/remove/resume supported assets
pub type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
pub type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
pub type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
pub type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
impl pallet_xcm_weight_trader::Config for Runtime {
type AccountIdToLocation = AccountIdToLocation;
type AddSupportedAssetOrigin = AddSupportedAssetOrigin;
type AssetLocationFilter = AssetFeesFilter;
type AssetTransactor = AssetTransactors;
type Balance = Balance;
type EditSupportedAssetOrigin = EditSupportedAssetOrigin;
type NativeLocation = SelfReserve;
#[cfg(feature = "runtime-benchmarks")]
type NotFilteredLocation = RelayLocation;
type PauseSupportedAssetOrigin = EditSupportedAssetOrigin;
type RemoveSupportedAssetOrigin = RemoveSupportedAssetOrigin;
type ResumeSupportedAssetOrigin = ResumeSupportedAssetOrigin;
type RuntimeEvent = RuntimeEvent;
// TODO: update this when we update benchmarks
type WeightInfo = weights::pallet_xcm_weight_trader::WeightInfo<Runtime>;
type WeightToFee = <Runtime as pallet_transaction_payment::Config>::WeightToFee;
type XcmFeesAccount = TreasuryAccount;
}
// For now we only allow to transact in the relay, although this might change in the future
// Transactors just defines the chains in which we allow transactions to be issued through
// xcm
@@ -542,34 +383,6 @@ parameter_types! {
pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
}
// implement your own business logic for who can manage and use xcm-transactor
pub type DerivativeAddressRegistrationOrigin = EnsureRoot<AccountId>;
pub type HrmpManipulatorOrigin = EnsureRoot<AccountId>;
pub type HrmpOpenOrigin = EnsureRoot<AccountId>;
pub type SovereignAccountDispatcherOrigin = EnsureRoot<AccountId>;
impl pallet_xcm_transactor::Config for Runtime {
type AccountIdToLocation = AccountIdToLocation;
type AssetTransactor = AssetTransactors;
type Balance = Balance;
type BaseXcmWeight = BaseXcmWeight;
type CurrencyId = CurrencyId;
type CurrencyIdToLocation = CurrencyIdToLocation<AsAssetType<AssetId, AssetType, AssetManager>>;
type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin;
type HrmpManipulatorOrigin = HrmpManipulatorOrigin;
type HrmpOpenOrigin = HrmpOpenOrigin;
type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
type ReserveProvider = AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
type RuntimeEvent = RuntimeEvent;
type SelfLocation = SelfLocation;
type SovereignAccountDispatcherOrigin = SovereignAccountDispatcherOrigin;
type Transactor = Transactors;
type UniversalLocation = UniversalLocation;
type Weigher = XcmWeigher;
type WeightInfo = weights::pallet_xcm_transactor::WeightInfo<Runtime>;
type XcmSender = XcmRouter;
}
#[cfg(feature = "runtime-benchmarks")]
mod testing {
use sp_runtime::traits::MaybeEquivalence;
+75 -7
View File
@@ -1,21 +1,33 @@
use frame_support::traits::EitherOfDiverse;
use frame_support::{
parameter_types,
traits::{EitherOfDiverse, InstanceFilter},
weights::Weight,
PalletId,
};
use frame_system::EnsureRoot;
use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use polkadot_runtime_common::impls::{
LocatableAssetConverter, VersionedLocatableAsset, VersionedLocationConverter,
};
use scale_info::TypeInfo;
use sp_core::ConstU32;
use sp_runtime::{
generic,
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiAddress, MultiSignature,
MultiAddress, MultiSignature, Perbill, RuntimeDebug,
};
use sp_version::RuntimeVersion;
use xcm::{
latest::{InteriorLocation, Junction::PalletInstance},
VersionedLocation,
};
use xcm::VersionedLocation;
use xcm_builder::PayOverXcm;
use crate::{
configs::{xcm_config, TreasuryInteriorLocation},
constants::HOURS,
configs::XcmRouter,
constants::{HOURS, VERSION},
Treasury,
};
pub use crate::{
configs::{
@@ -25,7 +37,7 @@ pub use crate::{
constants::{
BLOCK_PROCESSING_VELOCITY, RELAY_CHAIN_SLOT_DURATION_MILLIS, UNINCLUDED_SEGMENT_CAPACITY,
},
AllPalletsWithSystem, Runtime, RuntimeCall, XcmpQueue,
AllPalletsWithSystem, Runtime, RuntimeBlockWeights, RuntimeCall, XcmpQueue,
};
/// Alias to 512-bit hash when used in the context of a transaction signature on
@@ -117,7 +129,7 @@ pub type AssetKind = VersionedLocatableAsset;
/// This is a type that describes how we should transfer bounties from treasury pallet
pub type TreasuryPaymaster = PayOverXcm<
TreasuryInteriorLocation,
xcm_config::XcmRouter,
XcmRouter,
crate::PolkadotXcm,
ConstU32<{ 6 * HOURS }>,
Beneficiary,
@@ -125,3 +137,59 @@ pub type TreasuryPaymaster = PayOverXcm<
LocatableAssetConverter,
VersionedLocationConverter,
>;
/// 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 { .. })
}
}
}
}
// Getter types used in OpenZeppelinRuntime configuration
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub TreasuryAccount: AccountId = Treasury::account_id();
// 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 MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
}