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::{H160, H256};
use sp_runtime::traits::Hash as THash;
@@ -13,21 +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;
@@ -41,31 +27,6 @@ pallet_assets::runtime_benchmarks_enabled! {
}
}
// 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 +75,14 @@ impl From<AssetType> for AssetId {
}
}
#[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;
@@ -165,26 +134,6 @@ impl pallet_asset_manager::AssetRegistrar<Runtime> for AssetRegistrar {
}
}
#[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
@@ -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>;
}
+127 -587
View File
@@ -1,650 +1,190 @@
pub mod asset_config;
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"))]
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use cumulus_primitives_core::{AggregateMessageOrigin, AssetId, ParaId};
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
use frame_support::{
derive_impl,
dispatch::DispatchClass,
parameter_types,
traits::{
ConstU32, ConstU64, Contains, EitherOfDiverse, FindAuthor, InstanceFilter, TransformOrigin,
AsEnsureOriginWithArg, ConstU128, ConstU16, ConstU32, ConstU64, Contains, EitherOf,
EitherOfDiverse, Everything, FindAuthor, 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_evm,
impl_openzeppelin_governance, impl_openzeppelin_system, impl_openzeppelin_xcm, AssetsConfig,
ConsensusConfig, EvmConfig, GovernanceConfig, SystemConfig, XcmConfig,
};
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 parity_scale_codec::{Decode, Encode};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use scale_info::TypeInfo;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{H160, U256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
ConsensusEngineId, Perbill, Permill, RuntimeDebug,
ConsensusEngineId, Perbill, Permill,
};
use sp_std::marker::PhantomData;
use sp_version::RuntimeVersion;
// XCM Imports
use xcm::latest::{prelude::BodyId, InteriorLocation, Junction::PalletInstance};
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, AccountIdToLocation, 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, MILLICENTS},
AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MAX_BLOCK_LENGTH,
NORMAL_DISPATCH_RATIO, SLOT_DURATION, VERSION, WEIGHT_PER_GAS,
NORMAL_DISPATCH_RATIO, WEIGHT_PER_GAS,
},
opaque,
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,
PrecompilesValue, PriceForSiblingParachainDelivery, ProxyType, TreasuryInteriorLocation,
TreasuryPalletId, TreasuryPaymaster, Version,
},
weights::{self, BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
Aura, Balances, BaseFee, CollatorSelection, EVMChainId, MessageQueue, OpenZeppelinPrecompiles,
OriginCaller, PalletInfo, ParachainSystem, Preimage, Runtime, RuntimeCall, RuntimeEvent,
RuntimeFreezeReason, RuntimeHoldReason, RuntimeOrigin, RuntimeTask, Session, SessionKeys,
System, Timestamp, Treasury, UncheckedExtrinsic, WeightToFee, XcmpQueue,
AllPalletsWithSystem, AssetManager, Aura, Balances, BaseFee, CollatorSelection, EVMChainId,
Erc20XcmBridge, MessageQueue, OpenZeppelinPrecompiles, OriginCaller, PalletInfo, ParachainInfo,
ParachainSystem, PolkadotXcm, Preimage, Referenda, Runtime, RuntimeCall, RuntimeEvent,
RuntimeFreezeReason, RuntimeHoldReason, RuntimeOrigin, RuntimeTask, Scheduler, 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();
// 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 Lookup = sp_runtime::traits::IdentityLookup<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 ExistentialDeposit = ConstU128<EXISTENTIAL_DEPOSIT>;
type Lookup = IdentityLookup<AccountId>;
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 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 XcmConfig for OpenZeppelinRuntime {
type AccountIdToLocation = AccountIdToLocation<AccountId>;
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_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;
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>;
}
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();
}
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub LocationParents: u8 = 1;
pub BenchmarkParaId: u8 = 0;
}
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>;
}
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! {
/// Block gas limit is calculated with target for 75% of block capacity and ratio of maximum block weight and weight per gas
pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
/// To calculate ratio of Gas Limit to PoV size we take the BlockGasLimit we calculated before, and divide it on MAX_POV_SIZE
pub GasLimitPovSizeRatio: u64 = BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64);
pub PrecompilesValue: OpenZeppelinPrecompiles<Runtime> = OpenZeppelinPrecompiles::<_>::new();
pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
pub SuicideQuickClearLimit: u32 = 0;
}
impl pallet_evm::Config for Runtime {
impl EvmConfig for OpenZeppelinRuntime {
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 Erc20XcmBridgeTransferGasLimit = Erc20XcmBridgeTransferGasLimit;
type FindAuthor = FindAuthorSession<Aura>;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type OnChargeTransaction = EVMCurrencyAdapter<Balances, ()>;
type OnCreate = ();
type PrecompilesType = OpenZeppelinPrecompiles<Self>;
type LocationToH160 = LocationToH160;
type PrecompilesType = OpenZeppelinPrecompiles<Runtime>;
type PrecompilesValue = PrecompilesValue;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type RuntimeEvent = RuntimeEvent;
type SuicideQuickClearLimit = SuicideQuickClearLimit;
type Timestamp = Timestamp;
/// Rerun benchmarks if you are making changes to runtime configuration.
type WeightInfo = weights::pallet_evm::WeightInfo<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;
impl AssetsConfig for OpenZeppelinRuntime {
type ApprovalDeposit = ConstU128<MILLICENTS>;
type AssetAccountDeposit = ConstU128<{ deposit(1, 16) }>;
type AssetDeposit = ConstU128<{ 10 * CENTS }>;
type AssetId = AssetId;
type AssetRegistrar = AssetRegistrar;
type AssetRegistrarMetadata = AssetRegistrarMetadata;
type AssetType = AssetType;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = BenchmarkHelper;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type ForceOrigin = EnsureRoot<AccountId>;
type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
type WeightToFee = WeightToFee;
}
impl_openzeppelin_assets!(OpenZeppelinRuntime);
impl_openzeppelin_system!(OpenZeppelinRuntime);
impl_openzeppelin_consensus!(OpenZeppelinRuntime);
impl_openzeppelin_governance!(OpenZeppelinRuntime);
impl_openzeppelin_xcm!(OpenZeppelinRuntime);
impl_openzeppelin_evm!(OpenZeppelinRuntime);
pub struct FindAuthorSession<F>(PhantomData<F>);
impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorSession<F> {
+16 -185
View File
@@ -2,10 +2,9 @@ use core::marker::PhantomData;
use frame_support::{
parameter_types,
traits::{ConstU32, Contains, ContainsPair, Everything, Nothing, PalletInfoAccess},
traits::{ConstU32, Contains, ContainsPair, Everything, 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;
@@ -17,29 +16,21 @@ use sp_runtime::Vec;
use xcm::latest::prelude::{Assets as XcmAssets, *};
use xcm_builder::{
AccountKey20Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, Case,
ConvertedConcreteId, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin,
FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, HandleFee,
IsChildSystemParachain, IsConcrete, NoChecking, ParentIsPreset, RelayChainAsNative,
SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountKey20AsNative,
SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, WithComputedOrigin,
WithUniqueTopic, XcmFeeManagerFromComponents,
};
use xcm_executor::{
traits::{ConvertLocation, FeeReason, JustTry, TransactAsset},
XcmExecutor,
ConvertedConcreteId, DenyReserveTransferToRelayChain, DenyThenTry, FixedWeightBounds,
FungibleAdapter, FungiblesAdapter, HandleFee, IsChildSystemParachain, IsConcrete, NoChecking,
ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
SignedAccountKey20AsNative, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
};
use xcm_executor::traits::{ConvertLocation, FeeReason, JustTry, TransactAsset};
use xcm_primitives::{
AbsoluteAndRelativeReserve, AccountIdToLocation, AsAssetType, UtilityAvailableCalls,
UtilityEncodeCall, XcmTransact,
AbsoluteAndRelativeReserve, AsAssetType, UtilityAvailableCalls, UtilityEncodeCall, XcmTransact,
};
use crate::{
configs::{
AssetType, ParachainSystem, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, XcmpQueue,
},
configs::{AssetType, ParachainSystem, Runtime, RuntimeCall, RuntimeOrigin, XcmpQueue},
types::{AccountId, AssetId, Balance},
weights, AllPalletsWithSystem, AssetManager, Assets, Balances, Erc20XcmBridge, ParachainInfo,
PolkadotXcm, Treasury,
AssetManager, Assets, Balances, Erc20XcmBridge, ParachainInfo, Treasury,
};
parameter_types! {
@@ -236,7 +227,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
@@ -249,50 +240,13 @@ parameter_types! {
pub TreasuryAccount: AccountId = Treasury::account_id();
}
/// If you change this config, keep in mind that you should define how you collect fees.
pub type FeeManager = XcmFeeManagerFromComponents<
IsChildSystemParachain<primitives::Id>,
XcmFeeToAccount<AssetTransactors, AccountId, TreasuryAccount>,
>;
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 = pallet_erc20_xcm_bridge::AssetTrapWrapper<PolkadotXcm, Runtime>;
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.
/// The IsReserve type must be set to specify which <MultiAsset, MultiLocation> pair we trust to deposit reserve assets on our chain. We can also use the unit type () to block ReserveAssetDeposited instructions.
/// The IsTeleporter type must be set to specify which <MultiAsset, MultiLocation> pair we trust to teleport assets to our chain. We can also use the unit type () to block ReceiveTeleportedAssets instruction.
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;
}
use frame_support::{pallet_prelude::Get, traits::OriginTrait};
use sp_runtime::traits::TryConvert;
@@ -328,49 +282,6 @@ pub type XcmRouter = WithUniqueTopic<(
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 = 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>;
}
// We are not using all of these below atm, but we will need them when configuring `orml_xtokens`
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(200_000_000u64, 0);
@@ -463,13 +374,6 @@ parameter_types! {
pub Erc20XcmBridgeTransferGasLimit: u64 = 800_000;
}
impl pallet_erc20_xcm_bridge::Config for Runtime {
type AccountIdConverter = LocationToH160;
type Erc20MultilocationPrefix = Erc20XcmBridgePalletLocation;
type Erc20TransferGasLimit = Erc20XcmBridgeTransferGasLimit;
type EvmRunner = pallet_evm::runner::stack::Runner<Self>;
}
/// The `DOTReserveProvider` overrides the default reserve location for DOT (Polkadot's native token).
///
/// DOT can exist in multiple locations, and this provider ensures that the reserve is correctly set
@@ -539,25 +443,6 @@ impl Reserve for ReserveProviders {
}
}
impl orml_xtokens::Config for Runtime {
type AccountIdToLocation = AccountIdToLocation<AccountId>;
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 {
@@ -566,32 +451,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<AccountId>;
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
@@ -642,34 +501,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<AccountId>;
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;
+1 -1
View File
@@ -35,7 +35,7 @@ where
a if a == hash(3) => Some(Ripemd160::execute(handle)),
a if a == hash(4) => Some(Identity::execute(handle)),
a if a == hash(5) => Some(Modexp::execute(handle)),
// Non-Frontier specific nor Ethereum precompiles :
// Frontier precompiles :
a if a == hash(1024) => Some(Sha3FIPS256::execute(handle)),
a if a == hash(1025) => Some(ECRecoverPublicKey::execute(handle)),
_ => None,
+78 -8
View File
@@ -1,31 +1,44 @@
use fp_account::EthereumSignature;
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},
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},
configs::{
xcm_config::{self, RelayLocation},
FeeAssetId, StakingAdminBodyId, ToSiblingBaseDeliveryFee, TransactionByteFee,
},
constants::HOURS,
};
pub use crate::{
configs::{
xcm_config::RelayLocation, FeeAssetId, StakingAdminBodyId, ToSiblingBaseDeliveryFee,
TransactionByteFee,
},
constants::{
BLOCK_PROCESSING_VELOCITY, RELAY_CHAIN_SLOT_DURATION_MILLIS, UNINCLUDED_SEGMENT_CAPACITY,
VERSION,
},
AllPalletsWithSystem, Runtime, RuntimeCall, XcmpQueue,
AllPalletsWithSystem, OpenZeppelinPrecompiles, Runtime, RuntimeBlockWeights, RuntimeCall,
Treasury, XcmpQueue,
};
/// Unchecked extrinsic type as expected by this runtime.
@@ -123,3 +136,60 @@ 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;
pub PrecompilesValue: OpenZeppelinPrecompiles<Runtime> = OpenZeppelinPrecompiles::<_>::new();
}