git.delta.rocks / unique-network / refs/commits / 3ae92b8aacb2

difftreelog

refactor move collection dispatch to runtime

Yaroslav Bolyukin2022-04-07parent: #059f10c.patch.diff
in: master

13 files changed

addedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/common/src/dispatch.rs
@@ -0,0 +1,68 @@
+use frame_support::{
+	dispatch::{
+		DispatchResultWithPostInfo, PostDispatchInfo, Weight, DispatchErrorWithPostInfo,
+		DispatchResult,
+	},
+	weights::Pays,
+	traits::Get,
+};
+use up_data_structs::{CollectionId, CreateCollectionData};
+
+use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
+
+// TODO: move to benchmarking
+/// Price of [`dispatch_call`] call with noop `call` argument
+pub fn dispatch_weight<T: Config>() -> Weight {
+	// Read collection
+	<T as frame_system::Config>::DbWeight::get().reads(1)
+	// Dynamic dispatch?
+	+ 6_000_000
+	// submit_logs is measured as part of collection pallets
+}
+
+/// Helper function to implement substrate calls for common collection methods
+pub fn dispatch_call<
+	T: Config,
+	C: FnOnce(&dyn CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
+>(
+	collection: CollectionId,
+	call: C,
+) -> DispatchResultWithPostInfo {
+	let handle =
+		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
+			post_info: PostDispatchInfo {
+				actual_weight: Some(dispatch_weight::<T>()),
+				pays_fee: Pays::Yes,
+			},
+			error,
+		})?;
+	let dispatched = T::CollectionDispatch::dispatch(handle);
+	let mut result = call(dispatched.as_dyn());
+	match &mut result {
+		Ok(PostDispatchInfo {
+			actual_weight: Some(weight),
+			..
+		})
+		| Err(DispatchErrorWithPostInfo {
+			post_info: PostDispatchInfo {
+				actual_weight: Some(weight),
+				..
+			},
+			..
+		}) => *weight += dispatch_weight::<T>(),
+		_ => {}
+	}
+
+	dispatched.into_inner().submit_logs();
+	result
+}
+
+pub trait CollectionDispatch<T: Config> {
+	fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult;
+	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
+
+	fn dispatch(handle: CollectionHandle<T>) -> Self;
+	fn into_inner(self) -> CollectionHandle<T>;
+
+	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
+}
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -21,17 +21,17 @@
 use sp_std::vec::Vec;
 use pallet_evm::account::CrossAccountId;
 use frame_support::{
-	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},
+	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
 	ensure, fail,
-	traits::{Imbalance, Get, Currency},
+	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
 	BoundedVec,
+	weights::Pays,
 };
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
-	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
-	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
-	TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
-	NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,
+	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,
+	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
 	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
 	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit,
 };
@@ -40,6 +40,7 @@
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
+pub mod dispatch;
 pub mod erc;
 pub mod eth;
 
@@ -163,9 +164,11 @@
 	use super::*;
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
 	use pallet_evm::account;
+	use dispatch::CollectionDispatch;
 	use frame_support::traits::Currency;
 	use up_data_structs::TokenId;
 	use scale_info::TypeInfo;
+	use up_evm_mapping::CrossAccountId;
 
 	#[pallet::config]
 	pub trait Config:
@@ -179,6 +182,7 @@
 		type CollectionCreationPrice: Get<
 			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
 		>;
+		type CollectionDispatch: CollectionDispatch<Self>;
 
 		type TreasuryAccountId: Get<Self::AccountId>;
 	}
modifiedpallets/unique/src/common.rsdiffbeforeafterboth
--- a/pallets/unique/src/common.rs
+++ b/pallets/unique/src/common.rs
@@ -16,14 +16,14 @@
 
 use core::marker::PhantomData;
 use frame_support::{weights::Weight};
-use pallet_common::{CommonWeightInfo};
+use pallet_common::{CommonWeightInfo, dispatch::dispatch_weight};
 
 use pallet_fungible::{common::CommonWeights as FungibleWeights};
 use pallet_nonfungible::{common::CommonWeights as NonfungibleWeights};
 use pallet_refungible::{common::CommonWeights as RefungibleWeights};
 use up_data_structs::CreateItemExData;
 
-use crate::{Config, dispatch::dispatch_weight};
+use crate::Config;
 
 macro_rules! max_weight_of {
 	($method:ident ( $($args:tt)* )) => {
@@ -35,7 +35,7 @@
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
-	fn create_item() -> up_data_structs::Weight {
+	fn create_item() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(create_item())
 	}
 
@@ -51,19 +51,19 @@
 		dispatch_weight::<T>() + max_weight_of!(burn_item())
 	}
 
-	fn transfer() -> up_data_structs::Weight {
+	fn transfer() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer())
 	}
 
-	fn approve() -> up_data_structs::Weight {
+	fn approve() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(approve())
 	}
 
-	fn transfer_from() -> up_data_structs::Weight {
+	fn transfer_from() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer_from())
 	}
 
-	fn set_variable_metadata(bytes: u32) -> up_data_structs::Weight {
+	fn set_variable_metadata(bytes: u32) -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
 	}
 
deletedpallets/unique/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/unique/src/dispatch.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use frame_support::{
-	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},
-	traits::Get,
-	weights::Weight,
-};
-use up_data_structs::{CollectionId, CollectionMode, Pays, PostDispatchInfo};
-use pallet_common::{CollectionHandle, CommonCollectionOperations};
-use pallet_fungible::FungibleHandle;
-use pallet_nonfungible::NonfungibleHandle;
-use pallet_refungible::RefungibleHandle;
-
-use crate::Config;
-
-// TODO: move to benchmarking
-/// Price of [`dispatch_call`] call with noop `call` argument
-pub fn dispatch_weight<T: Config>() -> Weight {
-	// Read collection
-	<T as frame_system::Config>::DbWeight::get().reads(1)
-	// Dynamic dispatch?
-	+ 6_000_000
-	// submit_logs is measured as part of collection pallets
-}
-
-pub enum Dispatched<T: Config> {
-	Fungible(FungibleHandle<T>),
-	Nonfungible(NonfungibleHandle<T>),
-	Refungible(RefungibleHandle<T>),
-}
-impl<T: Config> Dispatched<T> {
-	pub fn dispatch(handle: CollectionHandle<T>) -> Self {
-		match handle.mode {
-			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
-			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
-			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
-		}
-	}
-	fn into_inner(self) -> CollectionHandle<T> {
-		match self {
-			Dispatched::Fungible(f) => f.into_inner(),
-			Dispatched::Nonfungible(f) => f.into_inner(),
-			Dispatched::Refungible(f) => f.into_inner(),
-		}
-	}
-	pub fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
-		match self {
-			Dispatched::Fungible(h) => h,
-			Dispatched::Nonfungible(h) => h,
-			Dispatched::Refungible(h) => h,
-		}
-	}
-}
-
-/// Helper function to implement substrate calls for common collection methods
-pub fn dispatch_call<
-	T: Config,
-	C: FnOnce(&dyn pallet_common::CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
->(
-	collection: CollectionId,
-	call: C,
-) -> DispatchResultWithPostInfo {
-	let handle =
-		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(dispatch_weight::<T>()),
-				pays_fee: Pays::Yes,
-			},
-			error,
-		})?;
-	let dispatched = Dispatched::dispatch(handle);
-	let mut result = call(dispatched.as_dyn());
-	match &mut result {
-		Ok(PostDispatchInfo {
-			actual_weight: Some(weight),
-			..
-		})
-		| Err(DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(weight),
-				..
-			},
-			..
-		}) => *weight += dispatch_weight::<T>(),
-		_ => {}
-	}
-
-	dispatched.into_inner().submit_logs();
-	result
-}
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -15,82 +15,3 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 pub mod sponsoring;
-
-use fp_evm::PrecompileResult;
-use pallet_common::{
-	CollectionById,
-	erc::CommonEvmHandler,
-	eth::{map_eth_to_id, map_eth_to_token_id},
-};
-use pallet_fungible::FungibleHandle;
-use pallet_nonfungible::NonfungibleHandle;
-use pallet_refungible::{RefungibleHandle, erc::RefungibleTokenHandle};
-use sp_std::borrow::ToOwned;
-use sp_std::vec::Vec;
-use sp_core::{H160, U256};
-use crate::{CollectionMode, Config, dispatch::Dispatched};
-use pallet_common::CollectionHandle;
-
-pub struct UniqueErcSupport<T: Config>(core::marker::PhantomData<T>);
-
-impl<T: Config> pallet_evm::OnMethodCall<T> for UniqueErcSupport<T> {
-	fn is_reserved(target: &H160) -> bool {
-		map_eth_to_id(target).is_some()
-	}
-	fn is_used(target: &H160) -> bool {
-		map_eth_to_id(target)
-			.map(<CollectionById<T>>::contains_key)
-			.unwrap_or(false)
-	}
-	fn get_code(target: &H160) -> Option<Vec<u8>> {
-		if let Some(collection_id) = map_eth_to_id(target) {
-			let collection = <CollectionById<T>>::get(collection_id)?;
-			Some(
-				match collection.mode {
-					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
-					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
-					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
-				}
-				.to_owned(),
-			)
-		} else if let Some((collection_id, _token_id)) = map_eth_to_token_id(target) {
-			let collection = <CollectionById<T>>::get(collection_id)?;
-			if collection.mode != CollectionMode::ReFungible {
-				return None;
-			}
-			// TODO: check token existence
-			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
-		} else {
-			None
-		}
-	}
-	fn call(
-		source: &H160,
-		target: &H160,
-		gas_limit: u64,
-		input: &[u8],
-		value: U256,
-	) -> Option<PrecompileResult> {
-		if let Some(collection_id) = map_eth_to_id(target) {
-			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
-			let dispatched = Dispatched::dispatch(collection);
-
-			match dispatched {
-				Dispatched::Fungible(h) => h.call(source, input, value),
-				Dispatched::Nonfungible(h) => h.call(source, input, value),
-				Dispatched::Refungible(h) => h.call(source, input, value),
-			}
-		} else if let Some((collection_id, token_id)) = map_eth_to_token_id(target) {
-			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
-			if collection.mode != CollectionMode::ReFungible {
-				return None;
-			}
-
-			let handle = RefungibleHandle::cast(collection);
-			// TODO: check token existence
-			RefungibleTokenHandle(handle, token_id).call(source, input, value)
-		} else {
-			None
-		}
-	}
-}
modifiedpallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/sponsoring.rs
+++ b/pallets/unique/src/eth/sponsoring.rs
@@ -25,6 +25,7 @@
 use core::marker::PhantomData;
 use core::convert::TryInto;
 use pallet_evm::account::CrossAccountId;
+use up_data_structs::{TokenId, CreateItemData, CreateNftData};
 
 use pallet_nonfungible::erc::{
 	UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -26,20 +26,12 @@
 
 pub use serde::{Serialize, Deserialize};
 
-pub use frame_support::{
-	construct_runtime, decl_module, decl_storage, decl_error, decl_event,
+use frame_support::{
+	decl_module, decl_storage, decl_error, decl_event,
 	dispatch::DispatchResult,
-	ensure, fail, parameter_types,
-	traits::{
-		ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,
-		IsSubType, WithdrawReasons,
-	},
-	weights::{
-		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
-		WeightToFeePolynomial, DispatchClass,
-	},
-	StorageValue, transactional,
+	ensure,
+	weights::{Weight},
+	transactional,
 	pallet_prelude::{DispatchResultWithPostInfo, ConstU32},
 	BoundedVec,
 };
@@ -47,17 +39,17 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
-	OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
-	MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData, CollectionLimits, CollectionId,
-	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
-	CreateCollectionData, CustomDataLimit, CreateItemExData,
+	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
+	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
+	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
+	CreateItemExData,
 };
-use pallet_common::{CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo};
 use pallet_evm::account::CrossAccountId;
-use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
-use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
-use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
+use pallet_common::{
+	CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo,
+	dispatch::dispatch_call, dispatch::CollectionDispatch,
+};
 
 #[cfg(test)]
 mod mock;
@@ -70,12 +62,8 @@
 pub use sponsorship::{UniqueSponsorshipHandler, UniqueSponsorshipPredict};
 pub use eth::sponsoring::UniqueEthSponsorshipHandler;
 
-pub use eth::UniqueErcSupport;
-
 pub mod common;
 use common::CommonWeights;
-pub mod dispatch;
-use dispatch::dispatch_call;
 
 #[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
@@ -352,19 +340,11 @@
 		#[weight = <SelfWeightOf<T>>::create_collection()]
 		#[transactional]
 		pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
-			let owner = ensure_signed(origin)?;
+			let sender = ensure_signed(origin)?;
+
+			// =========
 
-			let _id = match data.mode {
-				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
-				CollectionMode::Fungible(decimal_points) => {
-					// check params
-					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					<PalletFungible<T>>::init_collection(owner, data)?
-				}
-				CollectionMode::ReFungible => {
-					<PalletRefungible<T>>::init_collection(owner, data)?
-				}
-			};
+			T::CollectionDispatch::create(sender, data)?;
 
 			Ok(())
 		}
@@ -382,17 +362,11 @@
 		#[transactional]
 		pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_owner(&sender)?;
 
 			// =========
 
-			match collection.mode {
-				CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,
-				CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,
-				CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,
-			}
+			T::CollectionDispatch::destroy(sender, collection)?;
 
 			<NftTransferBasket<T>>::remove_prefix(collection_id, None);
 			<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
modifiedruntime/common/Cargo.tomldiffbeforeafterboth
--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -12,12 +12,19 @@
 default = ['std']
 std = [
     'sp-core/std',
+    'sp-std/std',
     'sp-runtime/std',
     'codec/std',
     'frame-support/std',
     'frame-system/std',
     'sp-consensus-aura/std',
     'pallet-common/std',
+    'pallet-unique/std',
+    'pallet-fungible/std',
+    'pallet-nonfungible/std',
+    'pallet-refungible/std',
+    'up-data-structs/std',
+    'pallet-evm/std',
     'fp-rpc/std',
 ]
 runtime-benchmarks = [
@@ -31,6 +38,11 @@
 git = "https://github.com/paritytech/substrate"
 branch = "polkadot-v0.9.20"
 
+[dependencies.sp-std]
+default-features = false
+git = 'https://github.com/paritytech/substrate.git'
+branch = 'polkadot-v0.9.17'
+
 [dependencies.sp-runtime]
 default-features = false
 git = "https://github.com/paritytech/substrate"
@@ -61,6 +73,31 @@
 default-features = false
 path = "../../pallets/common"
 
+[dependencies.pallet-unique]
+default-features = false
+path = "../../pallets/unique"
+
+[dependencies.pallet-fungible]
+default-features = false
+path = "../../pallets/fungible"
+
+[dependencies.pallet-nonfungible]
+default-features = false
+path = "../../pallets/nonfungible"
+
+[dependencies.pallet-refungible]
+default-features = false
+path = "../../pallets/refungible"
+
+[dependencies.up-data-structs]
+default-features = false
+path = "../../primitives/data-structs"
+
+[dependencies.pallet-evm]
+default-features = false
+git = "https://github.com/uniquenetwork/frontier.git"
+branch = "unique-polkadot-v0.9.17"
+
 [dependencies.sp-consensus-aura]
 default-features = false
 git = "https://github.com/paritytech/substrate"
addedruntime/common/src/dispatch.rsdiffbeforeafterboth
--- /dev/null
+++ b/runtime/common/src/dispatch.rs
@@ -0,0 +1,160 @@
+use frame_support::{dispatch::DispatchResult, ensure};
+use pallet_evm::PrecompileResult;
+use sp_core::{H160, U256};
+use sp_std::{borrow::ToOwned, vec::Vec};
+use pallet_common::{
+	CollectionById, CollectionHandle, CommonCollectionOperations, erc::CommonEvmHandler,
+	eth::map_eth_to_id,
+};
+pub use pallet_common::dispatch::CollectionDispatch;
+use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
+use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
+use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle, erc::RefungibleTokenHandle};
+use up_data_structs::{
+	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
+};
+
+pub enum CollectionDispatchT<T>
+where
+	T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,
+{
+	Fungible(FungibleHandle<T>),
+	Nonfungible(NonfungibleHandle<T>),
+	Refungible(RefungibleHandle<T>),
+}
+impl<T> CollectionDispatch<T> for CollectionDispatchT<T>
+where
+	T: pallet_common::Config
+		+ pallet_unique::Config
+		+ pallet_fungible::Config
+		+ pallet_nonfungible::Config
+		+ pallet_refungible::Config,
+{
+	fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+		let _id = match data.mode {
+			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data)?,
+			CollectionMode::Fungible(decimal_points) => {
+				// check params
+				ensure!(
+					decimal_points <= MAX_DECIMAL_POINTS,
+					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
+				);
+				<PalletFungible<T>>::init_collection(sender, data)?
+			}
+			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,
+		};
+		Ok(())
+	}
+
+	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {
+		match collection.mode {
+			CollectionMode::ReFungible => {
+				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?
+			}
+			CollectionMode::Fungible(_) => {
+				PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?
+			}
+			CollectionMode::NFT => {
+				PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?
+			}
+		}
+		Ok(())
+	}
+
+	fn dispatch(handle: CollectionHandle<T>) -> Self {
+		match handle.mode {
+			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
+			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
+			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
+		}
+	}
+
+	fn into_inner(self) -> CollectionHandle<T> {
+		match self {
+			Self::Fungible(f) => f.into_inner(),
+			Self::Nonfungible(f) => f.into_inner(),
+			Self::Refungible(f) => f.into_inner(),
+		}
+	}
+
+	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
+		match self {
+			Self::Fungible(h) => h,
+			Self::Nonfungible(h) => h,
+			Self::Refungible(h) => h,
+		}
+	}
+}
+
+impl<T> pallet_evm::OnMethodCall<T> for CollectionDispatchT<T>
+where
+	T: pallet_common::Config
+		+ pallet_unique::Config
+		+ pallet_fungible::Config
+		+ pallet_nonfungible::Config
+		+ pallet_refungible::Config,
+{
+	fn is_reserved(target: &H160) -> bool {
+		map_eth_to_id(target).is_some()
+	}
+	fn is_used(target: &H160) -> bool {
+		map_eth_to_id(target)
+			.map(<CollectionById<T>>::contains_key)
+			.unwrap_or(false)
+	}
+	fn get_code(target: &H160) -> Option<Vec<u8>> {
+		if let Some(collection_id) = map_eth_to_id(target) {
+			let collection = <CollectionById<T>>::get(collection_id)?;
+			Some(
+				match collection.mode {
+					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
+					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
+					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
+				}
+				.to_owned(),
+			)
+		} else if let Some((collection_id, _token_id)) =
+			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)
+		{
+			let collection = <CollectionById<T>>::get(collection_id)?;
+			if collection.mode != CollectionMode::ReFungible {
+				return None;
+			}
+			// TODO: check token existence
+			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
+		} else {
+			None
+		}
+	}
+	fn call(
+		source: &H160,
+		target: &H160,
+		gas_limit: u64,
+		input: &[u8],
+		value: U256,
+	) -> Option<PrecompileResult> {
+		if let Some(collection_id) = map_eth_to_id(target) {
+			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+			let dispatched = Self::dispatch(collection);
+
+			match dispatched {
+				Self::Fungible(h) => h.call(source, input, value),
+				Self::Nonfungible(h) => h.call(source, input, value),
+				Self::Refungible(h) => h.call(source, input, value),
+			}
+		} else if let Some((collection_id, token_id)) =
+			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)
+		{
+			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+			if collection.mode != CollectionMode::ReFungible {
+				return None;
+			}
+
+			let handle = RefungibleHandle::cast(collection);
+			// TODO: check token existence
+			RefungibleTokenHandle(handle, token_id).call(source, input, value)
+		} else {
+			None
+		}
+	}
+}
modifiedruntime/common/src/lib.rsdiffbeforeafterboth
--- a/runtime/common/src/lib.rs
+++ b/runtime/common/src/lib.rs
@@ -1,5 +1,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 pub mod constants;
+pub mod dispatch;
 pub mod runtime_apis;
 pub mod types;
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -66,7 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use up_data_structs::*;
+use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
 use frame_system::{
@@ -114,7 +114,12 @@
 //use xcm_executor::traits::MatchesFungible;
 use sp_runtime::traits::CheckedConversion;
 
-use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
+use unique_runtime_common::{
+	impl_common_runtime_apis,
+	types::*,
+	constants::*,
+	dispatch::{CollectionDispatchT, CollectionDispatch},
+};
 
 pub const RUNTIME_NAME: &str = "opal";
 pub const TOKEN_SYMBOL: &str = "OPL";
@@ -295,8 +300,8 @@
 	type Event = Event;
 	type OnMethodCall = (
 		pallet_evm_migration::OnMethodCall<Self>,
-		pallet_unique::UniqueErcSupport<Self>,
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
+		CollectionDispatchT<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -871,8 +876,18 @@
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
+	type CollectionDispatch = CollectionDispatchT<Self>;
+
+	type EvmTokenAddressMapping = EvmTokenAddressMapping;
+	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
 }
 
+impl pallet_structure::Config for Runtime {
+	type Event = Event;
+	type Call = Call;
+	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;
+}
+
 impl pallet_fungible::Config for Runtime {
 	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;
 }
@@ -1119,9 +1134,7 @@
 
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*)) => {{
-		use pallet_unique::dispatch::Dispatched;
-
-		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		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),*))
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -66,6 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
+use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};
 use up_data_structs::*;
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
@@ -92,6 +93,7 @@
 // Polkadot imports
 use pallet_xcm::XcmPassthrough;
 use polkadot_parachain::primitives::Sibling;
+use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -274,8 +276,8 @@
 	type Event = Event;
 	type OnMethodCall = (
 		pallet_evm_migration::OnMethodCall<Self>,
-		pallet_unique::UniqueErcSupport<Self>,
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
+		CollectionDispatchT<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -851,8 +853,18 @@
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
+	type CollectionDispatch = CollectionDispatchT<Self>;
+
+	type EvmTokenAddressMapping = EvmTokenAddressMapping;
+	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
 }
 
+impl pallet_structure::Config for Runtime {
+	type Event = Event;
+	type Call = Call;
+	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;
+}
+
 impl pallet_evm::account::Config for Runtime {
 	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;
 	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
@@ -979,6 +991,7 @@
 		Fungible: pallet_fungible::{Pallet, Storage} = 67,
 		Refungible: pallet_refungible::{Pallet, Storage} = 68,
 		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
+		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
 
 		// Frontier
 		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
@@ -1105,9 +1118,7 @@
 
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*)) => {{
-		use pallet_unique::dispatch::Dispatched;
-
-		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		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),*))
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
after · runtime/unique/src/lib.rs
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::dispatch::{CollectionDispatchT, CollectionDispatch};70use up_data_structs::*;71// use pallet_contracts::weights::WeightInfo;72// #[cfg(any(feature = "std", test))]73use frame_system::{74	self as frame_system, EnsureRoot, EnsureSigned,75	limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78	traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use codec::{Encode, Decode};82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};83use fp_rpc::TransactionStatus;84use sp_runtime::{85	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86	transaction_validity::TransactionValidityError,87	SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102	ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108	//	Xcm,109	AssetId::{Concrete},110	Fungibility::Fungible as XcmFungible,111	MultiAsset,112	Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};119120pub const RUNTIME_NAME: &str = "unique";121pub const TOKEN_SYMBOL: &str = "UNQ";122123type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;124125impl RuntimeInstance for Runtime {126	type CrossAccountId = self::CrossAccountId;127128	type TransactionConverter = self::TransactionConverter;129130	fn get_transaction_converter() -> TransactionConverter {131		TransactionConverter132	}133}134135/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know136/// the specifics of the runtime. They can then be made to be agnostic over specific formats137/// of data like extrinsics, allowing for them to continue syncing the network through upgrades138/// to even the core data structures.139pub mod opaque {140	use sp_std::prelude::*;141	use sp_runtime::impl_opaque_keys;142	use super::Aura;143144	pub use unique_runtime_common::types::*;145146	impl_opaque_keys! {147		pub struct SessionKeys {148			pub aura: Aura,149		}150	}151}152153/// This runtime version.154pub const VERSION: RuntimeVersion = RuntimeVersion {155	spec_name: create_runtime_str!(RUNTIME_NAME),156	impl_name: create_runtime_str!(RUNTIME_NAME),157	authoring_version: 1,158	spec_version: 920000,159	impl_version: 0,160	apis: RUNTIME_API_VERSIONS,161	transaction_version: 1,162	state_version: 0,163};164165#[derive(codec::Encode, codec::Decode)]166pub enum XCMPMessage<XAccountId, XBalance> {167	/// Transfer tokens to the given account from the Parachain account.168	TransferToken(XAccountId, XBalance),169}170171/// The version information used to identify this runtime when compiled natively.172#[cfg(feature = "std")]173pub fn native_version() -> NativeVersion {174	NativeVersion {175		runtime_version: VERSION,176		can_author_with: Default::default(),177	}178}179180type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;181182pub struct DealWithFees;183impl OnUnbalanced<NegativeImbalance> for DealWithFees {184	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {185		if let Some(fees) = fees_then_tips.next() {186			// for fees, 100% to treasury187			let mut split = fees.ration(100, 0);188			if let Some(tips) = fees_then_tips.next() {189				// for tips, if any, 100% to treasury190				tips.ration_merge_into(100, 0, &mut split);191			}192			Treasury::on_unbalanced(split.0);193			// Author::on_unbalanced(split.1);194		}195	}196}197198parameter_types! {199	pub const BlockHashCount: BlockNumber = 2400;200	pub RuntimeBlockLength: BlockLength =201		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);202	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);203	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;204	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()205		.base_block(BlockExecutionWeight::get())206		.for_class(DispatchClass::all(), |weights| {207			weights.base_extrinsic = ExtrinsicBaseWeight::get();208		})209		.for_class(DispatchClass::Normal, |weights| {210			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);211		})212		.for_class(DispatchClass::Operational, |weights| {213			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);214			// Operational transactions have some extra reserved space, so that they215			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.216			weights.reserved = Some(217				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT218			);219		})220		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)221		.build_or_panic();222	pub const Version: RuntimeVersion = VERSION;223	pub const SS58Prefix: u16 = 7391;224}225226parameter_types! {227	pub const ChainId: u64 = 8880;228}229230pub struct FixedFee;231impl FeeCalculator for FixedFee {232	fn min_gas_price() -> U256 {233		MIN_GAS_PRICE.into()234	}235}236237// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case238// (contract, which only writes a lot of data),239// approximating on top of our real store write weight240parameter_types! {241	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;242	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;243	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();244}245246/// Limiting EVM execution to 50% of block for substrate users and management tasks247/// EVM transaction consumes more weight than substrate's, so we can't rely on them being248/// scheduled fairly249const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);250parameter_types! {251	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());252}253254pub enum FixedGasWeightMapping {}255impl GasWeightMapping for FixedGasWeightMapping {256	fn gas_to_weight(gas: u64) -> Weight {257		gas.saturating_mul(WeightPerGas::get())258	}259	fn weight_to_gas(weight: Weight) -> u64 {260		weight / WeightPerGas::get()261	}262}263264impl pallet_evm::Config for Runtime {265	type BlockGasLimit = BlockGasLimit;266	type FeeCalculator = FixedFee;267	type GasWeightMapping = FixedGasWeightMapping;268	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;269	type CallOrigin = EnsureAddressTruncated;270	type WithdrawOrigin = EnsureAddressTruncated;271	type AddressMapping = HashedAddressMapping<Self::Hashing>;272	type PrecompilesType = ();273	type PrecompilesValue = ();274	type Currency = Balances;275	type Event = Event;276	type OnMethodCall = (277		pallet_evm_migration::OnMethodCall<Self>,278		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,279		CollectionDispatchT<Self>,280	);281	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;282	type ChainId = ChainId;283	type Runner = pallet_evm::runner::stack::Runner<Self>;284	type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;285	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;286	type FindAuthor = EthereumFindAuthor<Aura>;287}288289impl pallet_evm_migration::Config for Runtime {290	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;291}292293pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);294impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {295	fn find_author<'a, I>(digests: I) -> Option<H160>296	where297		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,298	{299		if let Some(author_index) = F::find_author(digests) {300			let authority_id = Aura::authorities()[author_index as usize].clone();301			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));302		}303		None304	}305}306307impl pallet_ethereum::Config for Runtime {308	type Event = Event;309	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;310}311312impl pallet_randomness_collective_flip::Config for Runtime {}313314impl frame_system::Config for Runtime {315	/// The data to be stored in an account.316	type AccountData = pallet_balances::AccountData<Balance>;317	/// The identifier used to distinguish between accounts.318	type AccountId = AccountId;319	/// The basic call filter to use in dispatchable.320	type BaseCallFilter = Everything;321	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).322	type BlockHashCount = BlockHashCount;323	/// The maximum length of a block (in bytes).324	type BlockLength = RuntimeBlockLength;325	/// The index type for blocks.326	type BlockNumber = BlockNumber;327	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.328	type BlockWeights = RuntimeBlockWeights;329	/// The aggregated dispatch type that is available for extrinsics.330	type Call = Call;331	/// The weight of database operations that the runtime can invoke.332	type DbWeight = RocksDbWeight;333	/// The ubiquitous event type.334	type Event = Event;335	/// The type for hashing blocks and tries.336	type Hash = Hash;337	/// The hashing algorithm used.338	type Hashing = BlakeTwo256;339	/// The header type.340	type Header = generic::Header<BlockNumber, BlakeTwo256>;341	/// The index type for storing how many extrinsics an account has signed.342	type Index = Index;343	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.344	type Lookup = AccountIdLookup<AccountId, ()>;345	/// What to do if an account is fully reaped from the system.346	type OnKilledAccount = ();347	/// What to do if a new account is created.348	type OnNewAccount = ();349	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;350	/// The ubiquitous origin type.351	type Origin = Origin;352	/// This type is being generated by `construct_runtime!`.353	type PalletInfo = PalletInfo;354	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.355	type SS58Prefix = SS58Prefix;356	/// Weight information for the extrinsics of this pallet.357	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;358	/// Version of the runtime.359	type Version = Version;360	type MaxConsumers = ConstU32<16>;361}362363parameter_types! {364	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;365}366367impl pallet_timestamp::Config for Runtime {368	/// A timestamp: milliseconds since the unix epoch.369	type Moment = u64;370	type OnTimestampSet = ();371	type MinimumPeriod = MinimumPeriod;372	type WeightInfo = ();373}374375parameter_types! {376	// pub const ExistentialDeposit: u128 = 500;377	pub const ExistentialDeposit: u128 = 0;378	pub const MaxLocks: u32 = 50;379}380381impl pallet_balances::Config for Runtime {382	type MaxLocks = MaxLocks;383	type MaxReserves = ();384	type ReserveIdentifier = [u8; 8];385	/// The type for recording an account's balance.386	type Balance = Balance;387	/// The ubiquitous event type.388	type Event = Event;389	type DustRemoval = Treasury;390	type ExistentialDeposit = ExistentialDeposit;391	type AccountStore = System;392	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;393}394395pub const fn deposit(items: u32, bytes: u32) -> Balance {396	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE397}398399/*400parameter_types! {401	pub TombstoneDeposit: Balance = deposit(402		1,403		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,404	);405	pub DepositPerContract: Balance = TombstoneDeposit::get();406	pub const DepositPerStorageByte: Balance = deposit(0, 1);407	pub const DepositPerStorageItem: Balance = deposit(1, 0);408	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);409	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;410	pub const SignedClaimHandicap: u32 = 2;411	pub const MaxDepth: u32 = 32;412	pub const MaxValueSize: u32 = 16 * 1024;413	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb414	// The lazy deletion runs inside on_initialize.415	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *416		RuntimeBlockWeights::get().max_block;417	// The weight needed for decoding the queue should be less or equal than a fifth418	// of the overall weight dedicated to the lazy deletion.419	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (420			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -421			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)422		)) / 5) as u32;423	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();424}425426impl pallet_contracts::Config for Runtime {427	type Time = Timestamp;428	type Randomness = RandomnessCollectiveFlip;429	type Currency = Balances;430	type Event = Event;431	type RentPayment = ();432	type SignedClaimHandicap = SignedClaimHandicap;433	type TombstoneDeposit = TombstoneDeposit;434	type DepositPerContract = DepositPerContract;435	type DepositPerStorageByte = DepositPerStorageByte;436	type DepositPerStorageItem = DepositPerStorageItem;437	type RentFraction = RentFraction;438	type SurchargeReward = SurchargeReward;439	type WeightPrice = pallet_transaction_payment::Pallet<Self>;440	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;441	type ChainExtension = NFTExtension;442	type DeletionQueueDepth = DeletionQueueDepth;443	type DeletionWeightLimit = DeletionWeightLimit;444	type Schedule = Schedule;445	type CallStack = [pallet_contracts::Frame<Self>; 31];446}447*/448449parameter_types! {450	/// This value increases the priority of `Operational` transactions by adding451	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.452	pub const OperationalFeeMultiplier: u8 = 5;453}454455/// Linear implementor of `WeightToFeePolynomial`456pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);457458impl<T> WeightToFeePolynomial for LinearFee<T>459where460	T: BaseArithmetic + From<u32> + Copy + Unsigned,461{462	type Balance = T;463464	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {465		smallvec!(WeightToFeeCoefficient {466			// Targeting 0.1 Unique per NFT transfer467			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),468			coeff_frac: Perbill::zero(),469			negative: false,470			degree: 1,471		})472	}473}474475impl pallet_transaction_payment::Config for Runtime {476	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;477	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;478	type OperationalFeeMultiplier = OperationalFeeMultiplier;479	type WeightToFee = LinearFee<Balance>;480	type FeeMultiplierUpdate = ();481}482483parameter_types! {484	pub const ProposalBond: Permill = Permill::from_percent(5);485	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;486	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;487	pub const SpendPeriod: BlockNumber = 5 * MINUTES;488	pub const Burn: Permill = Permill::from_percent(0);489	pub const TipCountdown: BlockNumber = 1 * DAYS;490	pub const TipFindersFee: Percent = Percent::from_percent(20);491	pub const TipReportDepositBase: Balance = 1 * UNIQUE;492	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;493	pub const BountyDepositBase: Balance = 1 * UNIQUE;494	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;495	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");496	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;497	pub const MaximumReasonLength: u32 = 16384;498	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);499	pub const BountyValueMinimum: Balance = 5 * UNIQUE;500	pub const MaxApprovals: u32 = 100;501}502503impl pallet_treasury::Config for Runtime {504	type PalletId = TreasuryModuleId;505	type Currency = Balances;506	type ApproveOrigin = EnsureRoot<AccountId>;507	type RejectOrigin = EnsureRoot<AccountId>;508	type Event = Event;509	type OnSlash = ();510	type ProposalBond = ProposalBond;511	type ProposalBondMinimum = ProposalBondMinimum;512	type ProposalBondMaximum = ProposalBondMaximum;513	type SpendPeriod = SpendPeriod;514	type Burn = Burn;515	type BurnDestination = ();516	type SpendFunds = ();517	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;518	type MaxApprovals = MaxApprovals;519}520521impl pallet_sudo::Config for Runtime {522	type Event = Event;523	type Call = Call;524}525526pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);527528impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider529	for RelayChainBlockNumberProvider<T>530{531	type BlockNumber = BlockNumber;532533	fn current_block_number() -> Self::BlockNumber {534		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()535			.map(|d| d.relay_parent_number)536			.unwrap_or_default()537	}538}539540parameter_types! {541	pub const MinVestedTransfer: Balance = 10 * UNIQUE;542	pub const MaxVestingSchedules: u32 = 28;543}544545impl orml_vesting::Config for Runtime {546	type Event = Event;547	type Currency = pallet_balances::Pallet<Runtime>;548	type MinVestedTransfer = MinVestedTransfer;549	type VestedTransferOrigin = EnsureSigned<AccountId>;550	type WeightInfo = ();551	type MaxVestingSchedules = MaxVestingSchedules;552	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;553}554555parameter_types! {556	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;557	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;558}559560impl cumulus_pallet_parachain_system::Config for Runtime {561	type Event = Event;562	type SelfParaId = parachain_info::Pallet<Self>;563	type OnSystemEvent = ();564	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<565	// 	MaxDownwardMessageWeight,566	// 	XcmExecutor<XcmConfig>,567	// 	Call,568	// >;569	type OutboundXcmpMessageSource = XcmpQueue;570	type DmpMessageHandler = DmpQueue;571	type ReservedDmpWeight = ReservedDmpWeight;572	type ReservedXcmpWeight = ReservedXcmpWeight;573	type XcmpMessageHandler = XcmpQueue;574}575576impl parachain_info::Config for Runtime {}577578impl cumulus_pallet_aura_ext::Config for Runtime {}579580parameter_types! {581	pub const RelayLocation: MultiLocation = MultiLocation::parent();582	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;583	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();584	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();585}586587/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used588/// when determining ownership of accounts for asset transacting and when attempting to use XCM589/// `Transact` in order to determine the dispatch Origin.590pub type LocationToAccountId = (591	// The parent (Relay-chain) origin converts to the default `AccountId`.592	ParentIsPreset<AccountId>,593	// Sibling parachain origins convert to AccountId via the `ParaId::into`.594	SiblingParachainConvertsVia<Sibling, AccountId>,595	// Straight up local `AccountId32` origins just alias directly to `AccountId`.596	AccountId32Aliases<RelayNetwork, AccountId>,597);598599pub struct OnlySelfCurrency;600impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {601	fn matches_fungible(a: &MultiAsset) -> Option<B> {602		match (&a.id, &a.fun) {603			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),604			_ => None,605		}606	}607}608609/// Means for transacting assets on this chain.610pub type LocalAssetTransactor = CurrencyAdapter<611	// Use this currency:612	Balances,613	// Use this currency when it is a fungible asset matching the given location or name:614	OnlySelfCurrency,615	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:616	LocationToAccountId,617	// Our chain's account ID type (we can't get away without mentioning it explicitly):618	AccountId,619	// We don't track any teleports.620	(),621>;622623/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,624/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can625/// biases the kind of local `Origin` it will become.626pub type XcmOriginToTransactDispatchOrigin = (627	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location628	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for629	// foreign chains who want to have a local sovereign account on this chain which they control.630	SovereignSignedViaLocation<LocationToAccountId, Origin>,631	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when632	// recognised.633	RelayChainAsNative<RelayOrigin, Origin>,634	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when635	// recognised.636	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,637	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a638	// transaction from the Root origin.639	ParentAsSuperuser<Origin>,640	// Native signed account converter; this just converts an `AccountId32` origin into a normal641	// `Origin::Signed` origin of the same 32-byte value.642	SignedAccountId32AsNative<RelayNetwork, Origin>,643	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.644	XcmPassthrough<Origin>,645);646647parameter_types! {648	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.649	pub UnitWeightCost: Weight = 1_000_000;650	// 1200 UNIQUEs buy 1 second of weight.651	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);652	pub const MaxInstructions: u32 = 100;653	pub const MaxAuthorities: u32 = 100_000;654}655656match_types! {657	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {658		MultiLocation { parents: 1, interior: Here } |659		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }660	};661}662663pub type Barrier = (664	TakeWeightCredit,665	AllowTopLevelPaidExecutionFrom<Everything>,666	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,667	// ^^^ Parent & its unit plurality gets free execution668);669670pub struct UsingOnlySelfCurrencyComponents<671	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,672	AssetId: Get<MultiLocation>,673	AccountId,674	Currency: CurrencyT<AccountId>,675	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,676>(677	Weight,678	Currency::Balance,679	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,680);681impl<682		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,683		AssetId: Get<MultiLocation>,684		AccountId,685		Currency: CurrencyT<AccountId>,686		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,687	> WeightTrader688	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>689{690	fn new() -> Self {691		Self(0, Zero::zero(), PhantomData)692	}693694	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {695		let amount = WeightToFee::calc(&weight);696		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;697698		// location to this parachain through relay chain699		let option1: xcm::v1::AssetId = Concrete(MultiLocation {700			parents: 1,701			interior: X1(Parachain(ParachainInfo::parachain_id().into())),702		});703		// direct location704		let option2: xcm::v1::AssetId = Concrete(MultiLocation {705			parents: 0,706			interior: Here,707		});708709		let required = if payment.fungible.contains_key(&option1) {710			(option1, u128_amount).into()711		} else if payment.fungible.contains_key(&option2) {712			(option2, u128_amount).into()713		} else {714			(Concrete(MultiLocation::default()), u128_amount).into()715		};716717		let unused = payment718			.checked_sub(required)719			.map_err(|_| XcmError::TooExpensive)?;720		self.0 = self.0.saturating_add(weight);721		self.1 = self.1.saturating_add(amount);722		Ok(unused)723	}724725	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {726		let weight = weight.min(self.0);727		let amount = WeightToFee::calc(&weight);728		self.0 -= weight;729		self.1 = self.1.saturating_sub(amount);730		let amount: u128 = amount.saturated_into();731		if amount > 0 {732			Some((AssetId::get(), amount).into())733		} else {734			None735		}736	}737}738impl<739		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,740		AssetId: Get<MultiLocation>,741		AccountId,742		Currency: CurrencyT<AccountId>,743		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,744	> Drop745	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>746{747	fn drop(&mut self) {748		OnUnbalanced::on_unbalanced(Currency::issue(self.1));749	}750}751752pub struct XcmConfig;753impl Config for XcmConfig {754	type Call = Call;755	type XcmSender = XcmRouter;756	// How to withdraw and deposit an asset.757	type AssetTransactor = LocalAssetTransactor;758	type OriginConverter = XcmOriginToTransactDispatchOrigin;759	type IsReserve = NativeAsset;760	type IsTeleporter = (); // Teleportation is disabled761	type LocationInverter = LocationInverter<Ancestry>;762	type Barrier = Barrier;763	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;764	type Trader = UsingOnlySelfCurrencyComponents<765		IdentityFee<Balance>,766		RelayLocation,767		AccountId,768		Balances,769		(),770	>;771	type ResponseHandler = (); // Don't handle responses for now.772	type SubscriptionService = PolkadotXcm;773774	type AssetTrap = PolkadotXcm;775	type AssetClaims = PolkadotXcm;776}777778// parameter_types! {779// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;780// }781782/// No local origins on this chain are allowed to dispatch XCM sends/executions.783pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);784785/// The means for routing XCM messages which are not for local execution into the right message786/// queues.787pub type XcmRouter = (788	// Two routers - use UMP to communicate with the relay chain:789	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,790	// ..and XCMP to communicate with the sibling chains.791	XcmpQueue,792);793794impl pallet_evm_coder_substrate::Config for Runtime {795	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;796	type GasWeightMapping = FixedGasWeightMapping;797}798799impl pallet_xcm::Config for Runtime {800	type Event = Event;801	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;802	type XcmRouter = XcmRouter;803	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;804	type XcmExecuteFilter = Everything;805	type XcmExecutor = XcmExecutor<XcmConfig>;806	type XcmTeleportFilter = Everything;807	type XcmReserveTransferFilter = Everything;808	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;809	type LocationInverter = LocationInverter<Ancestry>;810	type Origin = Origin;811	type Call = Call;812	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;813	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;814}815816impl cumulus_pallet_xcm::Config for Runtime {817	type Event = Event;818	type XcmExecutor = XcmExecutor<XcmConfig>;819}820821impl cumulus_pallet_xcmp_queue::Config for Runtime {822	type WeightInfo = ();823	type Event = Event;824	type XcmExecutor = XcmExecutor<XcmConfig>;825	type ChannelInfo = ParachainSystem;826	type VersionWrapper = ();827	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;828	type ControllerOrigin = EnsureRoot<AccountId>;829	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;830}831832impl cumulus_pallet_dmp_queue::Config for Runtime {833	type Event = Event;834	type XcmExecutor = XcmExecutor<XcmConfig>;835	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;836}837838impl pallet_aura::Config for Runtime {839	type AuthorityId = AuraId;840	type DisabledValidators = ();841	type MaxAuthorities = MaxAuthorities;842}843844parameter_types! {845	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();846	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;847}848849impl pallet_common::Config for Runtime {850	type Event = Event;851	type Currency = Balances;852	type CollectionCreationPrice = CollectionCreationPrice;853	type TreasuryAccountId = TreasuryAccountId;854	type CollectionDispatch = CollectionDispatchT<Self>;855856	type EvmTokenAddressMapping = EvmTokenAddressMapping;857	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;858}859860impl pallet_structure::Config for Runtime {861	type Event = Event;862	type Call = Call;863	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;864}865866impl pallet_evm::account::Config for Runtime {867	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;868	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;869	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;870}871872impl pallet_fungible::Config for Runtime {873	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;874}875impl pallet_refungible::Config for Runtime {876	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;877}878impl pallet_nonfungible::Config for Runtime {879	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;880}881882impl pallet_unique::Config for Runtime {883	type Event = Event;884	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;885}886887parameter_types! {888	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied889}890891/// Used for the pallet inflation892impl pallet_inflation::Config for Runtime {893	type Currency = Balances;894	type TreasuryAccountId = TreasuryAccountId;895	type InflationBlockInterval = InflationBlockInterval;896	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;897}898899// parameter_types! {900// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *901// 		RuntimeBlockWeights::get().max_block;902// 	pub const MaxScheduledPerBlock: u32 = 50;903// }904905type EvmSponsorshipHandler = (906	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,907	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,908);909type SponsorshipHandler = (910	pallet_unique::UniqueSponsorshipHandler<Runtime>,911	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,912	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,913);914915// impl pallet_unq_scheduler::Config for Runtime {916// 	type Event = Event;917// 	type Origin = Origin;918// 	type PalletsOrigin = OriginCaller;919// 	type Call = Call;920// 	type MaximumWeight = MaximumSchedulerWeight;921// 	type ScheduleOrigin = EnsureSigned<AccountId>;922// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;923// 	type SponsorshipHandler = SponsorshipHandler;924// 	type WeightInfo = ();925// }926927impl pallet_evm_transaction_payment::Config for Runtime {928	type EvmSponsorshipHandler = EvmSponsorshipHandler;929	type Currency = Balances;930}931932impl pallet_charge_transaction::Config for Runtime {933	type SponsorshipHandler = SponsorshipHandler;934}935936// impl pallet_contract_helpers::Config for Runtime {937//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;938// }939940parameter_types! {941	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049942	pub const HelpersContractAddress: H160 = H160([943		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,944	]);945}946947impl pallet_evm_contract_helpers::Config for Runtime {948	type ContractAddress = HelpersContractAddress;949	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;950}951952construct_runtime!(953	pub enum Runtime where954		Block = Block,955		NodeBlock = opaque::Block,956		UncheckedExtrinsic = UncheckedExtrinsic957	{958		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,959		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,960961		Aura: pallet_aura::{Pallet, Config<T>} = 22,962		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,963964		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,965		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,966		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,967		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,968		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,969		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,970		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,971		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,972		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,973		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,974975		// XCM helpers.976		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,977		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,978		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,979		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,980981		// Unique Pallets982		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,983		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,984		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,985		// free = 63986		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,987		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,988		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,989		Fungible: pallet_fungible::{Pallet, Storage} = 67,990		Refungible: pallet_refungible::{Pallet, Storage} = 68,991		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,992		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,993994		// Frontier995		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,996		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,997998		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,999		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1000		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1001		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1002	}1003);10041005pub struct TransactionConverter;10061007impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1008	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1009		UncheckedExtrinsic::new_unsigned(1010			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1011		)1012	}1013}10141015impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1016	fn convert_transaction(1017		&self,1018		transaction: pallet_ethereum::Transaction,1019	) -> opaque::UncheckedExtrinsic {1020		let extrinsic = UncheckedExtrinsic::new_unsigned(1021			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1022		);1023		let encoded = extrinsic.encode();1024		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1025			.expect("Encoded extrinsic is always valid")1026	}1027}10281029/// The address format for describing accounts.1030pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1031/// Block header type as expected by this runtime.1032pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1033/// Block type as expected by this runtime.1034pub type Block = generic::Block<Header, UncheckedExtrinsic>;1035/// A Block signed with a Justification1036pub type SignedBlock = generic::SignedBlock<Block>;1037/// BlockId type as expected by this runtime.1038pub type BlockId = generic::BlockId<Block>;1039/// The SignedExtension to the basic transaction logic.1040pub type SignedExtra = (1041	frame_system::CheckSpecVersion<Runtime>,1042	// system::CheckTxVersion<Runtime>,1043	frame_system::CheckGenesis<Runtime>,1044	frame_system::CheckEra<Runtime>,1045	frame_system::CheckNonce<Runtime>,1046	frame_system::CheckWeight<Runtime>,1047	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1048	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1049);1050/// Unchecked extrinsic type as expected by this runtime.1051pub type UncheckedExtrinsic =1052	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1053/// Extrinsic type that has already been checked.1054pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1055/// Executive: handles dispatch to the various modules.1056pub type Executive = frame_executive::Executive<1057	Runtime,1058	Block,1059	frame_system::ChainContext<Runtime>,1060	Runtime,1061	AllPalletsReversedWithSystemFirst,1062>;10631064impl_opaque_keys! {1065	pub struct SessionKeys {1066		pub aura: Aura,1067	}1068}10691070impl fp_self_contained::SelfContainedCall for Call {1071	type SignedInfo = H160;10721073	fn is_self_contained(&self) -> bool {1074		match self {1075			Call::Ethereum(call) => call.is_self_contained(),1076			_ => false,1077		}1078	}10791080	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1081		match self {1082			Call::Ethereum(call) => call.check_self_contained(),1083			_ => None,1084		}1085	}10861087	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1088		match self {1089			Call::Ethereum(call) => call.validate_self_contained(info),1090			_ => None,1091		}1092	}10931094	fn pre_dispatch_self_contained(1095		&self,1096		info: &Self::SignedInfo,1097	) -> Option<Result<(), TransactionValidityError>> {1098		match self {1099			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1100			_ => None,1101		}1102	}11031104	fn apply_self_contained(1105		self,1106		info: Self::SignedInfo,1107	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1108		match self {1109			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1110				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1111			)),1112			_ => None,1113		}1114	}1115}11161117macro_rules! dispatch_unique_runtime {1118	($collection:ident.$method:ident($($name:ident),*)) => {{1119		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1120		let dispatch = collection.as_dyn();11211122		Ok(dispatch.$method($($name),*))1123	}};1124}11251126impl_common_runtime_apis!();11271128struct CheckInherents;11291130impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1131	fn check_inherents(1132		block: &Block,1133		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1134	) -> sp_inherents::CheckInherentsResult {1135		let relay_chain_slot = relay_state_proof1136			.read_slot()1137			.expect("Could not read the relay chain slot from the proof");11381139		let inherent_data =1140			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1141				relay_chain_slot,1142				sp_std::time::Duration::from_secs(6),1143			)1144			.create_inherent_data()1145			.expect("Could not create the timestamp inherent data");11461147		inherent_data.check_extrinsics(block)1148	}1149}11501151cumulus_pallet_parachain_system::register_validate_block!(1152	Runtime = Runtime,1153	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1154	CheckInherents = CheckInherents,1155);