12345678910111213141516171819#![cfg_attr(not(feature = "std"), no_std)]2021#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]2425#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31use fp_self_contained::*;32use sp_runtime::traits::{SignedExtension, Member};33343536use sp_runtime::{37 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,38 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},39 transaction_validity::{TransactionSource, TransactionValidity},40 ApplyExtrinsicResult, RuntimeAppPublic,41};4243use sp_std::prelude::*;4445#[cfg(feature = "std")]46use sp_version::NativeVersion;47use sp_version::RuntimeVersion;48pub use pallet_transaction_payment::{49 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,50};5152pub use pallet_balances::Call as BalancesCall;53pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};54pub use frame_support::{55 construct_runtime, match_type,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, PrivilegeCmp,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,67 },68};69use pallet_unq_scheduler::DispatchCall;70use up_data_structs::*;717273use frame_system::{74 self as frame_system, EnsureRoot, EnsureSigned,75 limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78 traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use scale_info::TypeInfo;82use codec::{Encode, Decode};83use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};84use fp_rpc::TransactionStatus;85use sp_runtime::{86 traits::{87 Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,88 CheckedConversion,89 },90 generic::Era,91 transaction_validity::TransactionValidityError,92 DispatchErrorWithPostInfo, SaturatedConversion,93};949596pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;979899use pallet_xcm::XcmPassthrough;100use polkadot_parachain::primitives::Sibling;101use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};102use xcm_builder::{103 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,104 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,105 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,106 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,107 ParentIsPreset,108};109use xcm_executor::{Config, XcmExecutor, Assets};110use sp_std::{cmp::Ordering, marker::PhantomData};111112use xcm::latest::{113 114 AssetId::{Concrete},115 Fungibility::Fungible as XcmFungible,116 MultiAsset,117 Error as XcmError,118};119use xcm_executor::traits::{MatchesFungible, WeightTrader};120121122use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};123124pub const RUNTIME_NAME: &str = "Opal";125126type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;127128impl RuntimeInstance for Runtime {129 type CrossAccountId = self::CrossAccountId;130131 type TransactionConverter = self::TransactionConverter;132133 fn get_transaction_converter() -> TransactionConverter {134 TransactionConverter135 }136}137138139140141142pub mod opaque {143 use sp_std::prelude::*;144 use sp_runtime::impl_opaque_keys;145 use super::Aura;146147 pub use unique_runtime_common::types::*;148149 impl_opaque_keys! {150 pub struct SessionKeys {151 pub aura: Aura,152 }153 }154}155156157pub const VERSION: RuntimeVersion = RuntimeVersion {158 spec_name: create_runtime_str!(RUNTIME_NAME),159 impl_name: create_runtime_str!(RUNTIME_NAME),160 authoring_version: 1,161 spec_version: 917004,162 impl_version: 0,163 apis: RUNTIME_API_VERSIONS,164 transaction_version: 1,165 state_version: 0,166};167168#[derive(codec::Encode, codec::Decode)]169pub enum XCMPMessage<XAccountId, XBalance> {170 171 TransferToken(XAccountId, XBalance),172}173174175#[cfg(feature = "std")]176pub fn native_version() -> NativeVersion {177 NativeVersion {178 runtime_version: VERSION,179 can_author_with: Default::default(),180 }181}182183type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;184185pub struct DealWithFees;186impl OnUnbalanced<NegativeImbalance> for DealWithFees {187 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {188 if let Some(fees) = fees_then_tips.next() {189 190 let mut split = fees.ration(100, 0);191 if let Some(tips) = fees_then_tips.next() {192 193 tips.ration_merge_into(100, 0, &mut split);194 }195 Treasury::on_unbalanced(split.0);196 197 }198 }199}200201parameter_types! {202 pub const BlockHashCount: BlockNumber = 2400;203 pub RuntimeBlockLength: BlockLength =204 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);205 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);206 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;207 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()208 .base_block(BlockExecutionWeight::get())209 .for_class(DispatchClass::all(), |weights| {210 weights.base_extrinsic = ExtrinsicBaseWeight::get();211 })212 .for_class(DispatchClass::Normal, |weights| {213 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);214 })215 .for_class(DispatchClass::Operational, |weights| {216 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);217 218 219 weights.reserved = Some(220 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT221 );222 })223 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)224 .build_or_panic();225 pub const Version: RuntimeVersion = VERSION;226 pub const SS58Prefix: u8 = 42;227}228229parameter_types! {230 pub const ChainId: u64 = 8882;231}232233pub struct FixedFee;234impl FeeCalculator for FixedFee {235 fn min_gas_price() -> U256 {236 MIN_GAS_PRICE.into()237 }238}239240241242243parameter_types! {244 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;245 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;246 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();247}248249250251252const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);253parameter_types! {254 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());255}256257pub enum FixedGasWeightMapping {}258impl GasWeightMapping for FixedGasWeightMapping {259 fn gas_to_weight(gas: u64) -> Weight {260 gas.saturating_mul(WeightPerGas::get())261 }262 fn weight_to_gas(weight: Weight) -> u64 {263 weight / WeightPerGas::get()264 }265}266267impl pallet_evm::Config for Runtime {268 type BlockGasLimit = BlockGasLimit;269 type FeeCalculator = FixedFee;270 type GasWeightMapping = FixedGasWeightMapping;271 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;272 type CallOrigin = EnsureAddressTruncated;273 type WithdrawOrigin = EnsureAddressTruncated;274 type AddressMapping = HashedAddressMapping<Self::Hashing>;275 type PrecompilesType = ();276 type PrecompilesValue = ();277 type Currency = Balances;278 type Event = Event;279 type OnMethodCall = (280 pallet_evm_migration::OnMethodCall<Self>,281 pallet_unique::UniqueErcSupport<Self>,282 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,283 );284 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;285 type ChainId = ChainId;286 type Runner = pallet_evm::runner::stack::Runner<Self>;287 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;288 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;289 type FindAuthor = EthereumFindAuthor<Aura>;290}291292impl pallet_evm_migration::Config for Runtime {293 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;294}295296pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);297impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {298 fn find_author<'a, I>(digests: I) -> Option<H160>299 where300 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,301 {302 if let Some(author_index) = F::find_author(digests) {303 let authority_id = Aura::authorities()[author_index as usize].clone();304 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));305 }306 None307 }308}309310impl pallet_ethereum::Config for Runtime {311 type Event = Event;312 type StateRoot = pallet_ethereum::IntermediateStateRoot;313}314315impl pallet_randomness_collective_flip::Config for Runtime {}316317impl frame_system::Config for Runtime {318 319 type AccountData = pallet_balances::AccountData<Balance>;320 321 type AccountId = AccountId;322 323 type BaseCallFilter = Everything;324 325 type BlockHashCount = BlockHashCount;326 327 type BlockLength = RuntimeBlockLength;328 329 type BlockNumber = BlockNumber;330 331 type BlockWeights = RuntimeBlockWeights;332 333 type Call = Call;334 335 type DbWeight = RocksDbWeight;336 337 type Event = Event;338 339 type Hash = Hash;340 341 type Hashing = BlakeTwo256;342 343 type Header = generic::Header<BlockNumber, BlakeTwo256>;344 345 type Index = Index;346 347 type Lookup = AccountIdLookup<AccountId, ()>;348 349 type OnKilledAccount = ();350 351 type OnNewAccount = ();352 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;353 354 type Origin = Origin;355 356 type PalletInfo = PalletInfo;357 358 type SS58Prefix = SS58Prefix;359 360 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;361 362 type Version = Version;363 type MaxConsumers = ConstU32<16>;364}365366parameter_types! {367 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;368}369370impl pallet_timestamp::Config for Runtime {371 372 type Moment = u64;373 type OnTimestampSet = ();374 type MinimumPeriod = MinimumPeriod;375 type WeightInfo = ();376}377378parameter_types! {379 380 pub const ExistentialDeposit: u128 = 0;381 pub const MaxLocks: u32 = 50;382 pub const MaxReserves: u32 = 50;383}384385impl pallet_balances::Config for Runtime {386 type MaxLocks = MaxLocks;387 type MaxReserves = MaxReserves;388 type ReserveIdentifier = [u8; 16];389 390 type Balance = Balance;391 392 type Event = Event;393 type DustRemoval = Treasury;394 type ExistentialDeposit = ExistentialDeposit;395 type AccountStore = System;396 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;397}398399pub const fn deposit(items: u32, bytes: u32) -> Balance {400 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE401}402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453parameter_types! {454 455 456 pub const OperationalFeeMultiplier: u8 = 5;457}458459460pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);461462impl<T> WeightToFeePolynomial for LinearFee<T>463where464 T: BaseArithmetic + From<u32> + Copy + Unsigned,465{466 type Balance = T;467468 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {469 smallvec!(WeightToFeeCoefficient {470 471 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),472 coeff_frac: Perbill::zero(),473 negative: false,474 degree: 1,475 })476 }477}478479impl pallet_transaction_payment::Config for Runtime {480 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;481 type TransactionByteFee = TransactionByteFee;482 type OperationalFeeMultiplier = OperationalFeeMultiplier;483 type WeightToFee = LinearFee<Balance>;484 type FeeMultiplierUpdate = ();485}486487parameter_types! {488 pub const ProposalBond: Permill = Permill::from_percent(5);489 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;490 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;491 pub const SpendPeriod: BlockNumber = 5 * MINUTES;492 pub const Burn: Permill = Permill::from_percent(0);493 pub const TipCountdown: BlockNumber = 1 * DAYS;494 pub const TipFindersFee: Percent = Percent::from_percent(20);495 pub const TipReportDepositBase: Balance = 1 * UNIQUE;496 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;497 pub const BountyDepositBase: Balance = 1 * UNIQUE;498 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;499 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");500 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;501 pub const MaximumReasonLength: u32 = 16384;502 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);503 pub const BountyValueMinimum: Balance = 5 * UNIQUE;504 pub const MaxApprovals: u32 = 100;505}506507impl pallet_treasury::Config for Runtime {508 type PalletId = TreasuryModuleId;509 type Currency = Balances;510 type ApproveOrigin = EnsureRoot<AccountId>;511 type RejectOrigin = EnsureRoot<AccountId>;512 type Event = Event;513 type OnSlash = ();514 type ProposalBond = ProposalBond;515 type ProposalBondMinimum = ProposalBondMinimum;516 type ProposalBondMaximum = ProposalBondMaximum;517 type SpendPeriod = SpendPeriod;518 type Burn = Burn;519 type BurnDestination = ();520 type SpendFunds = ();521 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;522 type MaxApprovals = MaxApprovals;523}524525impl pallet_sudo::Config for Runtime {526 type Event = Event;527 type Call = Call;528}529530pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);531532impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider533 for RelayChainBlockNumberProvider<T>534{535 type BlockNumber = BlockNumber;536537 fn current_block_number() -> Self::BlockNumber {538 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()539 .map(|d| d.relay_parent_number)540 .unwrap_or_default()541 }542}543544parameter_types! {545 pub const MinVestedTransfer: Balance = 10 * UNIQUE;546 pub const MaxVestingSchedules: u32 = 28;547}548549impl orml_vesting::Config for Runtime {550 type Event = Event;551 type Currency = pallet_balances::Pallet<Runtime>;552 type MinVestedTransfer = MinVestedTransfer;553 type VestedTransferOrigin = EnsureSigned<AccountId>;554 type WeightInfo = ();555 type MaxVestingSchedules = MaxVestingSchedules;556 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;557}558559parameter_types! {560 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;561 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562}563564impl cumulus_pallet_parachain_system::Config for Runtime {565 type Event = Event;566 type SelfParaId = parachain_info::Pallet<Self>;567 type OnSystemEvent = ();568 569 570 571 572 573 type OutboundXcmpMessageSource = XcmpQueue;574 type DmpMessageHandler = DmpQueue;575 type ReservedDmpWeight = ReservedDmpWeight;576 type ReservedXcmpWeight = ReservedXcmpWeight;577 type XcmpMessageHandler = XcmpQueue;578}579580impl parachain_info::Config for Runtime {}581582impl cumulus_pallet_aura_ext::Config for Runtime {}583584parameter_types! {585 pub const RelayLocation: MultiLocation = MultiLocation::parent();586 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;587 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();588 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();589}590591592593594pub type LocationToAccountId = (595 596 ParentIsPreset<AccountId>,597 598 SiblingParachainConvertsVia<Sibling, AccountId>,599 600 AccountId32Aliases<RelayNetwork, AccountId>,601);602603pub struct OnlySelfCurrency;604impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {605 fn matches_fungible(a: &MultiAsset) -> Option<B> {606 match (&a.id, &a.fun) {607 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),608 _ => None,609 }610 }611}612613614pub type LocalAssetTransactor = CurrencyAdapter<615 616 Balances,617 618 OnlySelfCurrency,619 620 LocationToAccountId,621 622 AccountId,623 624 (),625>;626627628629630pub type XcmOriginToTransactDispatchOrigin = (631 632 633 634 SovereignSignedViaLocation<LocationToAccountId, Origin>,635 636 637 RelayChainAsNative<RelayOrigin, Origin>,638 639 640 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,641 642 643 ParentAsSuperuser<Origin>,644 645 646 SignedAccountId32AsNative<RelayNetwork, Origin>,647 648 XcmPassthrough<Origin>,649);650651parameter_types! {652 653 pub UnitWeightCost: Weight = 1_000_000;654 655 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);656 pub const MaxInstructions: u32 = 100;657 pub const MaxAuthorities: u32 = 100_000;658}659660match_type! {661 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {662 MultiLocation { parents: 1, interior: Here } |663 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }664 };665}666667pub type Barrier = (668 TakeWeightCredit,669 AllowTopLevelPaidExecutionFrom<Everything>,670 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,671 672);673674pub struct UsingOnlySelfCurrencyComponents<675 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,676 AssetId: Get<MultiLocation>,677 AccountId,678 Currency: CurrencyT<AccountId>,679 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,680>(681 Weight,682 Currency::Balance,683 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,684);685impl<686 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,687 AssetId: Get<MultiLocation>,688 AccountId,689 Currency: CurrencyT<AccountId>,690 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,691 > WeightTrader692 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>693{694 fn new() -> Self {695 Self(0, Zero::zero(), PhantomData)696 }697698 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {699 let amount = WeightToFee::calc(&weight);700 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;701702 703 let option1: xcm::v1::AssetId = Concrete(MultiLocation {704 parents: 1,705 interior: X1(Parachain(ParachainInfo::parachain_id().into())),706 });707 708 let option2: xcm::v1::AssetId = Concrete(MultiLocation {709 parents: 0,710 interior: Here,711 });712713 let required = if payment.fungible.contains_key(&option1) {714 (option1, u128_amount).into()715 } else if payment.fungible.contains_key(&option2) {716 (option2, u128_amount).into()717 } else {718 (Concrete(MultiLocation::default()), u128_amount).into()719 };720721 let unused = payment722 .checked_sub(required)723 .map_err(|_| XcmError::TooExpensive)?;724 self.0 = self.0.saturating_add(weight);725 self.1 = self.1.saturating_add(amount);726 Ok(unused)727 }728729 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {730 let weight = weight.min(self.0);731 let amount = WeightToFee::calc(&weight);732 self.0 -= weight;733 self.1 = self.1.saturating_sub(amount);734 let amount: u128 = amount.saturated_into();735 if amount > 0 {736 Some((AssetId::get(), amount).into())737 } else {738 None739 }740 }741}742impl<743 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,744 AssetId: Get<MultiLocation>,745 AccountId,746 Currency: CurrencyT<AccountId>,747 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,748 > Drop749 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>750{751 fn drop(&mut self) {752 OnUnbalanced::on_unbalanced(Currency::issue(self.1));753 }754}755756pub struct XcmConfig;757impl Config for XcmConfig {758 type Call = Call;759 type XcmSender = XcmRouter;760 761 type AssetTransactor = LocalAssetTransactor;762 type OriginConverter = XcmOriginToTransactDispatchOrigin;763 type IsReserve = NativeAsset;764 type IsTeleporter = (); 765 type LocationInverter = LocationInverter<Ancestry>;766 type Barrier = Barrier;767 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;768 type Trader = UsingOnlySelfCurrencyComponents<769 IdentityFee<Balance>,770 RelayLocation,771 AccountId,772 Balances,773 (),774 >;775 type ResponseHandler = (); 776 type SubscriptionService = PolkadotXcm;777778 type AssetTrap = PolkadotXcm;779 type AssetClaims = PolkadotXcm;780}781782783784785786787pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);788789790791pub type XcmRouter = (792 793 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,794 795 XcmpQueue,796);797798impl pallet_evm_coder_substrate::Config for Runtime {799 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;800 type GasWeightMapping = FixedGasWeightMapping;801}802803impl pallet_xcm::Config for Runtime {804 type Event = Event;805 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;806 type XcmRouter = XcmRouter;807 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;808 type XcmExecuteFilter = Everything;809 type XcmExecutor = XcmExecutor<XcmConfig>;810 type XcmTeleportFilter = Everything;811 type XcmReserveTransferFilter = Everything;812 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;813 type LocationInverter = LocationInverter<Ancestry>;814 type Origin = Origin;815 type Call = Call;816 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;817 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;818}819820impl cumulus_pallet_xcm::Config for Runtime {821 type Event = Event;822 type XcmExecutor = XcmExecutor<XcmConfig>;823}824825impl cumulus_pallet_xcmp_queue::Config for Runtime {826 type Event = Event;827 type XcmExecutor = XcmExecutor<XcmConfig>;828 type ChannelInfo = ParachainSystem;829 type VersionWrapper = ();830 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;831 type ControllerOrigin = EnsureRoot<AccountId>;832 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;833}834835impl cumulus_pallet_dmp_queue::Config for Runtime {836 type Event = Event;837 type XcmExecutor = XcmExecutor<XcmConfig>;838 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;839}840841impl pallet_aura::Config for Runtime {842 type AuthorityId = AuraId;843 type DisabledValidators = ();844 type MaxAuthorities = MaxAuthorities;845}846847parameter_types! {848 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();849 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;850}851852impl pallet_common::Config for Runtime {853 type Event = Event;854 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;855 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;856 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;857858 type Currency = Balances;859 type CollectionCreationPrice = CollectionCreationPrice;860 type TreasuryAccountId = TreasuryAccountId;861}862863impl pallet_fungible::Config for Runtime {864 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;865}866impl pallet_refungible::Config for Runtime {867 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;868}869impl pallet_nonfungible::Config for Runtime {870 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;871}872873impl pallet_unique::Config for Runtime {874 type Event = Event;875 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;876}877878parameter_types! {879 pub const InflationBlockInterval: BlockNumber = 100; 880}881882883impl pallet_inflation::Config for Runtime {884 type Currency = Balances;885 type TreasuryAccountId = TreasuryAccountId;886 type InflationBlockInterval = InflationBlockInterval;887 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;888}889890parameter_types! {891 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *892 RuntimeBlockWeights::get().max_block;893 pub const MaxScheduledPerBlock: u32 = 50;894}895896type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;897use frame_support::traits::NamedReservableCurrency;898899fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {900 (901 frame_system::CheckSpecVersion::<Runtime>::new(),902 frame_system::CheckGenesis::<Runtime>::new(),903 frame_system::CheckEra::<Runtime>::from(Era::Immortal),904 frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(905 from,906 )),907 frame_system::CheckWeight::<Runtime>::new(),908 pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),909 )910}911912pub struct SchedulerPaymentExecutor;913impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>914 DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor915where916 <T as frame_system::Config>::Call: Member917 + Dispatchable<Origin = Origin, Info = DispatchInfo>918 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>919 + GetDispatchInfo920 + From<frame_system::Call<Runtime>>,921 SelfContainedSignedInfo: Send + Sync + 'static,922 Call: From<<T as frame_system::Config>::Call>923 + From<<T as pallet_unq_scheduler::Config>::Call>924 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,925 sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,926{927 fn dispatch_call(928 signer: <T as frame_system::Config>::AccountId,929 call: <T as pallet_unq_scheduler::Config>::Call,930 ) -> Result<931 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,932 TransactionValidityError,933 > {934 let dispatch_info = call.get_dispatch_info();935 let extrinsic = fp_self_contained::CheckedExtrinsic::<936 AccountId,937 Call,938 SignedExtra,939 SelfContainedSignedInfo,940 > {941 signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(942 signer.clone().into(),943 get_signed_extras(signer.into()),944 ),945 function: call.into(),946 };947948 extrinsic.apply::<Runtime>(&dispatch_info, 0)949 }950951 fn reserve_balance(952 id: [u8; 16],953 sponsor: <T as frame_system::Config>::AccountId,954 call: <T as pallet_unq_scheduler::Config>::Call,955 count: u32,956 ) -> Result<(), DispatchError> {957 let dispatch_info = call.get_dispatch_info();958 let fee_charger = ChargeTransactionPayment::new(0);959 let pre = match fee_charger.pre_dispatch(960 &sponsor.clone().into(),961 &call.into(),962 &dispatch_info,963 0,964 ) {965 Ok(p) => p,966 Err(_) => fail!("failed to get pre dispatch info"),967 };968969 let count: u128 = count.into();970 let total_fee: u128 = pre.2.map(|imbalance| imbalance.peek()).unwrap() * count;971 <Balances as NamedReservableCurrency<AccountId>>::reserve_named(972 &id,973 &(sponsor.into()),974 total_fee,975 )976 }977978 fn pay_for_call(979 id: [u8; 16],980 sponsor: <T as frame_system::Config>::AccountId,981 call: <T as pallet_unq_scheduler::Config>::Call,982 ) -> Result<u128, DispatchError> {983 let dispatch_info = call.get_dispatch_info();984 let fee_charger = ChargeTransactionPayment::new(0);985 let pre = match fee_charger.pre_dispatch(986 &sponsor.clone().into(),987 &call.into(),988 &dispatch_info,989 0,990 ) {991 Ok(p) => p,992 Err(_) => fail!("failed to get pre dispatch info"),993 };994995 let single_fee: u128 = pre.2.map(|imbalance| imbalance.peek()).unwrap();996997 Ok(998 <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(999 &id,1000 &(sponsor.into()),1001 single_fee,1002 ),1003 )1004 }10051006 fn cancel_reserve(1007 id: [u8; 16],1008 sponsor: <T as frame_system::Config>::AccountId,1009 ) -> Result<u128, DispatchError> {1010 Ok(1011 <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(1012 &id,1013 &(sponsor.into()),1014 u128::MAX,1015 ),1016 )1017 }1018}10191020parameter_types! {1021 pub const NoPreimagePostponement: Option<u32> = Some(10);1022 pub const Preimage: Option<u32> = Some(10);1023}102410251026pub struct OriginPrivilegeCmp;10271028impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {1029 fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {1030 Some(Ordering::Equal)1031 }1032}10331034impl pallet_unq_scheduler::Config for Runtime {1035 type Event = Event;1036 type Origin = Origin;1037 type Currency = Balances;1038 type PalletsOrigin = OriginCaller;1039 type Call = Call;1040 type MaximumWeight = MaximumSchedulerWeight;1041 type ScheduleOrigin = EnsureSigned<AccountId>;1042 type MaxScheduledPerBlock = MaxScheduledPerBlock;1043 type WeightInfo = ();1044 type CallExecutor = SchedulerPaymentExecutor;1045 type OriginPrivilegeCmp = OriginPrivilegeCmp;1046 type PreimageProvider = ();1047 type NoPreimagePostponement = NoPreimagePostponement;1048}10491050type EvmSponsorshipHandler = (1051 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,1052 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,1053);10541055type SponsorshipHandler = (1056 pallet_unique::UniqueSponsorshipHandler<Runtime>,1057 1058 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,1059);10601061impl pallet_evm_transaction_payment::Config for Runtime {1062 type EvmSponsorshipHandler = EvmSponsorshipHandler;1063 type Currency = Balances;1064 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;1065 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;1066}10671068impl pallet_charge_transaction::Config for Runtime {1069 type SponsorshipHandler = SponsorshipHandler;1070}107110721073107410751076parameter_types! {1077 1078 pub const HelpersContractAddress: H160 = H160([1079 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,1080 ]);1081}10821083impl pallet_evm_contract_helpers::Config for Runtime {1084 type ContractAddress = HelpersContractAddress;1085 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;1086}10871088construct_runtime!(1089 pub enum Runtime where1090 Block = Block,1091 NodeBlock = opaque::Block,1092 UncheckedExtrinsic = UncheckedExtrinsic1093 {1094 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1095 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,10961097 Aura: pallet_aura::{Pallet, Config<T>} = 22,1098 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10991100 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1101 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1102 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1103 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1104 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1105 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1106 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1107 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1108 1109 11101111 1112 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1113 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1114 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1115 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,11161117 1118 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1119 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1120 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1121 1122 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1123 1124 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1125 Fungible: pallet_fungible::{Pallet, Storage} = 67,1126 Refungible: pallet_refungible::{Pallet, Storage} = 68,1127 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,11281129 1130 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1131 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,11321133 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1134 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1135 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1136 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1137 }1138);11391140pub struct TransactionConverter;11411142impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1143 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1144 UncheckedExtrinsic::new_unsigned(1145 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1146 )1147 }1148}11491150impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1151 fn convert_transaction(1152 &self,1153 transaction: pallet_ethereum::Transaction,1154 ) -> opaque::UncheckedExtrinsic {1155 let extrinsic = UncheckedExtrinsic::new_unsigned(1156 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1157 );1158 let encoded = extrinsic.encode();1159 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1160 .expect("Encoded extrinsic is always valid")1161 }1162}116311641165pub type Address = sp_runtime::MultiAddress<AccountId, ()>;11661167pub type Header = generic::Header<BlockNumber, BlakeTwo256>;11681169pub type Block = generic::Block<Header, UncheckedExtrinsic>;11701171pub type SignedBlock = generic::SignedBlock<Block>;11721173pub type BlockId = generic::BlockId<Block>;11741175pub type SignedExtra = (1176 frame_system::CheckSpecVersion<Runtime>,1177 1178 frame_system::CheckGenesis<Runtime>,1179 frame_system::CheckEra<Runtime>,1180 frame_system::CheckNonce<Runtime>,1181 frame_system::CheckWeight<Runtime>,1182 ChargeTransactionPayment,1183 1184);11851186pub type UncheckedExtrinsic =1187 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;11881189pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;11901191pub type Executive = frame_executive::Executive<1192 Runtime,1193 Block,1194 frame_system::ChainContext<Runtime>,1195 Runtime,1196 AllPalletsReversedWithSystemFirst,1197>;11981199impl_opaque_keys! {1200 pub struct SessionKeys {1201 pub aura: Aura,1202 }1203}12041205impl fp_self_contained::SelfContainedCall for Call {1206 type SignedInfo = H160;12071208 fn is_self_contained(&self) -> bool {1209 match self {1210 Call::Ethereum(call) => call.is_self_contained(),1211 _ => false,1212 }1213 }12141215 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1216 match self {1217 Call::Ethereum(call) => call.check_self_contained(),1218 _ => None,1219 }1220 }12211222 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1223 match self {1224 Call::Ethereum(call) => call.validate_self_contained(info),1225 _ => None,1226 }1227 }12281229 fn pre_dispatch_self_contained(1230 &self,1231 info: &Self::SignedInfo,1232 ) -> Option<Result<(), TransactionValidityError>> {1233 match self {1234 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1235 _ => None,1236 }1237 }12381239 fn apply_self_contained(1240 self,1241 info: Self::SignedInfo,1242 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1243 match self {1244 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1245 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1246 )),1247 _ => None,1248 }1249 }1250}12511252macro_rules! dispatch_unique_runtime {1253 ($collection:ident.$method:ident($($name:ident),*)) => {{1254 use pallet_unique::dispatch::Dispatched;12551256 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1257 let dispatch = collection.as_dyn();12581259 Ok(dispatch.$method($($name),*))1260 }};1261}12621263impl_common_runtime_apis!();12641265struct CheckInherents;12661267impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1268 fn check_inherents(1269 block: &Block,1270 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1271 ) -> sp_inherents::CheckInherentsResult {1272 let relay_chain_slot = relay_state_proof1273 .read_slot()1274 .expect("Could not read the relay chain slot from the proof");12751276 let inherent_data =1277 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1278 relay_chain_slot,1279 sp_std::time::Duration::from_secs(6),1280 )1281 .create_inherent_data()1282 .expect("Could not create the timestamp inherent data");12831284 inherent_data.check_extrinsics(block)1285 }1286}12871288cumulus_pallet_parachain_system::register_validate_block!(1289 Runtime = Runtime,1290 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1291 CheckInherents = CheckInherents,1292);