difftreelog
feat implement theme RMRK RPC
in: master
7 files changed
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -443,7 +443,7 @@
<TokenData<T>>::get((collection_id, token_id))
.unwrap()
.rmrk_nft_type()
- .ok_or(<Error<T>>::NoAvailableNftId.into())
+ .ok_or_else(|| <Error<T>>::NoAvailableNftId.into())
}
pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
@@ -453,6 +453,65 @@
Ok(())
}
+ pub fn filter_theme_properties(
+ collection_id: CollectionId,
+ token_id: TokenId,
+ filter_keys: Option<Vec<RmrkPropertyKey>>
+ ) -> Result<Vec<RmrkThemeProperty>, DispatchError> {
+ filter_keys.map(|keys| {
+ let properties = keys.into_iter()
+ .filter_map(|key| {
+ let key: RmrkString = key.try_into().ok()?;
+
+ let value = Self::get_nft_property(
+ collection_id,
+ token_id,
+ RmrkProperty::ThemeProperty(&key)
+ ).ok()?.decode_or_default();
+
+ let property = RmrkThemeProperty {
+ key,
+ value
+ };
+
+ Some(property)
+ })
+ .collect();
+
+ Ok(properties)
+ }).unwrap_or_else(|| {
+ let properties = Self::iterate_theme_properties(collection_id, token_id)?
+ .collect();
+
+ Ok(properties)
+ })
+ }
+
+ pub fn iterate_theme_properties(
+ collection_id: CollectionId,
+ token_id: TokenId
+ ) -> Result<impl Iterator<Item=RmrkThemeProperty>, DispatchError> {
+ let key_prefix = rmrk_property!(Config=T, key: ThemeProperty(&RmrkString::default()))?;
+
+ let properties = <PalletNft<T>>::token_properties((collection_id, token_id))
+ .into_iter()
+ .filter_map(move |(key, value)| {
+ let key = key.as_slice().strip_prefix(key_prefix.as_slice())?;
+
+ let key: RmrkString = key.to_vec().try_into().ok()?;
+ let value: RmrkString = value.decode_or_default();
+
+ let property = RmrkThemeProperty {
+ key,
+ value
+ };
+
+ Some(property)
+ });
+
+ Ok(properties)
+ }
+
pub fn get_typed_nft_collection(
collection_id: CollectionId,
collection_type: CollectionType
pallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/property.rs
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -1,7 +1,7 @@
use super::*;
use core::convert::AsRef;
-pub enum RmrkProperty {
+pub enum RmrkProperty<'r> {
Metadata,
CollectionType,
RoyaltyInfo,
@@ -23,11 +23,11 @@
EquippableList,
ZIndex,
ThemeName,
- ThemeProperty(RmrkString),
+ ThemeProperty(&'r RmrkString),
ThemeInherit,
}
-impl RmrkProperty {
+impl<'r> RmrkProperty<'r> {
pub fn to_key<T: Config>(self) -> Result<PropertyKey, Error<T>> {
fn get_bytes<T: AsRef<[u8]>>(container: &T) -> &[u8] {
container.as_ref()
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -775,6 +775,10 @@
self.0.iter()
}
+ pub fn into_iter(self) -> impl Iterator<Item = (PropertyKey, Value)> {
+ self.0.into_iter()
+ }
+
fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
if key.is_empty() {
return Err(PropertiesError::EmptyPropertyKey);
@@ -848,6 +852,10 @@
pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
self.map.iter()
}
+
+ pub fn into_iter(self) -> impl Iterator<Item = (PropertyKey, PropertyValue)> {
+ self.map.into_iter()
+ }
}
impl TrySetProperty for Properties {
@@ -936,7 +944,8 @@
pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;
pub type RmrkPartType =
PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;
-pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;
+pub type RmrkThemeProperty = ThemeProperty<RmrkString>;
+pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;
pub type RmrkRpcString = Vec<u8>;
pub type RmrkThemeName = RmrkRpcString;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -184,7 +184,7 @@
},
None => return Ok(None)
};
-
+
let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));
Ok(Some(RmrkInstanceInfo {
@@ -317,7 +317,7 @@
if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }
Ok(Vec::new(/*[RmrkResourceInfo {
-
+
}]*/))
}
@@ -379,16 +379,18 @@
fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};
let collection_id = CollectionId(base_id);
- // todo make sure this is theme
+ if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {
+ return Ok(Vec::new());
+ }
- let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?
+ let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()))?
.iter()
.filter_map(|token_id| {
let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();
-
+
match nft_type {
Theme => Some(
RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()
@@ -396,47 +398,59 @@
_ => None
}
})
- .collect::<Vec<RmrkThemeName>>();
+ .collect();
Ok(theme_names)
}
fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {
use frame_support::BoundedVec;
+ use pallet_proxy_rmrk_core::{
+ RmrkProperty,
+ misc::{CollectionType, NftType, RmrkNft, RmrkDecode}
+ };
let collection_id = CollectionId(base_id);
+ if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {
+ return Ok(None);
+ }
- // todo one theme. filter collection tokens according to theme name, should result in one
- // (is it possible to search with iter_prefix for part of a struct that satisfies?..)
- // filter properties according to filter_keys and load them into resulting theme.properties
- let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?
- .iter()
- .filter_map(|token_id| {
- let properties = Nonfungible::token_properties((collection_id, token_id));
+ let theme_info = (dispatch_unique_runtime!(collection_id.collection_tokens()))?
+ .into_iter()
+ .find_map(|token_id| {
+ RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;
+
+ let name: RmrkString = RmrkCore::get_nft_property(
+ collection_id, token_id, RmrkProperty::ThemeName
+ ).ok()?.decode_or_default();
- // todo ping properties for "rmrk:nft-type"
- // if none, skip, None
- // ugh gonna go through ALL properties, searching for matches for "rmrk:theme-property-<key>"
- let nft_type = "theme";
- match nft_type {
- "theme" => Some(RmrkTheme {
- name: BoundedVec::try_from(
- <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))
- .map(|t| t.const_data)
- .unwrap_or_default()
- .into_inner()
- ).unwrap(),
- // todo? (dispatch_unique_runtime!(collection_id.const_metadata(token_id)) as Result<Vec<u8>, DispatchError>)?,
- properties: Vec::new(), // pain in the ass
- inherit: false, // "rmrk:theme-inherit"
- }),
- _ => None
+ if name == theme_name {
+ Some((name, token_id))
+ } else {
+ None
}
- })
- .collect::<Vec<_>>();
+ });
+
+ let (name, theme_id) = match theme_info {
+ Some((name, theme_id)) => (name, theme_id),
+ None => return Ok(None)
+ };
- // todo
- Ok(Some(themes[0].clone()))
+ let properties = RmrkCore::filter_theme_properties(collection_id, theme_id, filter_keys)?;
+
+ let inherit = RmrkCore::get_nft_property(
+ collection_id,
+ theme_id,
+ RmrkProperty::ThemeInherit
+ )?.decode_or_default();
+
+ let theme = RmrkTheme {
+ name,
+ properties,
+ inherit,
+ };
+
+ Ok(Some(theme))
}
}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -1149,7 +1149,7 @@
let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
let dispatch = collection.as_dyn();
- Ok(dispatch.$method($($name),*))
+ Ok::<_, DispatchError>(dispatch.$method($($name),*))
}};
}
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -1122,7 +1122,7 @@
let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
let dispatch = collection.as_dyn();
- Ok(dispatch.$method($($name),*))
+ Ok::<_, DispatchError>(dispatch.$method($($name),*))
}};
}
runtime/unique/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[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;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,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, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use unique_runtime_common::{70 dispatch::{CollectionDispatchT, CollectionDispatch},71 weights::CommonWeights,72 sponsoring::UniqueSponsorshipHandler,73 eth_sponsoring::UniqueEthSponsorshipHandler,74};75use up_data_structs::*;76// use pallet_contracts::weights::WeightInfo;77// #[cfg(any(feature = "std", test))]78use frame_system::{79 self as frame_system, EnsureRoot, EnsureSigned,80 limits::{BlockWeights, BlockLength},81};82use sp_arithmetic::{83 traits::{BaseArithmetic, Unsigned},84};85use smallvec::smallvec;86use codec::{Encode, Decode};87use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};88use fp_rpc::TransactionStatus;89use sp_runtime::{90 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},91 transaction_validity::TransactionValidityError,92 SaturatedConversion,93};9495// pub use pallet_timestamp::Call as TimestampCall;9697// Polkadot imports98use pallet_xcm::XcmPassthrough;99use polkadot_parachain::primitives::Sibling;100use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};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::{marker::PhantomData};111112use xcm::latest::{113 // Xcm,114 AssetId::{Concrete},115 Fungibility::Fungible as XcmFungible,116 MultiAsset,117 Error as XcmError,118};119use xcm_executor::traits::{MatchesFungible, WeightTrader};120//use xcm_executor::traits::MatchesFungible;121use sp_runtime::traits::CheckedConversion;122123use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};124125pub const RUNTIME_NAME: &str = "unique";126pub const TOKEN_SYMBOL: &str = "UNQ";127128type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;129130impl RuntimeInstance for Runtime {131 type CrossAccountId = self::CrossAccountId;132133 type TransactionConverter = self::TransactionConverter;134135 fn get_transaction_converter() -> TransactionConverter {136 TransactionConverter137 }138}139140/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know141/// the specifics of the runtime. They can then be made to be agnostic over specific formats142/// of data like extrinsics, allowing for them to continue syncing the network through upgrades143/// to even the core data structures.144pub mod opaque {145 use sp_std::prelude::*;146 use sp_runtime::impl_opaque_keys;147 use super::Aura;148149 pub use unique_runtime_common::types::*;150151 impl_opaque_keys! {152 pub struct SessionKeys {153 pub aura: Aura,154 }155 }156}157158/// This runtime version.159pub const VERSION: RuntimeVersion = RuntimeVersion {160 spec_name: create_runtime_str!(RUNTIME_NAME),161 impl_name: create_runtime_str!(RUNTIME_NAME),162 authoring_version: 1,163 spec_version: 920000,164 impl_version: 0,165 apis: RUNTIME_API_VERSIONS,166 transaction_version: 1,167 state_version: 0,168};169170#[derive(codec::Encode, codec::Decode)]171pub enum XCMPMessage<XAccountId, XBalance> {172 /// Transfer tokens to the given account from the Parachain account.173 TransferToken(XAccountId, XBalance),174}175176/// The version information used to identify this runtime when compiled natively.177#[cfg(feature = "std")]178pub fn native_version() -> NativeVersion {179 NativeVersion {180 runtime_version: VERSION,181 can_author_with: Default::default(),182 }183}184185type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;186187pub struct DealWithFees;188impl OnUnbalanced<NegativeImbalance> for DealWithFees {189 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {190 if let Some(fees) = fees_then_tips.next() {191 // for fees, 100% to treasury192 let mut split = fees.ration(100, 0);193 if let Some(tips) = fees_then_tips.next() {194 // for tips, if any, 100% to treasury195 tips.ration_merge_into(100, 0, &mut split);196 }197 Treasury::on_unbalanced(split.0);198 // Author::on_unbalanced(split.1);199 }200 }201}202203parameter_types! {204 pub const BlockHashCount: BlockNumber = 2400;205 pub RuntimeBlockLength: BlockLength =206 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);207 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);208 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;209 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()210 .base_block(BlockExecutionWeight::get())211 .for_class(DispatchClass::all(), |weights| {212 weights.base_extrinsic = ExtrinsicBaseWeight::get();213 })214 .for_class(DispatchClass::Normal, |weights| {215 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);216 })217 .for_class(DispatchClass::Operational, |weights| {218 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);219 // Operational transactions have some extra reserved space, so that they220 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.221 weights.reserved = Some(222 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT223 );224 })225 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)226 .build_or_panic();227 pub const Version: RuntimeVersion = VERSION;228 pub const SS58Prefix: u16 = 7391;229}230231parameter_types! {232 pub const ChainId: u64 = 8880;233}234235pub struct FixedFee;236impl FeeCalculator for FixedFee {237 fn min_gas_price() -> U256 {238 MIN_GAS_PRICE.into()239 }240}241242// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case243// (contract, which only writes a lot of data),244// approximating on top of our real store write weight245parameter_types! {246 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;247 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;248 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();249}250251/// Limiting EVM execution to 50% of block for substrate users and management tasks252/// EVM transaction consumes more weight than substrate's, so we can't rely on them being253/// scheduled fairly254const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);255parameter_types! {256 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());257}258259pub enum FixedGasWeightMapping {}260impl GasWeightMapping for FixedGasWeightMapping {261 fn gas_to_weight(gas: u64) -> Weight {262 gas.saturating_mul(WeightPerGas::get())263 }264 fn weight_to_gas(weight: Weight) -> u64 {265 weight / WeightPerGas::get()266 }267}268269impl pallet_evm::Config for Runtime {270 type BlockGasLimit = BlockGasLimit;271 type FeeCalculator = FixedFee;272 type GasWeightMapping = FixedGasWeightMapping;273 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;274 type CallOrigin = EnsureAddressTruncated<Self>;275 type WithdrawOrigin = EnsureAddressTruncated<Self>;276 type AddressMapping = HashedAddressMapping<Self::Hashing>;277 type PrecompilesType = ();278 type PrecompilesValue = ();279 type Currency = Balances;280 type Event = Event;281 type OnMethodCall = (282 pallet_evm_migration::OnMethodCall<Self>,283 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,284 CollectionDispatchT<Self>,285 );286 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;287 type ChainId = ChainId;288 type Runner = pallet_evm::runner::stack::Runner<Self>;289 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;290 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;291 type FindAuthor = EthereumFindAuthor<Aura>;292}293294impl pallet_evm_migration::Config for Runtime {295 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;296}297298pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);299impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {300 fn find_author<'a, I>(digests: I) -> Option<H160>301 where302 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,303 {304 if let Some(author_index) = F::find_author(digests) {305 let authority_id = Aura::authorities()[author_index as usize].clone();306 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));307 }308 None309 }310}311312impl pallet_ethereum::Config for Runtime {313 type Event = Event;314 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;315}316317impl pallet_randomness_collective_flip::Config for Runtime {}318319impl frame_system::Config for Runtime {320 /// The data to be stored in an account.321 type AccountData = pallet_balances::AccountData<Balance>;322 /// The identifier used to distinguish between accounts.323 type AccountId = AccountId;324 /// The basic call filter to use in dispatchable.325 type BaseCallFilter = Everything;326 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).327 type BlockHashCount = BlockHashCount;328 /// The maximum length of a block (in bytes).329 type BlockLength = RuntimeBlockLength;330 /// The index type for blocks.331 type BlockNumber = BlockNumber;332 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.333 type BlockWeights = RuntimeBlockWeights;334 /// The aggregated dispatch type that is available for extrinsics.335 type Call = Call;336 /// The weight of database operations that the runtime can invoke.337 type DbWeight = RocksDbWeight;338 /// The ubiquitous event type.339 type Event = Event;340 /// The type for hashing blocks and tries.341 type Hash = Hash;342 /// The hashing algorithm used.343 type Hashing = BlakeTwo256;344 /// The header type.345 type Header = generic::Header<BlockNumber, BlakeTwo256>;346 /// The index type for storing how many extrinsics an account has signed.347 type Index = Index;348 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.349 type Lookup = AccountIdLookup<AccountId, ()>;350 /// What to do if an account is fully reaped from the system.351 type OnKilledAccount = ();352 /// What to do if a new account is created.353 type OnNewAccount = ();354 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;355 /// The ubiquitous origin type.356 type Origin = Origin;357 /// This type is being generated by `construct_runtime!`.358 type PalletInfo = PalletInfo;359 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.360 type SS58Prefix = SS58Prefix;361 /// Weight information for the extrinsics of this pallet.362 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;363 /// Version of the runtime.364 type Version = Version;365 type MaxConsumers = ConstU32<16>;366}367368parameter_types! {369 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;370}371372impl pallet_timestamp::Config for Runtime {373 /// A timestamp: milliseconds since the unix epoch.374 type Moment = u64;375 type OnTimestampSet = ();376 type MinimumPeriod = MinimumPeriod;377 type WeightInfo = ();378}379380parameter_types! {381 // pub const ExistentialDeposit: u128 = 500;382 pub const ExistentialDeposit: u128 = 0;383 pub const MaxLocks: u32 = 50;384}385386impl pallet_balances::Config for Runtime {387 type MaxLocks = MaxLocks;388 type MaxReserves = ();389 type ReserveIdentifier = [u8; 8];390 /// The type for recording an account's balance.391 type Balance = Balance;392 /// The ubiquitous event type.393 type Event = Event;394 type DustRemoval = Treasury;395 type ExistentialDeposit = ExistentialDeposit;396 type AccountStore = System;397 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;398}399400pub const fn deposit(items: u32, bytes: u32) -> Balance {401 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE402}403404/*405parameter_types! {406 pub TombstoneDeposit: Balance = deposit(407 1,408 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,409 );410 pub DepositPerContract: Balance = TombstoneDeposit::get();411 pub const DepositPerStorageByte: Balance = deposit(0, 1);412 pub const DepositPerStorageItem: Balance = deposit(1, 0);413 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);414 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;415 pub const SignedClaimHandicap: u32 = 2;416 pub const MaxDepth: u32 = 32;417 pub const MaxValueSize: u32 = 16 * 1024;418 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb419 // The lazy deletion runs inside on_initialize.420 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *421 RuntimeBlockWeights::get().max_block;422 // The weight needed for decoding the queue should be less or equal than a fifth423 // of the overall weight dedicated to the lazy deletion.424 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (425 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -426 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)427 )) / 5) as u32;428 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();429}430431impl pallet_contracts::Config for Runtime {432 type Time = Timestamp;433 type Randomness = RandomnessCollectiveFlip;434 type Currency = Balances;435 type Event = Event;436 type RentPayment = ();437 type SignedClaimHandicap = SignedClaimHandicap;438 type TombstoneDeposit = TombstoneDeposit;439 type DepositPerContract = DepositPerContract;440 type DepositPerStorageByte = DepositPerStorageByte;441 type DepositPerStorageItem = DepositPerStorageItem;442 type RentFraction = RentFraction;443 type SurchargeReward = SurchargeReward;444 type WeightPrice = pallet_transaction_payment::Pallet<Self>;445 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;446 type ChainExtension = NFTExtension;447 type DeletionQueueDepth = DeletionQueueDepth;448 type DeletionWeightLimit = DeletionWeightLimit;449 type Schedule = Schedule;450 type CallStack = [pallet_contracts::Frame<Self>; 31];451}452*/453454parameter_types! {455 /// This value increases the priority of `Operational` transactions by adding456 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.457 pub const OperationalFeeMultiplier: u8 = 5;458}459460/// Linear implementor of `WeightToFeePolynomial`461pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);462463impl<T> WeightToFeePolynomial for LinearFee<T>464where465 T: BaseArithmetic + From<u32> + Copy + Unsigned,466{467 type Balance = T;468469 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {470 smallvec!(WeightToFeeCoefficient {471 // Targeting 0.1 Unique per NFT transfer472 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),473 coeff_frac: Perbill::zero(),474 negative: false,475 degree: 1,476 })477 }478}479480impl pallet_transaction_payment::Config for Runtime {481 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;482 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;483 type OperationalFeeMultiplier = OperationalFeeMultiplier;484 type WeightToFee = LinearFee<Balance>;485 type FeeMultiplierUpdate = ();486}487488parameter_types! {489 pub const ProposalBond: Permill = Permill::from_percent(5);490 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;491 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;492 pub const SpendPeriod: BlockNumber = 5 * MINUTES;493 pub const Burn: Permill = Permill::from_percent(0);494 pub const TipCountdown: BlockNumber = 1 * DAYS;495 pub const TipFindersFee: Percent = Percent::from_percent(20);496 pub const TipReportDepositBase: Balance = 1 * UNIQUE;497 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;498 pub const BountyDepositBase: Balance = 1 * UNIQUE;499 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;500 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");501 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;502 pub const MaximumReasonLength: u32 = 16384;503 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);504 pub const BountyValueMinimum: Balance = 5 * UNIQUE;505 pub const MaxApprovals: u32 = 100;506}507508impl pallet_treasury::Config for Runtime {509 type PalletId = TreasuryModuleId;510 type Currency = Balances;511 type ApproveOrigin = EnsureRoot<AccountId>;512 type RejectOrigin = EnsureRoot<AccountId>;513 type Event = Event;514 type OnSlash = ();515 type ProposalBond = ProposalBond;516 type ProposalBondMinimum = ProposalBondMinimum;517 type ProposalBondMaximum = ProposalBondMaximum;518 type SpendPeriod = SpendPeriod;519 type Burn = Burn;520 type BurnDestination = ();521 type SpendFunds = ();522 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;523 type MaxApprovals = MaxApprovals;524}525526impl pallet_sudo::Config for Runtime {527 type Event = Event;528 type Call = Call;529}530531pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);532533impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider534 for RelayChainBlockNumberProvider<T>535{536 type BlockNumber = BlockNumber;537538 fn current_block_number() -> Self::BlockNumber {539 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()540 .map(|d| d.relay_parent_number)541 .unwrap_or_default()542 }543}544545parameter_types! {546 pub const MinVestedTransfer: Balance = 10 * UNIQUE;547 pub const MaxVestingSchedules: u32 = 28;548}549550impl orml_vesting::Config for Runtime {551 type Event = Event;552 type Currency = pallet_balances::Pallet<Runtime>;553 type MinVestedTransfer = MinVestedTransfer;554 type VestedTransferOrigin = EnsureSigned<AccountId>;555 type WeightInfo = ();556 type MaxVestingSchedules = MaxVestingSchedules;557 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;558}559560parameter_types! {561 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;563}564565impl cumulus_pallet_parachain_system::Config for Runtime {566 type Event = Event;567 type SelfParaId = parachain_info::Pallet<Self>;568 type OnSystemEvent = ();569 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<570 // MaxDownwardMessageWeight,571 // XcmExecutor<XcmConfig>,572 // Call,573 // >;574 type OutboundXcmpMessageSource = XcmpQueue;575 type DmpMessageHandler = DmpQueue;576 type ReservedDmpWeight = ReservedDmpWeight;577 type ReservedXcmpWeight = ReservedXcmpWeight;578 type XcmpMessageHandler = XcmpQueue;579}580581impl parachain_info::Config for Runtime {}582583impl cumulus_pallet_aura_ext::Config for Runtime {}584585parameter_types! {586 pub const RelayLocation: MultiLocation = MultiLocation::parent();587 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;588 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();589 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();590}591592/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used593/// when determining ownership of accounts for asset transacting and when attempting to use XCM594/// `Transact` in order to determine the dispatch Origin.595pub type LocationToAccountId = (596 // The parent (Relay-chain) origin converts to the default `AccountId`.597 ParentIsPreset<AccountId>,598 // Sibling parachain origins convert to AccountId via the `ParaId::into`.599 SiblingParachainConvertsVia<Sibling, AccountId>,600 // Straight up local `AccountId32` origins just alias directly to `AccountId`.601 AccountId32Aliases<RelayNetwork, AccountId>,602);603604pub struct OnlySelfCurrency;605impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {606 fn matches_fungible(a: &MultiAsset) -> Option<B> {607 match (&a.id, &a.fun) {608 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),609 _ => None,610 }611 }612}613614/// Means for transacting assets on this chain.615pub type LocalAssetTransactor = CurrencyAdapter<616 // Use this currency:617 Balances,618 // Use this currency when it is a fungible asset matching the given location or name:619 OnlySelfCurrency,620 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:621 LocationToAccountId,622 // Our chain's account ID type (we can't get away without mentioning it explicitly):623 AccountId,624 // We don't track any teleports.625 (),626>;627628/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,629/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can630/// biases the kind of local `Origin` it will become.631pub type XcmOriginToTransactDispatchOrigin = (632 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location633 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for634 // foreign chains who want to have a local sovereign account on this chain which they control.635 SovereignSignedViaLocation<LocationToAccountId, Origin>,636 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when637 // recognised.638 RelayChainAsNative<RelayOrigin, Origin>,639 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when640 // recognised.641 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,642 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a643 // transaction from the Root origin.644 ParentAsSuperuser<Origin>,645 // Native signed account converter; this just converts an `AccountId32` origin into a normal646 // `Origin::Signed` origin of the same 32-byte value.647 SignedAccountId32AsNative<RelayNetwork, Origin>,648 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.649 XcmPassthrough<Origin>,650);651652parameter_types! {653 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.654 pub UnitWeightCost: Weight = 1_000_000;655 // 1200 UNIQUEs buy 1 second of weight.656 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);657 pub const MaxInstructions: u32 = 100;658 pub const MaxAuthorities: u32 = 100_000;659}660661match_types! {662 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {663 MultiLocation { parents: 1, interior: Here } |664 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }665 };666}667668pub type Barrier = (669 TakeWeightCredit,670 AllowTopLevelPaidExecutionFrom<Everything>,671 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,672 // ^^^ Parent & its unit plurality gets free execution673);674675pub struct UsingOnlySelfCurrencyComponents<676 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,677 AssetId: Get<MultiLocation>,678 AccountId,679 Currency: CurrencyT<AccountId>,680 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,681>(682 Weight,683 Currency::Balance,684 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,685);686impl<687 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,688 AssetId: Get<MultiLocation>,689 AccountId,690 Currency: CurrencyT<AccountId>,691 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,692 > WeightTrader693 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>694{695 fn new() -> Self {696 Self(0, Zero::zero(), PhantomData)697 }698699 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {700 let amount = WeightToFee::calc(&weight);701 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;702703 // location to this parachain through relay chain704 let option1: xcm::v1::AssetId = Concrete(MultiLocation {705 parents: 1,706 interior: X1(Parachain(ParachainInfo::parachain_id().into())),707 });708 // direct location709 let option2: xcm::v1::AssetId = Concrete(MultiLocation {710 parents: 0,711 interior: Here,712 });713714 let required = if payment.fungible.contains_key(&option1) {715 (option1, u128_amount).into()716 } else if payment.fungible.contains_key(&option2) {717 (option2, u128_amount).into()718 } else {719 (Concrete(MultiLocation::default()), u128_amount).into()720 };721722 let unused = payment723 .checked_sub(required)724 .map_err(|_| XcmError::TooExpensive)?;725 self.0 = self.0.saturating_add(weight);726 self.1 = self.1.saturating_add(amount);727 Ok(unused)728 }729730 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {731 let weight = weight.min(self.0);732 let amount = WeightToFee::calc(&weight);733 self.0 -= weight;734 self.1 = self.1.saturating_sub(amount);735 let amount: u128 = amount.saturated_into();736 if amount > 0 {737 Some((AssetId::get(), amount).into())738 } else {739 None740 }741 }742}743impl<744 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,745 AssetId: Get<MultiLocation>,746 AccountId,747 Currency: CurrencyT<AccountId>,748 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,749 > Drop750 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>751{752 fn drop(&mut self) {753 OnUnbalanced::on_unbalanced(Currency::issue(self.1));754 }755}756757pub struct XcmConfig;758impl Config for XcmConfig {759 type Call = Call;760 type XcmSender = XcmRouter;761 // How to withdraw and deposit an asset.762 type AssetTransactor = LocalAssetTransactor;763 type OriginConverter = XcmOriginToTransactDispatchOrigin;764 type IsReserve = NativeAsset;765 type IsTeleporter = (); // Teleportation is disabled766 type LocationInverter = LocationInverter<Ancestry>;767 type Barrier = Barrier;768 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;769 type Trader = UsingOnlySelfCurrencyComponents<770 IdentityFee<Balance>,771 RelayLocation,772 AccountId,773 Balances,774 (),775 >;776 type ResponseHandler = (); // Don't handle responses for now.777 type SubscriptionService = PolkadotXcm;778779 type AssetTrap = PolkadotXcm;780 type AssetClaims = PolkadotXcm;781}782783// parameter_types! {784// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;785// }786787/// No local origins on this chain are allowed to dispatch XCM sends/executions.788pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);789790/// The means for routing XCM messages which are not for local execution into the right message791/// queues.792pub type XcmRouter = (793 // Two routers - use UMP to communicate with the relay chain:794 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,795 // ..and XCMP to communicate with the sibling chains.796 XcmpQueue,797);798799impl pallet_evm_coder_substrate::Config for Runtime {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 WeightInfo = ();827 type Event = Event;828 type XcmExecutor = XcmExecutor<XcmConfig>;829 type ChannelInfo = ParachainSystem;830 type VersionWrapper = ();831 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;832 type ControllerOrigin = EnsureRoot<AccountId>;833 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;834}835836impl cumulus_pallet_dmp_queue::Config for Runtime {837 type Event = Event;838 type XcmExecutor = XcmExecutor<XcmConfig>;839 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;840}841842impl pallet_aura::Config for Runtime {843 type AuthorityId = AuraId;844 type DisabledValidators = ();845 type MaxAuthorities = MaxAuthorities;846}847848parameter_types! {849 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();850 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;851}852853impl pallet_common::Config for Runtime {854 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;855 type Event = Event;856 type Currency = Balances;857 type CollectionCreationPrice = CollectionCreationPrice;858 type TreasuryAccountId = TreasuryAccountId;859 type CollectionDispatch = CollectionDispatchT<Self>;860861 type EvmTokenAddressMapping = EvmTokenAddressMapping;862 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;863}864865impl pallet_structure::Config for Runtime {866 type Event = Event;867 type Call = Call;868 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;869}870871impl pallet_evm::account::Config for Runtime {872 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;873 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;874 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;875}876877impl pallet_fungible::Config for Runtime {878 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;879}880impl pallet_refungible::Config for Runtime {881 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;882}883impl pallet_nonfungible::Config for Runtime {884 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;885}886887impl pallet_unique::Config for Runtime {888 type Event = Event;889 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;890 type CommonWeightInfo = CommonWeights<Self>;891}892893parameter_types! {894 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied895}896897/// Used for the pallet inflation898impl pallet_inflation::Config for Runtime {899 type Currency = Balances;900 type TreasuryAccountId = TreasuryAccountId;901 type InflationBlockInterval = InflationBlockInterval;902 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;903}904905// parameter_types! {906// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *907// RuntimeBlockWeights::get().max_block;908// pub const MaxScheduledPerBlock: u32 = 50;909// }910911type EvmSponsorshipHandler = (912 UniqueEthSponsorshipHandler<Runtime>,913 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,914);915type SponsorshipHandler = (916 UniqueSponsorshipHandler<Runtime>,917 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,918 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,919);920921// impl pallet_unq_scheduler::Config for Runtime {922// type Event = Event;923// type Origin = Origin;924// type PalletsOrigin = OriginCaller;925// type Call = Call;926// type MaximumWeight = MaximumSchedulerWeight;927// type ScheduleOrigin = EnsureSigned<AccountId>;928// type MaxScheduledPerBlock = MaxScheduledPerBlock;929// type SponsorshipHandler = SponsorshipHandler;930// type WeightInfo = ();931// }932933impl pallet_evm_transaction_payment::Config for Runtime {934 type EvmSponsorshipHandler = EvmSponsorshipHandler;935 type Currency = Balances;936}937938impl pallet_charge_transaction::Config for Runtime {939 type SponsorshipHandler = SponsorshipHandler;940}941942// impl pallet_contract_helpers::Config for Runtime {943// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;944// }945946parameter_types! {947 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049948 pub const HelpersContractAddress: H160 = H160([949 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,950 ]);951}952953impl pallet_evm_contract_helpers::Config for Runtime {954 type ContractAddress = HelpersContractAddress;955 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;956}957958construct_runtime!(959 pub enum Runtime where960 Block = Block,961 NodeBlock = opaque::Block,962 UncheckedExtrinsic = UncheckedExtrinsic963 {964 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,965 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,966967 Aura: pallet_aura::{Pallet, Config<T>} = 22,968 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,969970 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,971 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,972 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,973 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,974 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,975 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,976 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,977 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,978 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,979 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,980981 // XCM helpers.982 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,983 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,984 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,985 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,986987 // Unique Pallets988 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,989 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,990 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,991 // free = 63992 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,993 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,994 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,995 Fungible: pallet_fungible::{Pallet, Storage} = 67,996 Refungible: pallet_refungible::{Pallet, Storage} = 68,997 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,998 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,999 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,10001001 // Frontier1002 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1003 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10041005 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1006 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1007 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1008 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1009 }1010);10111012pub struct TransactionConverter;10131014impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1015 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1016 UncheckedExtrinsic::new_unsigned(1017 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1018 )1019 }1020}10211022impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1023 fn convert_transaction(1024 &self,1025 transaction: pallet_ethereum::Transaction,1026 ) -> opaque::UncheckedExtrinsic {1027 let extrinsic = UncheckedExtrinsic::new_unsigned(1028 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1029 );1030 let encoded = extrinsic.encode();1031 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1032 .expect("Encoded extrinsic is always valid")1033 }1034}10351036/// The address format for describing accounts.1037pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1038/// Block header type as expected by this runtime.1039pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1040/// Block type as expected by this runtime.1041pub type Block = generic::Block<Header, UncheckedExtrinsic>;1042/// A Block signed with a Justification1043pub type SignedBlock = generic::SignedBlock<Block>;1044/// BlockId type as expected by this runtime.1045pub type BlockId = generic::BlockId<Block>;1046/// The SignedExtension to the basic transaction logic.1047pub type SignedExtra = (1048 frame_system::CheckSpecVersion<Runtime>,1049 // system::CheckTxVersion<Runtime>,1050 frame_system::CheckGenesis<Runtime>,1051 frame_system::CheckEra<Runtime>,1052 frame_system::CheckNonce<Runtime>,1053 frame_system::CheckWeight<Runtime>,1054 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1055 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1056 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1057);1058/// Unchecked extrinsic type as expected by this runtime.1059pub type UncheckedExtrinsic =1060 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1061/// Extrinsic type that has already been checked.1062pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1063/// Executive: handles dispatch to the various modules.1064pub type Executive = frame_executive::Executive<1065 Runtime,1066 Block,1067 frame_system::ChainContext<Runtime>,1068 Runtime,1069 AllPalletsReversedWithSystemFirst,1070>;10711072impl_opaque_keys! {1073 pub struct SessionKeys {1074 pub aura: Aura,1075 }1076}10771078impl fp_self_contained::SelfContainedCall for Call {1079 type SignedInfo = H160;10801081 fn is_self_contained(&self) -> bool {1082 match self {1083 Call::Ethereum(call) => call.is_self_contained(),1084 _ => false,1085 }1086 }10871088 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1089 match self {1090 Call::Ethereum(call) => call.check_self_contained(),1091 _ => None,1092 }1093 }10941095 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1096 match self {1097 Call::Ethereum(call) => call.validate_self_contained(info),1098 _ => None,1099 }1100 }11011102 fn pre_dispatch_self_contained(1103 &self,1104 info: &Self::SignedInfo,1105 ) -> Option<Result<(), TransactionValidityError>> {1106 match self {1107 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1108 _ => None,1109 }1110 }11111112 fn apply_self_contained(1113 self,1114 info: Self::SignedInfo,1115 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1116 match self {1117 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1118 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1119 )),1120 _ => None,1121 }1122 }1123}11241125macro_rules! dispatch_unique_runtime {1126 ($collection:ident.$method:ident($($name:ident),*)) => {{1127 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1128 let dispatch = collection.as_dyn();11291130 Ok(dispatch.$method($($name),*))1131 }};1132}11331134impl_common_runtime_apis!();11351136struct CheckInherents;11371138impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1139 fn check_inherents(1140 block: &Block,1141 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1142 ) -> sp_inherents::CheckInherentsResult {1143 let relay_chain_slot = relay_state_proof1144 .read_slot()1145 .expect("Could not read the relay chain slot from the proof");11461147 let inherent_data =1148 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1149 relay_chain_slot,1150 sp_std::time::Duration::from_secs(6),1151 )1152 .create_inherent_data()1153 .expect("Could not create the timestamp inherent data");11541155 inherent_data.check_extrinsics(block)1156 }1157}11581159cumulus_pallet_parachain_system::register_validate_block!(1160 Runtime = Runtime,1161 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1162 CheckInherents = CheckInherents,1163);1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[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;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,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, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use unique_runtime_common::{70 dispatch::{CollectionDispatchT, CollectionDispatch},71 weights::CommonWeights,72 sponsoring::UniqueSponsorshipHandler,73 eth_sponsoring::UniqueEthSponsorshipHandler,74};75use up_data_structs::*;76// use pallet_contracts::weights::WeightInfo;77// #[cfg(any(feature = "std", test))]78use frame_system::{79 self as frame_system, EnsureRoot, EnsureSigned,80 limits::{BlockWeights, BlockLength},81};82use sp_arithmetic::{83 traits::{BaseArithmetic, Unsigned},84};85use smallvec::smallvec;86use codec::{Encode, Decode};87use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};88use fp_rpc::TransactionStatus;89use sp_runtime::{90 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},91 transaction_validity::TransactionValidityError,92 SaturatedConversion,93};9495// pub use pallet_timestamp::Call as TimestampCall;9697// Polkadot imports98use pallet_xcm::XcmPassthrough;99use polkadot_parachain::primitives::Sibling;100use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};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::{marker::PhantomData};111112use xcm::latest::{113 // Xcm,114 AssetId::{Concrete},115 Fungibility::Fungible as XcmFungible,116 MultiAsset,117 Error as XcmError,118};119use xcm_executor::traits::{MatchesFungible, WeightTrader};120//use xcm_executor::traits::MatchesFungible;121use sp_runtime::traits::CheckedConversion;122123use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};124125pub const RUNTIME_NAME: &str = "unique";126pub const TOKEN_SYMBOL: &str = "UNQ";127128type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;129130impl RuntimeInstance for Runtime {131 type CrossAccountId = self::CrossAccountId;132133 type TransactionConverter = self::TransactionConverter;134135 fn get_transaction_converter() -> TransactionConverter {136 TransactionConverter137 }138}139140/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know141/// the specifics of the runtime. They can then be made to be agnostic over specific formats142/// of data like extrinsics, allowing for them to continue syncing the network through upgrades143/// to even the core data structures.144pub mod opaque {145 use sp_std::prelude::*;146 use sp_runtime::impl_opaque_keys;147 use super::Aura;148149 pub use unique_runtime_common::types::*;150151 impl_opaque_keys! {152 pub struct SessionKeys {153 pub aura: Aura,154 }155 }156}157158/// This runtime version.159pub const VERSION: RuntimeVersion = RuntimeVersion {160 spec_name: create_runtime_str!(RUNTIME_NAME),161 impl_name: create_runtime_str!(RUNTIME_NAME),162 authoring_version: 1,163 spec_version: 920000,164 impl_version: 0,165 apis: RUNTIME_API_VERSIONS,166 transaction_version: 1,167 state_version: 0,168};169170#[derive(codec::Encode, codec::Decode)]171pub enum XCMPMessage<XAccountId, XBalance> {172 /// Transfer tokens to the given account from the Parachain account.173 TransferToken(XAccountId, XBalance),174}175176/// The version information used to identify this runtime when compiled natively.177#[cfg(feature = "std")]178pub fn native_version() -> NativeVersion {179 NativeVersion {180 runtime_version: VERSION,181 can_author_with: Default::default(),182 }183}184185type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;186187pub struct DealWithFees;188impl OnUnbalanced<NegativeImbalance> for DealWithFees {189 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {190 if let Some(fees) = fees_then_tips.next() {191 // for fees, 100% to treasury192 let mut split = fees.ration(100, 0);193 if let Some(tips) = fees_then_tips.next() {194 // for tips, if any, 100% to treasury195 tips.ration_merge_into(100, 0, &mut split);196 }197 Treasury::on_unbalanced(split.0);198 // Author::on_unbalanced(split.1);199 }200 }201}202203parameter_types! {204 pub const BlockHashCount: BlockNumber = 2400;205 pub RuntimeBlockLength: BlockLength =206 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);207 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);208 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;209 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()210 .base_block(BlockExecutionWeight::get())211 .for_class(DispatchClass::all(), |weights| {212 weights.base_extrinsic = ExtrinsicBaseWeight::get();213 })214 .for_class(DispatchClass::Normal, |weights| {215 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);216 })217 .for_class(DispatchClass::Operational, |weights| {218 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);219 // Operational transactions have some extra reserved space, so that they220 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.221 weights.reserved = Some(222 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT223 );224 })225 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)226 .build_or_panic();227 pub const Version: RuntimeVersion = VERSION;228 pub const SS58Prefix: u16 = 7391;229}230231parameter_types! {232 pub const ChainId: u64 = 8880;233}234235pub struct FixedFee;236impl FeeCalculator for FixedFee {237 fn min_gas_price() -> U256 {238 MIN_GAS_PRICE.into()239 }240}241242// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case243// (contract, which only writes a lot of data),244// approximating on top of our real store write weight245parameter_types! {246 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;247 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;248 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();249}250251/// Limiting EVM execution to 50% of block for substrate users and management tasks252/// EVM transaction consumes more weight than substrate's, so we can't rely on them being253/// scheduled fairly254const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);255parameter_types! {256 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());257}258259pub enum FixedGasWeightMapping {}260impl GasWeightMapping for FixedGasWeightMapping {261 fn gas_to_weight(gas: u64) -> Weight {262 gas.saturating_mul(WeightPerGas::get())263 }264 fn weight_to_gas(weight: Weight) -> u64 {265 weight / WeightPerGas::get()266 }267}268269impl pallet_evm::Config for Runtime {270 type BlockGasLimit = BlockGasLimit;271 type FeeCalculator = FixedFee;272 type GasWeightMapping = FixedGasWeightMapping;273 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;274 type CallOrigin = EnsureAddressTruncated<Self>;275 type WithdrawOrigin = EnsureAddressTruncated<Self>;276 type AddressMapping = HashedAddressMapping<Self::Hashing>;277 type PrecompilesType = ();278 type PrecompilesValue = ();279 type Currency = Balances;280 type Event = Event;281 type OnMethodCall = (282 pallet_evm_migration::OnMethodCall<Self>,283 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,284 CollectionDispatchT<Self>,285 );286 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;287 type ChainId = ChainId;288 type Runner = pallet_evm::runner::stack::Runner<Self>;289 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;290 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;291 type FindAuthor = EthereumFindAuthor<Aura>;292}293294impl pallet_evm_migration::Config for Runtime {295 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;296}297298pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);299impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {300 fn find_author<'a, I>(digests: I) -> Option<H160>301 where302 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,303 {304 if let Some(author_index) = F::find_author(digests) {305 let authority_id = Aura::authorities()[author_index as usize].clone();306 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));307 }308 None309 }310}311312impl pallet_ethereum::Config for Runtime {313 type Event = Event;314 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;315}316317impl pallet_randomness_collective_flip::Config for Runtime {}318319impl frame_system::Config for Runtime {320 /// The data to be stored in an account.321 type AccountData = pallet_balances::AccountData<Balance>;322 /// The identifier used to distinguish between accounts.323 type AccountId = AccountId;324 /// The basic call filter to use in dispatchable.325 type BaseCallFilter = Everything;326 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).327 type BlockHashCount = BlockHashCount;328 /// The maximum length of a block (in bytes).329 type BlockLength = RuntimeBlockLength;330 /// The index type for blocks.331 type BlockNumber = BlockNumber;332 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.333 type BlockWeights = RuntimeBlockWeights;334 /// The aggregated dispatch type that is available for extrinsics.335 type Call = Call;336 /// The weight of database operations that the runtime can invoke.337 type DbWeight = RocksDbWeight;338 /// The ubiquitous event type.339 type Event = Event;340 /// The type for hashing blocks and tries.341 type Hash = Hash;342 /// The hashing algorithm used.343 type Hashing = BlakeTwo256;344 /// The header type.345 type Header = generic::Header<BlockNumber, BlakeTwo256>;346 /// The index type for storing how many extrinsics an account has signed.347 type Index = Index;348 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.349 type Lookup = AccountIdLookup<AccountId, ()>;350 /// What to do if an account is fully reaped from the system.351 type OnKilledAccount = ();352 /// What to do if a new account is created.353 type OnNewAccount = ();354 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;355 /// The ubiquitous origin type.356 type Origin = Origin;357 /// This type is being generated by `construct_runtime!`.358 type PalletInfo = PalletInfo;359 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.360 type SS58Prefix = SS58Prefix;361 /// Weight information for the extrinsics of this pallet.362 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;363 /// Version of the runtime.364 type Version = Version;365 type MaxConsumers = ConstU32<16>;366}367368parameter_types! {369 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;370}371372impl pallet_timestamp::Config for Runtime {373 /// A timestamp: milliseconds since the unix epoch.374 type Moment = u64;375 type OnTimestampSet = ();376 type MinimumPeriod = MinimumPeriod;377 type WeightInfo = ();378}379380parameter_types! {381 // pub const ExistentialDeposit: u128 = 500;382 pub const ExistentialDeposit: u128 = 0;383 pub const MaxLocks: u32 = 50;384}385386impl pallet_balances::Config for Runtime {387 type MaxLocks = MaxLocks;388 type MaxReserves = ();389 type ReserveIdentifier = [u8; 8];390 /// The type for recording an account's balance.391 type Balance = Balance;392 /// The ubiquitous event type.393 type Event = Event;394 type DustRemoval = Treasury;395 type ExistentialDeposit = ExistentialDeposit;396 type AccountStore = System;397 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;398}399400pub const fn deposit(items: u32, bytes: u32) -> Balance {401 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE402}403404/*405parameter_types! {406 pub TombstoneDeposit: Balance = deposit(407 1,408 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,409 );410 pub DepositPerContract: Balance = TombstoneDeposit::get();411 pub const DepositPerStorageByte: Balance = deposit(0, 1);412 pub const DepositPerStorageItem: Balance = deposit(1, 0);413 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);414 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;415 pub const SignedClaimHandicap: u32 = 2;416 pub const MaxDepth: u32 = 32;417 pub const MaxValueSize: u32 = 16 * 1024;418 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb419 // The lazy deletion runs inside on_initialize.420 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *421 RuntimeBlockWeights::get().max_block;422 // The weight needed for decoding the queue should be less or equal than a fifth423 // of the overall weight dedicated to the lazy deletion.424 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (425 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -426 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)427 )) / 5) as u32;428 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();429}430431impl pallet_contracts::Config for Runtime {432 type Time = Timestamp;433 type Randomness = RandomnessCollectiveFlip;434 type Currency = Balances;435 type Event = Event;436 type RentPayment = ();437 type SignedClaimHandicap = SignedClaimHandicap;438 type TombstoneDeposit = TombstoneDeposit;439 type DepositPerContract = DepositPerContract;440 type DepositPerStorageByte = DepositPerStorageByte;441 type DepositPerStorageItem = DepositPerStorageItem;442 type RentFraction = RentFraction;443 type SurchargeReward = SurchargeReward;444 type WeightPrice = pallet_transaction_payment::Pallet<Self>;445 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;446 type ChainExtension = NFTExtension;447 type DeletionQueueDepth = DeletionQueueDepth;448 type DeletionWeightLimit = DeletionWeightLimit;449 type Schedule = Schedule;450 type CallStack = [pallet_contracts::Frame<Self>; 31];451}452*/453454parameter_types! {455 /// This value increases the priority of `Operational` transactions by adding456 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.457 pub const OperationalFeeMultiplier: u8 = 5;458}459460/// Linear implementor of `WeightToFeePolynomial`461pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);462463impl<T> WeightToFeePolynomial for LinearFee<T>464where465 T: BaseArithmetic + From<u32> + Copy + Unsigned,466{467 type Balance = T;468469 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {470 smallvec!(WeightToFeeCoefficient {471 // Targeting 0.1 Unique per NFT transfer472 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),473 coeff_frac: Perbill::zero(),474 negative: false,475 degree: 1,476 })477 }478}479480impl pallet_transaction_payment::Config for Runtime {481 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;482 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;483 type OperationalFeeMultiplier = OperationalFeeMultiplier;484 type WeightToFee = LinearFee<Balance>;485 type FeeMultiplierUpdate = ();486}487488parameter_types! {489 pub const ProposalBond: Permill = Permill::from_percent(5);490 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;491 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;492 pub const SpendPeriod: BlockNumber = 5 * MINUTES;493 pub const Burn: Permill = Permill::from_percent(0);494 pub const TipCountdown: BlockNumber = 1 * DAYS;495 pub const TipFindersFee: Percent = Percent::from_percent(20);496 pub const TipReportDepositBase: Balance = 1 * UNIQUE;497 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;498 pub const BountyDepositBase: Balance = 1 * UNIQUE;499 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;500 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");501 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;502 pub const MaximumReasonLength: u32 = 16384;503 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);504 pub const BountyValueMinimum: Balance = 5 * UNIQUE;505 pub const MaxApprovals: u32 = 100;506}507508impl pallet_treasury::Config for Runtime {509 type PalletId = TreasuryModuleId;510 type Currency = Balances;511 type ApproveOrigin = EnsureRoot<AccountId>;512 type RejectOrigin = EnsureRoot<AccountId>;513 type Event = Event;514 type OnSlash = ();515 type ProposalBond = ProposalBond;516 type ProposalBondMinimum = ProposalBondMinimum;517 type ProposalBondMaximum = ProposalBondMaximum;518 type SpendPeriod = SpendPeriod;519 type Burn = Burn;520 type BurnDestination = ();521 type SpendFunds = ();522 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;523 type MaxApprovals = MaxApprovals;524}525526impl pallet_sudo::Config for Runtime {527 type Event = Event;528 type Call = Call;529}530531pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);532533impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider534 for RelayChainBlockNumberProvider<T>535{536 type BlockNumber = BlockNumber;537538 fn current_block_number() -> Self::BlockNumber {539 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()540 .map(|d| d.relay_parent_number)541 .unwrap_or_default()542 }543}544545parameter_types! {546 pub const MinVestedTransfer: Balance = 10 * UNIQUE;547 pub const MaxVestingSchedules: u32 = 28;548}549550impl orml_vesting::Config for Runtime {551 type Event = Event;552 type Currency = pallet_balances::Pallet<Runtime>;553 type MinVestedTransfer = MinVestedTransfer;554 type VestedTransferOrigin = EnsureSigned<AccountId>;555 type WeightInfo = ();556 type MaxVestingSchedules = MaxVestingSchedules;557 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;558}559560parameter_types! {561 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;563}564565impl cumulus_pallet_parachain_system::Config for Runtime {566 type Event = Event;567 type SelfParaId = parachain_info::Pallet<Self>;568 type OnSystemEvent = ();569 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<570 // MaxDownwardMessageWeight,571 // XcmExecutor<XcmConfig>,572 // Call,573 // >;574 type OutboundXcmpMessageSource = XcmpQueue;575 type DmpMessageHandler = DmpQueue;576 type ReservedDmpWeight = ReservedDmpWeight;577 type ReservedXcmpWeight = ReservedXcmpWeight;578 type XcmpMessageHandler = XcmpQueue;579}580581impl parachain_info::Config for Runtime {}582583impl cumulus_pallet_aura_ext::Config for Runtime {}584585parameter_types! {586 pub const RelayLocation: MultiLocation = MultiLocation::parent();587 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;588 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();589 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();590}591592/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used593/// when determining ownership of accounts for asset transacting and when attempting to use XCM594/// `Transact` in order to determine the dispatch Origin.595pub type LocationToAccountId = (596 // The parent (Relay-chain) origin converts to the default `AccountId`.597 ParentIsPreset<AccountId>,598 // Sibling parachain origins convert to AccountId via the `ParaId::into`.599 SiblingParachainConvertsVia<Sibling, AccountId>,600 // Straight up local `AccountId32` origins just alias directly to `AccountId`.601 AccountId32Aliases<RelayNetwork, AccountId>,602);603604pub struct OnlySelfCurrency;605impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {606 fn matches_fungible(a: &MultiAsset) -> Option<B> {607 match (&a.id, &a.fun) {608 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),609 _ => None,610 }611 }612}613614/// Means for transacting assets on this chain.615pub type LocalAssetTransactor = CurrencyAdapter<616 // Use this currency:617 Balances,618 // Use this currency when it is a fungible asset matching the given location or name:619 OnlySelfCurrency,620 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:621 LocationToAccountId,622 // Our chain's account ID type (we can't get away without mentioning it explicitly):623 AccountId,624 // We don't track any teleports.625 (),626>;627628/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,629/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can630/// biases the kind of local `Origin` it will become.631pub type XcmOriginToTransactDispatchOrigin = (632 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location633 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for634 // foreign chains who want to have a local sovereign account on this chain which they control.635 SovereignSignedViaLocation<LocationToAccountId, Origin>,636 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when637 // recognised.638 RelayChainAsNative<RelayOrigin, Origin>,639 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when640 // recognised.641 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,642 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a643 // transaction from the Root origin.644 ParentAsSuperuser<Origin>,645 // Native signed account converter; this just converts an `AccountId32` origin into a normal646 // `Origin::Signed` origin of the same 32-byte value.647 SignedAccountId32AsNative<RelayNetwork, Origin>,648 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.649 XcmPassthrough<Origin>,650);651652parameter_types! {653 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.654 pub UnitWeightCost: Weight = 1_000_000;655 // 1200 UNIQUEs buy 1 second of weight.656 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);657 pub const MaxInstructions: u32 = 100;658 pub const MaxAuthorities: u32 = 100_000;659}660661match_types! {662 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {663 MultiLocation { parents: 1, interior: Here } |664 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }665 };666}667668pub type Barrier = (669 TakeWeightCredit,670 AllowTopLevelPaidExecutionFrom<Everything>,671 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,672 // ^^^ Parent & its unit plurality gets free execution673);674675pub struct UsingOnlySelfCurrencyComponents<676 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,677 AssetId: Get<MultiLocation>,678 AccountId,679 Currency: CurrencyT<AccountId>,680 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,681>(682 Weight,683 Currency::Balance,684 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,685);686impl<687 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,688 AssetId: Get<MultiLocation>,689 AccountId,690 Currency: CurrencyT<AccountId>,691 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,692 > WeightTrader693 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>694{695 fn new() -> Self {696 Self(0, Zero::zero(), PhantomData)697 }698699 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {700 let amount = WeightToFee::calc(&weight);701 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;702703 // location to this parachain through relay chain704 let option1: xcm::v1::AssetId = Concrete(MultiLocation {705 parents: 1,706 interior: X1(Parachain(ParachainInfo::parachain_id().into())),707 });708 // direct location709 let option2: xcm::v1::AssetId = Concrete(MultiLocation {710 parents: 0,711 interior: Here,712 });713714 let required = if payment.fungible.contains_key(&option1) {715 (option1, u128_amount).into()716 } else if payment.fungible.contains_key(&option2) {717 (option2, u128_amount).into()718 } else {719 (Concrete(MultiLocation::default()), u128_amount).into()720 };721722 let unused = payment723 .checked_sub(required)724 .map_err(|_| XcmError::TooExpensive)?;725 self.0 = self.0.saturating_add(weight);726 self.1 = self.1.saturating_add(amount);727 Ok(unused)728 }729730 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {731 let weight = weight.min(self.0);732 let amount = WeightToFee::calc(&weight);733 self.0 -= weight;734 self.1 = self.1.saturating_sub(amount);735 let amount: u128 = amount.saturated_into();736 if amount > 0 {737 Some((AssetId::get(), amount).into())738 } else {739 None740 }741 }742}743impl<744 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,745 AssetId: Get<MultiLocation>,746 AccountId,747 Currency: CurrencyT<AccountId>,748 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,749 > Drop750 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>751{752 fn drop(&mut self) {753 OnUnbalanced::on_unbalanced(Currency::issue(self.1));754 }755}756757pub struct XcmConfig;758impl Config for XcmConfig {759 type Call = Call;760 type XcmSender = XcmRouter;761 // How to withdraw and deposit an asset.762 type AssetTransactor = LocalAssetTransactor;763 type OriginConverter = XcmOriginToTransactDispatchOrigin;764 type IsReserve = NativeAsset;765 type IsTeleporter = (); // Teleportation is disabled766 type LocationInverter = LocationInverter<Ancestry>;767 type Barrier = Barrier;768 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;769 type Trader = UsingOnlySelfCurrencyComponents<770 IdentityFee<Balance>,771 RelayLocation,772 AccountId,773 Balances,774 (),775 >;776 type ResponseHandler = (); // Don't handle responses for now.777 type SubscriptionService = PolkadotXcm;778779 type AssetTrap = PolkadotXcm;780 type AssetClaims = PolkadotXcm;781}782783// parameter_types! {784// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;785// }786787/// No local origins on this chain are allowed to dispatch XCM sends/executions.788pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);789790/// The means for routing XCM messages which are not for local execution into the right message791/// queues.792pub type XcmRouter = (793 // Two routers - use UMP to communicate with the relay chain:794 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,795 // ..and XCMP to communicate with the sibling chains.796 XcmpQueue,797);798799impl pallet_evm_coder_substrate::Config for Runtime {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 WeightInfo = ();827 type Event = Event;828 type XcmExecutor = XcmExecutor<XcmConfig>;829 type ChannelInfo = ParachainSystem;830 type VersionWrapper = ();831 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;832 type ControllerOrigin = EnsureRoot<AccountId>;833 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;834}835836impl cumulus_pallet_dmp_queue::Config for Runtime {837 type Event = Event;838 type XcmExecutor = XcmExecutor<XcmConfig>;839 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;840}841842impl pallet_aura::Config for Runtime {843 type AuthorityId = AuraId;844 type DisabledValidators = ();845 type MaxAuthorities = MaxAuthorities;846}847848parameter_types! {849 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();850 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;851}852853impl pallet_common::Config for Runtime {854 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;855 type Event = Event;856 type Currency = Balances;857 type CollectionCreationPrice = CollectionCreationPrice;858 type TreasuryAccountId = TreasuryAccountId;859 type CollectionDispatch = CollectionDispatchT<Self>;860861 type EvmTokenAddressMapping = EvmTokenAddressMapping;862 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;863}864865impl pallet_structure::Config for Runtime {866 type Event = Event;867 type Call = Call;868 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;869}870871impl pallet_evm::account::Config for Runtime {872 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;873 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;874 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;875}876877impl pallet_fungible::Config for Runtime {878 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;879}880impl pallet_refungible::Config for Runtime {881 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;882}883impl pallet_nonfungible::Config for Runtime {884 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;885}886887impl pallet_unique::Config for Runtime {888 type Event = Event;889 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;890 type CommonWeightInfo = CommonWeights<Self>;891}892893parameter_types! {894 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied895}896897/// Used for the pallet inflation898impl pallet_inflation::Config for Runtime {899 type Currency = Balances;900 type TreasuryAccountId = TreasuryAccountId;901 type InflationBlockInterval = InflationBlockInterval;902 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;903}904905// parameter_types! {906// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *907// RuntimeBlockWeights::get().max_block;908// pub const MaxScheduledPerBlock: u32 = 50;909// }910911type EvmSponsorshipHandler = (912 UniqueEthSponsorshipHandler<Runtime>,913 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,914);915type SponsorshipHandler = (916 UniqueSponsorshipHandler<Runtime>,917 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,918 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,919);920921// impl pallet_unq_scheduler::Config for Runtime {922// type Event = Event;923// type Origin = Origin;924// type PalletsOrigin = OriginCaller;925// type Call = Call;926// type MaximumWeight = MaximumSchedulerWeight;927// type ScheduleOrigin = EnsureSigned<AccountId>;928// type MaxScheduledPerBlock = MaxScheduledPerBlock;929// type SponsorshipHandler = SponsorshipHandler;930// type WeightInfo = ();931// }932933impl pallet_evm_transaction_payment::Config for Runtime {934 type EvmSponsorshipHandler = EvmSponsorshipHandler;935 type Currency = Balances;936}937938impl pallet_charge_transaction::Config for Runtime {939 type SponsorshipHandler = SponsorshipHandler;940}941942// impl pallet_contract_helpers::Config for Runtime {943// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;944// }945946parameter_types! {947 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049948 pub const HelpersContractAddress: H160 = H160([949 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,950 ]);951}952953impl pallet_evm_contract_helpers::Config for Runtime {954 type ContractAddress = HelpersContractAddress;955 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;956}957958construct_runtime!(959 pub enum Runtime where960 Block = Block,961 NodeBlock = opaque::Block,962 UncheckedExtrinsic = UncheckedExtrinsic963 {964 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,965 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,966967 Aura: pallet_aura::{Pallet, Config<T>} = 22,968 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,969970 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,971 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,972 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,973 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,974 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,975 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,976 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,977 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,978 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,979 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,980981 // XCM helpers.982 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,983 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,984 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,985 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,986987 // Unique Pallets988 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,989 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,990 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,991 // free = 63992 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,993 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,994 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,995 Fungible: pallet_fungible::{Pallet, Storage} = 67,996 Refungible: pallet_refungible::{Pallet, Storage} = 68,997 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,998 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,999 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,10001001 // Frontier1002 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1003 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10041005 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1006 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1007 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1008 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1009 }1010);10111012pub struct TransactionConverter;10131014impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1015 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1016 UncheckedExtrinsic::new_unsigned(1017 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1018 )1019 }1020}10211022impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1023 fn convert_transaction(1024 &self,1025 transaction: pallet_ethereum::Transaction,1026 ) -> opaque::UncheckedExtrinsic {1027 let extrinsic = UncheckedExtrinsic::new_unsigned(1028 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1029 );1030 let encoded = extrinsic.encode();1031 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1032 .expect("Encoded extrinsic is always valid")1033 }1034}10351036/// The address format for describing accounts.1037pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1038/// Block header type as expected by this runtime.1039pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1040/// Block type as expected by this runtime.1041pub type Block = generic::Block<Header, UncheckedExtrinsic>;1042/// A Block signed with a Justification1043pub type SignedBlock = generic::SignedBlock<Block>;1044/// BlockId type as expected by this runtime.1045pub type BlockId = generic::BlockId<Block>;1046/// The SignedExtension to the basic transaction logic.1047pub type SignedExtra = (1048 frame_system::CheckSpecVersion<Runtime>,1049 // system::CheckTxVersion<Runtime>,1050 frame_system::CheckGenesis<Runtime>,1051 frame_system::CheckEra<Runtime>,1052 frame_system::CheckNonce<Runtime>,1053 frame_system::CheckWeight<Runtime>,1054 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1055 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1056 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1057);1058/// Unchecked extrinsic type as expected by this runtime.1059pub type UncheckedExtrinsic =1060 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1061/// Extrinsic type that has already been checked.1062pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1063/// Executive: handles dispatch to the various modules.1064pub type Executive = frame_executive::Executive<1065 Runtime,1066 Block,1067 frame_system::ChainContext<Runtime>,1068 Runtime,1069 AllPalletsReversedWithSystemFirst,1070>;10711072impl_opaque_keys! {1073 pub struct SessionKeys {1074 pub aura: Aura,1075 }1076}10771078impl fp_self_contained::SelfContainedCall for Call {1079 type SignedInfo = H160;10801081 fn is_self_contained(&self) -> bool {1082 match self {1083 Call::Ethereum(call) => call.is_self_contained(),1084 _ => false,1085 }1086 }10871088 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1089 match self {1090 Call::Ethereum(call) => call.check_self_contained(),1091 _ => None,1092 }1093 }10941095 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1096 match self {1097 Call::Ethereum(call) => call.validate_self_contained(info),1098 _ => None,1099 }1100 }11011102 fn pre_dispatch_self_contained(1103 &self,1104 info: &Self::SignedInfo,1105 ) -> Option<Result<(), TransactionValidityError>> {1106 match self {1107 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1108 _ => None,1109 }1110 }11111112 fn apply_self_contained(1113 self,1114 info: Self::SignedInfo,1115 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1116 match self {1117 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1118 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1119 )),1120 _ => None,1121 }1122 }1123}11241125macro_rules! dispatch_unique_runtime {1126 ($collection:ident.$method:ident($($name:ident),*)) => {{1127 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1128 let dispatch = collection.as_dyn();11291130 Ok::<_, DispatchError>(dispatch.$method($($name),*))1131 }};1132}11331134impl_common_runtime_apis!();11351136struct CheckInherents;11371138impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1139 fn check_inherents(1140 block: &Block,1141 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1142 ) -> sp_inherents::CheckInherentsResult {1143 let relay_chain_slot = relay_state_proof1144 .read_slot()1145 .expect("Could not read the relay chain slot from the proof");11461147 let inherent_data =1148 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1149 relay_chain_slot,1150 sp_std::time::Duration::from_secs(6),1151 )1152 .create_inherent_data()1153 .expect("Could not create the timestamp inherent data");11541155 inherent_data.check_extrinsics(block)1156 }1157}11581159cumulus_pallet_parachain_system::register_validate_block!(1160 Runtime = Runtime,1161 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1162 CheckInherents = CheckInherents,1163);