diff --git a/evm-template/Cargo.lock b/evm-template/Cargo.lock index e0e3066..933169c 100644 --- a/evm-template/Cargo.lock +++ b/evm-template/Cargo.lock @@ -3008,6 +3008,7 @@ dependencies = [ "frame-try-runtime", "hex-literal", "log", + "openzeppelin-polkadot-wrappers", "orml-traits", "orml-xcm-support", "orml-xtokens", @@ -6831,6 +6832,18 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "openzeppelin-polkadot-wrappers" +version = "0.1.0" +source = "git+http://github.com/openzeppelin/polkadot-runtime-wrappers?tag=v0.1-rc1#92a8d332b70202b5699106aefb6a42fe1b896794" +dependencies = [ + "cumulus-primitives-core", + "frame-support", + "scale-info", + "sp-std", + "sp-version", +] + [[package]] name = "option-ext" version = "0.2.0" diff --git a/evm-template/Cargo.toml b/evm-template/Cargo.toml index 8c6d31a..4d0def4 100644 --- a/evm-template/Cargo.toml +++ b/evm-template/Cargo.toml @@ -27,6 +27,8 @@ serde_derive = { version = "1.0.121", default-features = false } serde_json = "1.0.121" smallvec = "1.11.0" +openzeppelin-polkadot-wrappers = { git = "http://github.com/openzeppelin/polkadot-runtime-wrappers", default-features = false, tag = "v0.1-rc1" } + # Substrate frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-stable2407-1" } frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-stable2407-1" } diff --git a/evm-template/runtime/Cargo.toml b/evm-template/runtime/Cargo.toml index e23b5e6..cc29327 100644 --- a/evm-template/runtime/Cargo.toml +++ b/evm-template/runtime/Cargo.toml @@ -17,6 +17,8 @@ parity-scale-codec = { workspace = true, features = [ "derive" ] } scale-info = { workspace = true, features = [ "derive" ] } smallvec = { workspace = true } +openzeppelin-polkadot-wrappers = { workspace = true } + # Substrate frame-benchmarking = { workspace = true, optional = true } frame-executive = { workspace = true } @@ -141,6 +143,7 @@ std = [ "frame-system/std", "frame-try-runtime?/std", "log/std", + "openzeppelin-polkadot-wrappers/std", "orml-xtokens/std", "pallet-asset-manager/std", "pallet-assets/std", diff --git a/evm-template/runtime/src/configs/asset_config.rs b/evm-template/runtime/src/configs/asset_config.rs index 6404bc7..f8c2ae0 100644 --- a/evm-template/runtime/src/configs/asset_config.rs +++ b/evm-template/runtime/src/configs/asset_config.rs @@ -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; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = BenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - 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; -} - // 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 for AssetId { } } +#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] +pub struct AssetRegistrarMetadata { + pub name: Vec, + pub symbol: Vec, + 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 for AssetRegistrar { } } -#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] -pub struct AssetRegistrarMetadata { - pub name: Vec, - pub symbol: Vec, - 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; - type ForeignAssetType = AssetType; - type RuntimeEvent = RuntimeEvent; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_asset_manager::WeightInfo; -} - /// This trait ensure we can convert AccountIds to AssetIds. pub trait AccountIdAssetIdConversion { // Get assetId and prefix from account diff --git a/evm-template/runtime/src/configs/governance/mod.rs b/evm-template/runtime/src/configs/governance/mod.rs index 85712be..4d05cdd 100644 --- a/evm-template/runtime/src/configs/governance/mod.rs +++ b/evm-template/runtime/src/configs/governance/mod.rs @@ -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; - 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; -} - -parameter_types! { - pub const MaxBalance: Balance = Balance::MAX; -} -pub type TreasurySpender = EitherOf, Spender>; - -impl origins::pallet_custom_origins::Config for Runtime {} - -impl pallet_whitelist::Config for Runtime { - type DispatchWhitelistedOrigin = EitherOf, 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; - type WhitelistOrigin = EnsureRoot; -} - -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; - type Currency = Balances; - type KillOrigin = EnsureRoot; - 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; - type Tally = pallet_conviction_voting::TallyOf; - type Tracks = tracks::TracksInfo; - type UndecidingTimeout = UndecidingTimeout; - type Votes = pallet_conviction_voting::VotesOf; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_referenda::WeightInfo; -} diff --git a/evm-template/runtime/src/configs/mod.rs b/evm-template/runtime/src/configs/mod.rs index 25acbb0..eaaf502 100644 --- a/evm-template/runtime/src/configs/mod.rs +++ b/evm-template/runtime/src/configs/mod.rs @@ -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 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; - /// 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; - /// 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; - /// 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; + type Lookup = IdentityLookup; + type PreimageOrigin = EnsureRoot; + type ProxyType = ProxyType; + type SS58Prefix = ConstU16<42>; + type ScheduleOrigin = EnsureRoot; 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; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_scheduler::WeightInfo; +impl GovernanceConfig for OpenZeppelinRuntime { + type ConvictionVoteLockingPeriod = ConstU32<{ 7 * DAYS }>; + type DispatchWhitelistedOrigin = EitherOf, WhitelistedCaller>; + type ReferendaAlarmInterval = ConstU32<1>; + type ReferendaCancelOrigin = EnsureRoot; + type ReferendaKillOrigin = EnsureRoot; + type ReferendaSlash = Treasury; + type ReferendaSubmissionDeposit = ConstU128<{ 3 * CENTS }>; + type ReferendaSubmitOrigin = EnsureSigned; + type ReferendaUndecidingTimeout = ConstU32<{ 14 * DAYS }>; + type TreasuryInteriorLocation = TreasuryInteriorLocation; + type TreasuryPalletId = TreasuryPalletId; + type TreasuryPayoutSpendPeriod = ConstU32<{ 30 * DAYS }>; + type TreasuryRejectOrigin = EitherOfDiverse, Treasurer>; + type TreasurySpendOrigin = TreasurySpender; + type TreasurySpendPeriod = ConstU32<{ 6 * DAYS }>; + type WhitelistOrigin = EnsureRoot; } - -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; - type RuntimeEvent = RuntimeEvent; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_preimage::WeightInfo; -} - -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; -} - -impl pallet_authorship::Config for Runtime { - type EventHandler = (CollatorSelection,); - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; -} - -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 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; -} - -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; -} - -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; - type LengthToFee = ConstantMultiplier; - type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter; - type OperationalFeeMultiplier = OperationalFeeMultiplier; - type RuntimeEvent = RuntimeEvent; +impl XcmConfig for OpenZeppelinRuntime { + type AccountIdToLocation = AccountIdToLocation; + type AddSupportedAssetOrigin = EnsureRoot; + type AssetFeesFilter = AssetFeesFilter; + type AssetTransactors = AssetTransactors; + type BaseXcmWeight = BaseXcmWeight; + type CurrencyId = CurrencyId; + type CurrencyIdToLocation = CurrencyIdToLocation>; + type DerivativeAddressRegistrationOrigin = EnsureRoot; + type EditSupportedAssetOrigin = EnsureRoot; + type FeeManager = FeeManager; + type HrmpManipulatorOrigin = EnsureRoot; + type HrmpOpenOrigin = EnsureRoot; + 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; + type RelayLocation = RelayLocation; + type RemoveSupportedAssetOrigin = EnsureRoot; + type Reserves = Reserves; + type ResumeSupportedAssetOrigin = EnsureRoot; + type SelfLocation = SelfLocation; + type SelfReserve = SelfReserve; + type SovereignAccountDispatcherOrigin = EnsureRoot; + type Trader = pallet_xcm_weight_trader::Trader; + type TransactorReserveProvider = AbsoluteAndRelativeReserve; + type Transactors = Transactors; + type UniversalLocation = UniversalLocation; type WeightToFee = WeightToFee; + type XcmAdminOrigin = EnsureRoot; + type XcmFeesAccount = TreasuryAccount; + type XcmOriginToTransactDispatchOrigin = XcmOriginToTransactDispatchOrigin; + type XcmSender = XcmRouter; + type XcmWeigher = XcmWeigher; + type XcmpQueueControllerOrigin = EnsureRoot; + 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; -} - -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; - type OnSystemEvent = (); - type OutboundXcmpMessageSource = XcmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type ReservedXcmpWeight = ReservedXcmpWeight; - type RuntimeEvent = RuntimeEvent; - type SelfParaId = parachain_info::Pallet; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; - 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, - RuntimeCall, - >; - // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: - type QueueChangeHandler = NarrowOriginToSibling; - type QueuePausedQuery = NarrowOriginToSibling; - 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; -} - -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; - 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; - // Enqueue XCMP messages from siblings for later processing. - type XcmpQueue = TransformOrigin; -} - -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; -} - -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; - type RuntimeEvent = RuntimeEvent; - // Essentially just Aura, but let's be pedantic. - type SessionHandler = ::KeyTypeIdProviders; - type SessionManager = CollatorSelection; - type ShouldEndSession = pallet_session::PeriodicSessions; - type ValidatorId = ::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; -} - -#[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; -} - -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 = ::AccountId; - type ValidatorIdOf = pallet_collator_selection::IdentityCollator; - type ValidatorRegistration = Session; - type WeightInfo = weights::pallet_collator_selection::WeightInfo; -} - -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; -} - -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; - type Burn = (); - type BurnDestination = (); - type Currency = Balances; - type MaxApprovals = MaxApprovals; - type PalletId = TreasuryPalletId; - #[cfg(feature = "runtime-benchmarks")] - type Paymaster = PayWithEnsure>; - #[cfg(not(feature = "runtime-benchmarks"))] - type Paymaster = TreasuryPaymaster; - type PayoutPeriod = PayoutSpendPeriod; - type RejectOrigin = EitherOfDiverse, 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; -} - -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; -} - -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 = 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; type CallOrigin = EnsureAccountId20; - type ChainId = EVMChainId; - type Currency = Balances; - type FeeCalculator = BaseFee; + type Erc20XcmBridgeTransferGasLimit = Erc20XcmBridgeTransferGasLimit; type FindAuthor = FindAuthorSession; - type GasLimitPovSizeRatio = GasLimitPovSizeRatio; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type OnChargeTransaction = EVMCurrencyAdapter; - type OnCreate = (); - type PrecompilesType = OpenZeppelinPrecompiles; + type LocationToH160 = LocationToH160; + type PrecompilesType = OpenZeppelinPrecompiles; type PrecompilesValue = PrecompilesValue; - type Runner = pallet_evm::runner::stack::Runner; - 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; - 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; + 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>; + type ForceOrigin = EnsureRoot; + type ForeignAssetModifierOrigin = EnsureRoot; + 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(PhantomData); impl> FindAuthor for FindAuthorSession { diff --git a/evm-template/runtime/src/configs/xcm_config.rs b/evm-template/runtime/src/configs/xcm_config.rs index 090fc9d..153996c 100644 --- a/evm-template/runtime/src/configs/xcm_config.rs +++ b/evm-template/runtime/src/configs/xcm_config.rs @@ -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, // 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, + XcmFeeToAccount, +>; pub type XcmWeigher = FixedWeightBounds; -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; - type Barrier = Barrier; - type CallDispatcher = RuntimeCall; - /// When changing this config, keep in mind, that you should collect fees. - type FeeManager = XcmFeeManagerFromComponents< - IsChildSystemParachain, - XcmFeeToAccount, - >; - 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 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 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; - 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; - // ^ Override for AdvertisedXcmVersion default - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; - type Currency = Balances; - type CurrencyMatcher = (); - type ExecuteXcmOrigin = EnsureXcmOrigin; - type MaxLockers = MaxLockers; - type MaxRemoteLockConsumers = MaxRemoteLockConsumers; - type RemoteLockConsumerIdentifier = (); - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type SendXcmOrigin = EnsureXcmOrigin; - 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; - #[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; - 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; -} - // 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; -} - /// 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; - type Balance = Balance; - type BaseXcmWeight = BaseXcmWeight; - type CurrencyId = CurrencyId; - type CurrencyIdConvert = CurrencyIdToLocation>; - 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; -} - pub struct AssetFeesFilter; impl frame_support::traits::Contains for AssetFeesFilter { fn contains(location: &Location) -> bool { @@ -566,32 +451,6 @@ impl frame_support::traits::Contains for AssetFeesFilter { } } -// implement your own business logic for who can add/edit/remove/resume supported assets -pub type AddSupportedAssetOrigin = EnsureRoot; -pub type EditSupportedAssetOrigin = EnsureRoot; -pub type RemoveSupportedAssetOrigin = EnsureRoot; -pub type ResumeSupportedAssetOrigin = EnsureRoot; - -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; - type WeightToFee = ::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; -pub type HrmpManipulatorOrigin = EnsureRoot; -pub type HrmpOpenOrigin = EnsureRoot; -pub type SovereignAccountDispatcherOrigin = EnsureRoot; - -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>; - type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin; - type HrmpManipulatorOrigin = HrmpManipulatorOrigin; - type HrmpOpenOrigin = HrmpOpenOrigin; - type MaxHrmpFee = xcm_builder::Case; - type ReserveProvider = AbsoluteAndRelativeReserve; - 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; - type XcmSender = XcmRouter; -} - #[cfg(feature = "runtime-benchmarks")] mod testing { use sp_runtime::traits::MaybeEquivalence; diff --git a/evm-template/runtime/src/precompiles.rs b/evm-template/runtime/src/precompiles.rs index 24f8199..046a38c 100644 --- a/evm-template/runtime/src/precompiles.rs +++ b/evm-template/runtime/src/precompiles.rs @@ -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, diff --git a/evm-template/runtime/src/types.rs b/evm-template/runtime/src/types.rs index 5115224..113fb67 100644 --- a/evm-template/runtime/src/types.rs +++ b/evm-template/runtime/src/types.rs @@ -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 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 = OpenZeppelinPrecompiles::<_>::new(); +} diff --git a/evm-template/template-fuzzer/src/main.rs b/evm-template/template-fuzzer/src/main.rs index d4d2537..14d1236 100644 --- a/evm-template/template-fuzzer/src/main.rs +++ b/evm-template/template-fuzzer/src/main.rs @@ -5,13 +5,12 @@ use std::{ // Local Imports use evm_runtime_template::{ - configs::MaxCandidates, constants::SLOT_DURATION, AccountId, AllPalletsWithSystem, Balance, - Balances, EVMChainIdConfig, Executive, Runtime, RuntimeCall, RuntimeOrigin, SudoConfig, - UncheckedExtrinsic, + constants::SLOT_DURATION, AccountId, AllPalletsWithSystem, Balance, Balances, EVMChainIdConfig, + Executive, Runtime, RuntimeCall, RuntimeOrigin, SudoConfig, UncheckedExtrinsic, }; use frame_support::{ dispatch::GetDispatchInfo, - traits::{IntegrityTest, TryState, TryStateSelect}, + traits::{Get, IntegrityTest, TryState, TryStateSelect}, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, }; use frame_system::Account; @@ -264,7 +263,9 @@ fn recursive_call_filter(call: &RuntimeCall, origin: usize) -> bool { ) => false, RuntimeCall::CollatorSelection( pallet_collator_selection::Call::set_desired_candidates { max }, - ) => *max < MaxCandidates::get(), + ) => + *max < <::MaxCandidates as Get>::get( + ), RuntimeCall::Balances(pallet_balances::Call::force_adjust_total_issuance { .. }) => false, _ => true, diff --git a/generic-template/Cargo.lock b/generic-template/Cargo.lock index 1daa7a2..3d2dd34 100644 --- a/generic-template/Cargo.lock +++ b/generic-template/Cargo.lock @@ -3635,6 +3635,7 @@ dependencies = [ "frame-try-runtime", "hex-literal", "log", + "openzeppelin-polkadot-wrappers", "orml-traits", "orml-xcm-support", "orml-xtokens", @@ -6344,6 +6345,18 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "openzeppelin-polkadot-wrappers" +version = "0.1.0" +source = "git+http://github.com/openzeppelin/polkadot-runtime-wrappers?tag=v0.1-rc1#92a8d332b70202b5699106aefb6a42fe1b896794" +dependencies = [ + "cumulus-primitives-core", + "frame-support", + "scale-info", + "sp-std", + "sp-version", +] + [[package]] name = "option-ext" version = "0.2.0" diff --git a/generic-template/Cargo.toml b/generic-template/Cargo.toml index 21645ce..b445300 100644 --- a/generic-template/Cargo.toml +++ b/generic-template/Cargo.toml @@ -25,6 +25,8 @@ serde = { version = "1.0.197", default-features = false } serde_json = "1.0.121" smallvec = "1.11.0" +openzeppelin-polkadot-wrappers = { git = "http://github.com/openzeppelin/polkadot-runtime-wrappers", default-features = false, tag = "v0.1-rc1" } + # Substrate frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-stable2407-1" } frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-stable2407-1" } diff --git a/generic-template/runtime/Cargo.toml b/generic-template/runtime/Cargo.toml index f7fe344..8167cfb 100644 --- a/generic-template/runtime/Cargo.toml +++ b/generic-template/runtime/Cargo.toml @@ -17,6 +17,8 @@ parity-scale-codec = { workspace = true, features = [ "derive" ] } scale-info = { workspace = true, features = [ "derive" ] } smallvec = { workspace = true } +openzeppelin-polkadot-wrappers = { workspace = true } + # Substrate frame-benchmarking = { workspace = true, optional = true } frame-executive = { workspace = true } @@ -120,6 +122,7 @@ std = [ "frame-system/std", "frame-try-runtime?/std", "log/std", + "openzeppelin-polkadot-wrappers/std", "orml-xtokens/std", "pallet-asset-manager/std", "pallet-assets/std", diff --git a/generic-template/runtime/src/configs/asset_config.rs b/generic-template/runtime/src/configs/asset_config.rs index e71c707..65b9886 100644 --- a/generic-template/runtime/src/configs/asset_config.rs +++ b/generic-template/runtime/src/configs/asset_config.rs @@ -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 pallet_assets::BenchmarkHelper for BenchmarkHelper - where - AssetIdParameter: From, - { - 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; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = BenchmarkHelper; - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - 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; -} - // 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 for AssetId { } } +/// This trait ensure we can convert AccountIds to AssetIds. +pub trait AccountIdAssetIdConversion { + // Get assetId and prefix from account + fn account_to_asset_id(account: Account) -> Option<(Vec, 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 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, 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, + pub symbol: Vec, + 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 for AssetRegistrar { .weight } } - -#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] -pub struct AssetRegistrarMetadata { - pub name: Vec, - pub symbol: Vec, - 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; - type ForeignAssetType = AssetType; - type RuntimeEvent = RuntimeEvent; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_asset_manager::WeightInfo; -} - -/// This trait ensure we can convert AccountIds to AssetIds. -pub trait AccountIdAssetIdConversion { - // Get assetId and prefix from account - fn account_to_asset_id(account: Account) -> Option<(Vec, 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 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, 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) - } -} diff --git a/generic-template/runtime/src/configs/governance/mod.rs b/generic-template/runtime/src/configs/governance/mod.rs index 85712be..4d05cdd 100644 --- a/generic-template/runtime/src/configs/governance/mod.rs +++ b/generic-template/runtime/src/configs/governance/mod.rs @@ -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; - 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; -} - -parameter_types! { - pub const MaxBalance: Balance = Balance::MAX; -} -pub type TreasurySpender = EitherOf, Spender>; - -impl origins::pallet_custom_origins::Config for Runtime {} - -impl pallet_whitelist::Config for Runtime { - type DispatchWhitelistedOrigin = EitherOf, 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; - type WhitelistOrigin = EnsureRoot; -} - -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; - type Currency = Balances; - type KillOrigin = EnsureRoot; - 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; - type Tally = pallet_conviction_voting::TallyOf; - type Tracks = tracks::TracksInfo; - type UndecidingTimeout = UndecidingTimeout; - type Votes = pallet_conviction_voting::VotesOf; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_referenda::WeightInfo; -} diff --git a/generic-template/runtime/src/configs/mod.rs b/generic-template/runtime/src/configs/mod.rs index f94b866..fa18510 100644 --- a/generic-template/runtime/src/configs/mod.rs +++ b/generic-template/runtime/src/configs/mod.rs @@ -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 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; - /// 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; type Lookup = AccountIdLookup; - /// 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; - /// 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; + type ProxyType = ProxyType; + type SS58Prefix = ConstU16<42>; + type ScheduleOrigin = EnsureRoot; 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; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_scheduler::WeightInfo; +impl GovernanceConfig for OpenZeppelinRuntime { + type ConvictionVoteLockingPeriod = ConstU32<{ 7 * DAYS }>; + type DispatchWhitelistedOrigin = EitherOf, WhitelistedCaller>; + type ReferendaAlarmInterval = ConstU32<1>; + type ReferendaCancelOrigin = EnsureRoot; + type ReferendaKillOrigin = EnsureRoot; + type ReferendaSlash = Treasury; + type ReferendaSubmissionDeposit = ConstU128<{ 3 * CENTS }>; + type ReferendaSubmitOrigin = EnsureSigned; + type ReferendaUndecidingTimeout = ConstU32<{ 14 * DAYS }>; + type TreasuryInteriorLocation = TreasuryInteriorLocation; + type TreasuryPalletId = TreasuryPalletId; + type TreasuryPayoutSpendPeriod = ConstU32<{ 30 * DAYS }>; + type TreasuryRejectOrigin = EitherOfDiverse, Treasurer>; + type TreasurySpendOrigin = TreasurySpender; + type TreasurySpendPeriod = ConstU32<{ 6 * DAYS }>; + type WhitelistOrigin = EnsureRoot; } - -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; + type AssetFeesFilter = AssetFeesFilter; + type AssetTransactors = AssetTransactors; + type BaseXcmWeight = BaseXcmWeight; + type CurrencyId = CurrencyId; + type CurrencyIdToLocation = CurrencyIdToLocation>; + type DerivativeAddressRegistrationOrigin = EnsureRoot; + type EditSupportedAssetOrigin = EnsureRoot; + type FeeManager = FeeManager; + type HrmpManipulatorOrigin = EnsureRoot; + type HrmpOpenOrigin = EnsureRoot; + 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; + type RelayLocation = RelayLocation; + type RemoveSupportedAssetOrigin = EnsureRoot; + type Reserves = Reserves; + type ResumeSupportedAssetOrigin = EnsureRoot; + type SelfLocation = SelfLocation; + type SelfReserve = SelfReserve; + type SovereignAccountDispatcherOrigin = EnsureRoot; + type Trader = pallet_xcm_weight_trader::Trader; + type TransactorReserveProvider = AbsoluteAndRelativeReserve; + type Transactors = Transactors; + type UniversalLocation = UniversalLocation; + type WeightToFee = WeightToFee; + type XcmAdminOrigin = EnsureRoot; + type XcmFeesAccount = TreasuryAccount; + type XcmOriginToTransactDispatchOrigin = XcmOriginToTransactDispatchOrigin; + type XcmSender = XcmRouter; + type XcmWeigher = XcmWeigher; + type XcmpQueueControllerOrigin = EnsureRoot; + 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; - type RuntimeEvent = RuntimeEvent; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::pallet_preimage::WeightInfo; -} - -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; -} - -impl pallet_authorship::Config for Runtime { - type EventHandler = (CollatorSelection,); - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; -} - -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 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; -} - -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; -} - -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; - type LengthToFee = ConstantMultiplier; - type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter; - type OperationalFeeMultiplier = OperationalFeeMultiplier; - type RuntimeEvent = RuntimeEvent; +impl AssetsConfig for OpenZeppelinRuntime { + type ApprovalDeposit = ConstU128; + 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>; + type ForceOrigin = EnsureRoot; + type ForeignAssetModifierOrigin = EnsureRoot; 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; -} - -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; - type OnSystemEvent = (); - type OutboundXcmpMessageSource = XcmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type ReservedXcmpWeight = ReservedXcmpWeight; - type RuntimeEvent = RuntimeEvent; - type SelfParaId = parachain_info::Pallet; - /// Rerun benchmarks if you are making changes to runtime configuration. - type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; - 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, - RuntimeCall, - >; - // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: - type QueueChangeHandler = NarrowOriginToSibling; - type QueuePausedQuery = NarrowOriginToSibling; - 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; -} - -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; - 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; - // Enqueue XCMP messages from siblings for later processing. - type XcmpQueue = TransformOrigin; -} - -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; -} - -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; - type RuntimeEvent = RuntimeEvent; - // Essentially just Aura, but let's be pedantic. - type SessionHandler = ::KeyTypeIdProviders; - type SessionManager = CollatorSelection; - type ShouldEndSession = pallet_session::PeriodicSessions; - type ValidatorId = ::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; -} - -#[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; -} - -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 = ::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; -} - -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; -} - -#[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; - type Burn = (); - type BurnDestination = (); - type Currency = Balances; - type MaxApprovals = MaxApprovals; - type PalletId = TreasuryPalletId; - #[cfg(feature = "runtime-benchmarks")] - type Paymaster = PayWithEnsure>; - #[cfg(not(feature = "runtime-benchmarks"))] - type Paymaster = TreasuryPaymaster; - type PayoutPeriod = PayoutSpendPeriod; - type RejectOrigin = EitherOfDiverse, 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; -} +impl_openzeppelin_system!(OpenZeppelinRuntime); +impl_openzeppelin_consensus!(OpenZeppelinRuntime); +impl_openzeppelin_governance!(OpenZeppelinRuntime); +impl_openzeppelin_xcm!(OpenZeppelinRuntime); +impl_openzeppelin_assets!(OpenZeppelinRuntime); diff --git a/generic-template/runtime/src/configs/xcm_config.rs b/generic-template/runtime/src/configs/xcm_config.rs index 6d480ba..d8c08e3 100644 --- a/generic-template/runtime/src/configs/xcm_config.rs +++ b/generic-template/runtime/src/configs/xcm_config.rs @@ -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 = None; pub PlaceholderAccount: AccountId = PolkadotXcm::check_account(); + pub const RelayNetwork: Option = None; + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub AssetsPalletLocation: Location = PalletInstance(::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; - /// 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; + /// 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, ); -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 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, - AllowExplicitUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution - ), - UniversalLocation, - ConstU32<8>, - >, - ), - >, +pub type FeeManager = XcmFeeManagerFromComponents< + IsChildSystemParachain, + XcmFeeToAccount, >; /// 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, // Relaychain (DOT) from Asset Hub @@ -205,46 +169,6 @@ type Reserves = ( pub type XcmWeigher = FixedWeightBounds; -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, - XcmFeeToAccount, - >; - 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; - 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; @@ -262,44 +186,6 @@ parameter_types! { pub const MaxRemoteLockConsumers: u32 = 0; } -impl pallet_xcm::Config for Runtime { - type AdminOrigin = EnsureRoot; - // ^ Override for AdvertisedXcmVersion default - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; - type Currency = Balances; - type CurrencyMatcher = (); - type ExecuteXcmOrigin = EnsureXcmOrigin; - type MaxLockers = MaxLockers; - type MaxRemoteLockConsumers = MaxRemoteLockConsumers; - type RemoteLockConsumerIdentifier = (); - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type SendXcmOrigin = EnsureXcmOrigin; - 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; - #[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; - 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; -} - 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>; - 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; -} - pub struct AssetFeesFilter; impl frame_support::traits::Contains for AssetFeesFilter { fn contains(location: &Location) -> bool { @@ -466,32 +333,6 @@ impl frame_support::traits::Contains for AssetFeesFilter { } } -// implement your own business logic for who can add/edit/remove/resume supported assets -pub type AddSupportedAssetOrigin = EnsureRoot; -pub type EditSupportedAssetOrigin = EnsureRoot; -pub type RemoveSupportedAssetOrigin = EnsureRoot; -pub type ResumeSupportedAssetOrigin = EnsureRoot; - -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; - type WeightToFee = ::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; -pub type HrmpManipulatorOrigin = EnsureRoot; -pub type HrmpOpenOrigin = EnsureRoot; -pub type SovereignAccountDispatcherOrigin = EnsureRoot; - -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>; - type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin; - type HrmpManipulatorOrigin = HrmpManipulatorOrigin; - type HrmpOpenOrigin = HrmpOpenOrigin; - type MaxHrmpFee = xcm_builder::Case; - type ReserveProvider = AbsoluteAndRelativeReserve; - 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; - type XcmSender = XcmRouter; -} - #[cfg(feature = "runtime-benchmarks")] mod testing { use sp_runtime::traits::MaybeEquivalence; diff --git a/generic-template/runtime/src/types.rs b/generic-template/runtime/src/types.rs index 048233e..ac31594 100644 --- a/generic-template/runtime/src/types.rs +++ b/generic-template/runtime/src/types.rs @@ -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 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; +} diff --git a/generic-template/runtime/tests/constants_test.rs b/generic-template/runtime/tests/constants_test.rs index d366f22..a0bc660 100644 --- a/generic-template/runtime/tests/constants_test.rs +++ b/generic-template/runtime/tests/constants_test.rs @@ -197,7 +197,7 @@ mod runtime_tests { #[cfg(feature = "async-backing")] assert!(AllowMultipleBlocksPerSlot::get()); - assert_eq!(MaxAuthorities::get(), 100_000); + assert_eq!(::MaxAuthorities::get(), 100_000); } #[test] @@ -212,17 +212,17 @@ mod runtime_tests { assert_eq!(StakingAdminBodyId::get(), BodyId::Defense); - assert_eq!(MaxCandidates::get(), 100); + assert_eq!(::MaxCandidates::get(), 100); - assert_eq!(MaxInvulnerables::get(), 20); + assert_eq!(::MaxInvulnerables::get(), 20); - assert_eq!(MinEligibleCollators::get(), 4); + assert_eq!(::MinEligibleCollators::get(), 4); } } mod xcm_tests { use frame_support::weights::Weight; - use generic_runtime_template::configs::xcm_config::*; + use generic_runtime_template::configs::*; #[test] fn xcm_executor_constants() { diff --git a/generic-template/template-fuzzer/src/main.rs b/generic-template/template-fuzzer/src/main.rs index af68787..417fcb9 100644 --- a/generic-template/template-fuzzer/src/main.rs +++ b/generic-template/template-fuzzer/src/main.rs @@ -5,14 +5,14 @@ use std::{ use frame_support::{ dispatch::GetDispatchInfo, - traits::{IntegrityTest, TryState, TryStateSelect}, + traits::{Get, IntegrityTest, TryState, TryStateSelect}, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, }; use frame_system::Account; // Local Imports use generic_runtime_template::{ - configs::MaxCandidates, constants::SLOT_DURATION, AllPalletsWithSystem, Balance, Balances, - Executive, Runtime, RuntimeCall, RuntimeOrigin, SudoConfig, UncheckedExtrinsic, + constants::SLOT_DURATION, AllPalletsWithSystem, Balance, Balances, Executive, Runtime, + RuntimeCall, RuntimeOrigin, SudoConfig, UncheckedExtrinsic, }; use pallet_balances::{Holds, TotalIssuance}; use parachains_common::AccountId; @@ -296,7 +296,7 @@ fn recursive_call_filter(call: &RuntimeCall, origin: usize) -> bool { ) => false, RuntimeCall::CollatorSelection( pallet_collator_selection::Call::set_desired_candidates { max }, - ) => *max < MaxCandidates::get(), + ) => *max < ::MaxCandidates::get(), RuntimeCall::Balances(pallet_balances::Call::force_adjust_total_issuance { .. }) => false, _ => true,