git.delta.rocks / unique-network / refs/commits / cf8cdb9aa8d5

difftreelog

CORE-345 Split evm collection to collection and helper

Trubnikov Sergey2022-05-18parent: #2cfa7af.patch.diff
in: master

16 files changed

modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,9 @@
 COLLECTION_STUBS=./pallets/unique/src/eth/stubs/
 COLLECTION_ABI=./tests/src/eth/collectionAbi.json
 
+COLLECTION_HELPER_STUBS=$(COLLECTION_STUBS)
+COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelperAbi.json
+
 TESTS_API=./tests/src/eth/api/
 
 .PHONY: regenerate_solidity
@@ -36,9 +39,13 @@
 	PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
 
 Collection.sol:
-	PACKAGE=pallet-unique NAME=eth::pallet_evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
-	PACKAGE=pallet-unique NAME=eth::pallet_evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-unique NAME=eth::evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-unique NAME=eth::evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
 
+CollectionHelper.sol:
+	PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
 UniqueFungible: UniqueFungible.sol
 	INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
 	INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
@@ -55,7 +62,11 @@
 	INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_STUBS)/Collection.raw ./.maintain/scripts/compile_stub.sh
 	INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_ABI) ./.maintain/scripts/generate_abi.sh
 
-evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection
+CollectionHelper: CollectionHelper.sol
+	INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelper.raw ./.maintain/scripts/compile_stub.sh
+	INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_ABI) ./.maintain/scripts/generate_abi.sh
+
+evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection CollectionHelper
 
 .PHONY: _bench
 _bench:
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -112,7 +112,6 @@
 	use sp_std::{vec::Vec, rc::Rc};
 	use alloc::format;
 	
-	// #[pallet::config]
 	pub trait Config:
 		frame_system::Config
 		+ pallet_evm_coder_substrate::Config
@@ -122,8 +121,8 @@
 		type ContractAddress: Get<H160>;
 	}
 
-	struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
-	impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+	struct EvmCollectionHelper<T: Config>(Rc<SubstrateRecorder<T>>);
+	impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
 		fn recorder(&self) -> &SubstrateRecorder<T> {
 			&self.0
 		}
@@ -132,19 +131,9 @@
 			self.0
 		}
 	}
-	
-	#[derive(ToLog)]
-	pub enum EthCollectionEvent {
-		CollectionCreated {
-			#[indexed]
-			owner: address,
-			#[indexed]
-			collection_id: address,
-		},
-	}
-	
-	#[solidity_interface(name = "Collection")]
-	impl<T: Config> EvmCollection<T> {
+
+	#[solidity_interface(name = "CollectionHelper")]
+	impl<T: Config> EvmCollectionHelper<T> {
 		fn create_721_collection(
 			&self,
 			caller: caller,
@@ -188,14 +177,37 @@
 			});
 			Ok(address)
 		}
+	}
+	
+	struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
+	impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+		fn recorder(&self) -> &SubstrateRecorder<T> {
+			&self.0
+		}
+	
+		fn into_recorder(self) -> Rc<SubstrateRecorder<T>> {
+			self.0
+		}
+	}
+	
+	#[derive(ToLog)]
+	pub enum EthCollectionEvent {
+		CollectionCreated {
+			#[indexed]
+			owner: address,
+			#[indexed]
+			collection_id: address,
+		},
+	}
 	
+	#[solidity_interface(name = "Collection")]
+	impl<T: Config> EvmCollection<T> {
 		fn set_sponsor(
 			&self,
 			caller: caller,
-			collection_address: address,
 			sponsor: address,
 		) -> Result<void> {
-			let mut collection = collection_from_address(collection_address, &self.0)?;
+			let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
 			check_is_owner(caller, &collection)?;
 	
 			let sponsor = T::CrossAccountId::from_eth(sponsor);
@@ -203,8 +215,8 @@
 			save_eth(collection)
 		}
 	
-		fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {
-			let mut collection = collection_from_address(collection_address, &self.0)?;
+		fn confirm_sponsorship(&self, caller: caller) -> Result<void> {
+			let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
 			let caller = T::CrossAccountId::from_eth(caller);
 			if !collection.confirm_sponsorship(caller.as_sub()) {
 				return Err(Error::Revert("Caller is not set as sponsor".into()));
@@ -215,10 +227,9 @@
 		fn set_limits(
 			&self,
 			caller: caller,
-			collection_address: address,
 			limits_json: string,
 		) -> Result<void> {
-			let mut collection = collection_from_address(collection_address, &self.0)?;
+			let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
 			check_is_owner(caller, &collection)?;
 	
 			let limits = serde_json_core::from_str(limits_json.as_ref())
@@ -226,6 +237,10 @@
 			collection.limits = limits.0;
 			save_eth(collection)
 		}
+
+		fn contract_address(&self, _caller: caller) -> Result<address> {
+			Ok(self.0.contract())
+		}
 	}
 	
 	fn error_feild_too_long(feild: &str, bound: u32) -> Error {
@@ -251,9 +266,9 @@
 			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 		Ok(())
 	}
-	
-	pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
-	impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
+
+	pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
+	impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
 		fn is_reserved(contract: &sp_core::H160) -> bool {
 			contract == &T::ContractAddress::get()
 		}
@@ -273,6 +288,36 @@
 				return None;
 			}
 	
+			let helpers = EvmCollectionHelper::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
+			pallet_evm_coder_substrate::call(*source, helpers, value, input)
+		}
+	
+		fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
+			(contract == &T::ContractAddress::get())
+				.then(|| include_bytes!("./stubs/CollectionHelper.raw").to_vec())
+		}
+	}
+	
+	generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);
+	generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);
+	
+	pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
+	impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
+		fn is_reserved(contract: &sp_core::H160) -> bool {
+			contract == &T::ContractAddress::get()
+		}
+	
+		fn is_used(contract: &sp_core::H160) -> bool {
+			contract == &T::ContractAddress::get()
+		}
+	
+		fn call(
+			source: &sp_core::H160,
+			target: &sp_core::H160,
+			gas_left: u64,
+			input: &[u8],
+			value: sp_core::U256,
+		) -> Option<PrecompileResult> {
 			let helpers = EvmCollection::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
 			pallet_evm_coder_substrate::call(*source, helpers, value, input)
 		}
modifiedpallets/unique/src/eth/stubs/Collection.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/Collection.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/Collection.sol
+++ b/pallets/unique/src/eth/stubs/Collection.sol
@@ -21,48 +21,32 @@
 	}
 }
 
-// Selector: 1e95830f
+// Selector: 15cc740e
 contract Collection is Dummy, ERC165 {
-	// Selector: create721Collection(string,string,string) 951c0151
-	function create721Collection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix
-	) public view returns (address) {
+	// Selector: setSponsor(address) 59753fb1
+	function setSponsor(address sponsor) public view {
 		require(false, stub_error);
-		name;
-		description;
-		tokenPrefix;
+		sponsor;
 		dummy;
-		return 0x0000000000000000000000000000000000000000;
 	}
 
-	// Selector: setSponsor(address,address) f01fba93
-	function setSponsor(address collectionAddress, address sponsor)
-		public
-		view
-	{
+	// Selector: confirmSponsorship() c8c6a056
+	function confirmSponsorship() public view {
 		require(false, stub_error);
-		collectionAddress;
-		sponsor;
 		dummy;
 	}
 
-	// Selector: confirmSponsorship(address) abc00001
-	function confirmSponsorship(address collectionAddress) public view {
+	// Selector: setLimits(string) 72cb345d
+	function setLimits(string memory limitsJson) public view {
 		require(false, stub_error);
-		collectionAddress;
+		limitsJson;
 		dummy;
 	}
 
-	// Selector: setLimits(address,string) d05638cc
-	function setLimits(address collectionAddress, string memory limitsJson)
-		public
-		view
-	{
+	// Selector: contractAddress() f6b4dfb4
+	function contractAddress() public view returns (address) {
 		require(false, stub_error);
-		collectionAddress;
-		limitsJson;
 		dummy;
+		return 0x0000000000000000000000000000000000000000;
 	}
 }
addedpallets/unique/src/eth/stubs/CollectionHelper.rawdiffbeforeafterboth

binary blob — no preview

addedpallets/unique/src/eth/stubs/CollectionHelper.soldiffbeforeafterboth
--- /dev/null
+++ b/pallets/unique/src/eth/stubs/CollectionHelper.sol
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+contract Dummy {
+	uint8 dummy;
+	string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+	function supportsInterface(bytes4 interfaceID)
+		external
+		view
+		returns (bool)
+	{
+		require(false, stub_error);
+		interfaceID;
+		return true;
+	}
+}
+
+// Selector: 951c0151
+contract CollectionHelper is Dummy, ERC165 {
+	// Selector: create721Collection(string,string,string) 951c0151
+	function create721Collection(
+		string memory name,
+		string memory description,
+		string memory tokenPrefix
+	) public view returns (address) {
+		require(false, stub_error);
+		name;
+		description;
+		tokenPrefix;
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
+}
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -308,6 +308,7 @@
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
 		CollectionDispatchT<Self>,
 		evm_collection::CollectionOnMethodCall<Self>,
+		evm_collection::CollectionHelperOnMethodCall<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -978,7 +979,7 @@
 	]);
 
 	// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
-	pub const EvmCollectionAddress: H160 = H160([
+	pub const EvmCollectionHelperAddress: H160 = H160([
 		0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
 	]);
 }
@@ -989,7 +990,7 @@
 }
 
 impl evm_collection::Config for Runtime {
-	type ContractAddress = EvmCollectionAddress;
+	type ContractAddress = EvmCollectionHelperAddress;
 }
 
 construct_runtime!(
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
before · runtime/quartz/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, OnMethodCall};83use pallet_unique::evm_collection;84use fp_rpc::TransactionStatus;85use sp_runtime::{86	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},87	transaction_validity::TransactionValidityError,88	SaturatedConversion,89};9091// pub use pallet_timestamp::Call as TimestampCall;92pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9394// Polkadot imports95use pallet_xcm::XcmPassthrough;96use polkadot_parachain::primitives::Sibling;97use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};98use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};99use xcm_builder::{100	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,101	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,102	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,103	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,104	ParentIsPreset,105};106use xcm_executor::{Config, XcmExecutor, Assets};107use sp_std::{marker::PhantomData};108109use xcm::latest::{110	//	Xcm,111	AssetId::{Concrete},112	Fungibility::Fungible as XcmFungible,113	MultiAsset,114	Error as XcmError,115};116use xcm_executor::traits::{MatchesFungible, WeightTrader};117//use xcm_executor::traits::MatchesFungible;118use sp_runtime::traits::CheckedConversion;119120use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};121122pub const RUNTIME_NAME: &str = "quartz";123pub const TOKEN_SYMBOL: &str = "QTZ";124125type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;126127impl RuntimeInstance for Runtime {128	type CrossAccountId = self::CrossAccountId;129130	type TransactionConverter = self::TransactionConverter;131132	fn get_transaction_converter() -> TransactionConverter {133		TransactionConverter134	}135}136137/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know138/// the specifics of the runtime. They can then be made to be agnostic over specific formats139/// of data like extrinsics, allowing for them to continue syncing the network through upgrades140/// to even the core data structures.141pub mod opaque {142	use sp_std::prelude::*;143	use sp_runtime::impl_opaque_keys;144	use super::Aura;145146	pub use unique_runtime_common::types::*;147148	impl_opaque_keys! {149		pub struct SessionKeys {150			pub aura: Aura,151		}152	}153}154155/// This runtime version.156pub const VERSION: RuntimeVersion = RuntimeVersion {157	spec_name: create_runtime_str!(RUNTIME_NAME),158	impl_name: create_runtime_str!(RUNTIME_NAME),159	authoring_version: 1,160	spec_version: 920000,161	impl_version: 0,162	apis: RUNTIME_API_VERSIONS,163	transaction_version: 1,164	state_version: 0,165};166167#[derive(codec::Encode, codec::Decode)]168pub enum XCMPMessage<XAccountId, XBalance> {169	/// Transfer tokens to the given account from the Parachain account.170	TransferToken(XAccountId, XBalance),171}172173/// The version information used to identify this runtime when compiled natively.174#[cfg(feature = "std")]175pub fn native_version() -> NativeVersion {176	NativeVersion {177		runtime_version: VERSION,178		can_author_with: Default::default(),179	}180}181182type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;183184pub struct DealWithFees;185impl OnUnbalanced<NegativeImbalance> for DealWithFees {186	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {187		if let Some(fees) = fees_then_tips.next() {188			// for fees, 100% to treasury189			let mut split = fees.ration(100, 0);190			if let Some(tips) = fees_then_tips.next() {191				// for tips, if any, 100% to treasury192				tips.ration_merge_into(100, 0, &mut split);193			}194			Treasury::on_unbalanced(split.0);195			// Author::on_unbalanced(split.1);196		}197	}198}199200parameter_types! {201	pub const BlockHashCount: BlockNumber = 2400;202	pub RuntimeBlockLength: BlockLength =203		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);204	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);205	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;206	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()207		.base_block(BlockExecutionWeight::get())208		.for_class(DispatchClass::all(), |weights| {209			weights.base_extrinsic = ExtrinsicBaseWeight::get();210		})211		.for_class(DispatchClass::Normal, |weights| {212			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);213		})214		.for_class(DispatchClass::Operational, |weights| {215			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);216			// Operational transactions have some extra reserved space, so that they217			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.218			weights.reserved = Some(219				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT220			);221		})222		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)223		.build_or_panic();224	pub const Version: RuntimeVersion = VERSION;225	pub const SS58Prefix: u8 = 255;226}227228parameter_types! {229	pub const ChainId: u64 = 8881;230}231232pub struct FixedFee;233impl FeeCalculator for FixedFee {234	fn min_gas_price() -> U256 {235		MIN_GAS_PRICE.into()236	}237}238239// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case240// (contract, which only writes a lot of data),241// approximating on top of our real store write weight242parameter_types! {243	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;244	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;245	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();246}247248/// Limiting EVM execution to 50% of block for substrate users and management tasks249/// EVM transaction consumes more weight than substrate's, so we can't rely on them being250/// scheduled fairly251const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);252parameter_types! {253	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());254}255256pub enum FixedGasWeightMapping {}257impl GasWeightMapping for FixedGasWeightMapping {258	fn gas_to_weight(gas: u64) -> Weight {259		gas.saturating_mul(WeightPerGas::get())260	}261	fn weight_to_gas(weight: Weight) -> u64 {262		weight / WeightPerGas::get()263	}264}265266impl pallet_evm::Config for Runtime {267	type BlockGasLimit = BlockGasLimit;268	type FeeCalculator = FixedFee;269	type GasWeightMapping = FixedGasWeightMapping;270	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;271	type CallOrigin = EnsureAddressTruncated<Self>;272	type WithdrawOrigin = EnsureAddressTruncated<Self>;273	type AddressMapping = HashedAddressMapping<Self::Hashing>;274	type PrecompilesType = ();275	type PrecompilesValue = ();276	type Currency = Balances;277	type Event = Event;278	type OnMethodCall = (279		pallet_evm_migration::OnMethodCall<Self>,280		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,281		CollectionDispatchT<Self>,282		evm_collection::CollectionOnMethodCall<Self>,283	);284	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;285	type ChainId = ChainId;286	type Runner = pallet_evm::runner::stack::Runner<Self>;287	type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;288	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;289	type FindAuthor = EthereumFindAuthor<Aura>;290}291292impl pallet_evm_migration::Config for Runtime {293	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;294}295296pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);297impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {298	fn find_author<'a, I>(digests: I) -> Option<H160>299	where300		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,301	{302		if let Some(author_index) = F::find_author(digests) {303			let authority_id = Aura::authorities()[author_index as usize].clone();304			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));305		}306		None307	}308}309310impl pallet_ethereum::Config for Runtime {311	type Event = Event;312	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;313}314315impl pallet_randomness_collective_flip::Config for Runtime {}316317impl frame_system::Config for Runtime {318	/// The data to be stored in an account.319	type AccountData = pallet_balances::AccountData<Balance>;320	/// The identifier used to distinguish between accounts.321	type AccountId = AccountId;322	/// The basic call filter to use in dispatchable.323	type BaseCallFilter = Everything;324	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).325	type BlockHashCount = BlockHashCount;326	/// The maximum length of a block (in bytes).327	type BlockLength = RuntimeBlockLength;328	/// The index type for blocks.329	type BlockNumber = BlockNumber;330	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.331	type BlockWeights = RuntimeBlockWeights;332	/// The aggregated dispatch type that is available for extrinsics.333	type Call = Call;334	/// The weight of database operations that the runtime can invoke.335	type DbWeight = RocksDbWeight;336	/// The ubiquitous event type.337	type Event = Event;338	/// The type for hashing blocks and tries.339	type Hash = Hash;340	/// The hashing algorithm used.341	type Hashing = BlakeTwo256;342	/// The header type.343	type Header = generic::Header<BlockNumber, BlakeTwo256>;344	/// The index type for storing how many extrinsics an account has signed.345	type Index = Index;346	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.347	type Lookup = AccountIdLookup<AccountId, ()>;348	/// What to do if an account is fully reaped from the system.349	type OnKilledAccount = ();350	/// What to do if a new account is created.351	type OnNewAccount = ();352	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;353	/// The ubiquitous origin type.354	type Origin = Origin;355	/// This type is being generated by `construct_runtime!`.356	type PalletInfo = PalletInfo;357	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.358	type SS58Prefix = SS58Prefix;359	/// Weight information for the extrinsics of this pallet.360	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;361	/// Version of the runtime.362	type Version = Version;363	type MaxConsumers = ConstU32<16>;364}365366parameter_types! {367	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;368}369370impl pallet_timestamp::Config for Runtime {371	/// A timestamp: milliseconds since the unix epoch.372	type Moment = u64;373	type OnTimestampSet = ();374	type MinimumPeriod = MinimumPeriod;375	type WeightInfo = ();376}377378parameter_types! {379	// pub const ExistentialDeposit: u128 = 500;380	pub const ExistentialDeposit: u128 = 0;381	pub const MaxLocks: u32 = 50;382}383384impl pallet_balances::Config for Runtime {385	type MaxLocks = MaxLocks;386	type MaxReserves = ();387	type ReserveIdentifier = [u8; 8];388	/// The type for recording an account's balance.389	type Balance = Balance;390	/// The ubiquitous event type.391	type Event = Event;392	type DustRemoval = Treasury;393	type ExistentialDeposit = ExistentialDeposit;394	type AccountStore = System;395	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;396}397398pub const fn deposit(items: u32, bytes: u32) -> Balance {399	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE400}401402/*403parameter_types! {404	pub TombstoneDeposit: Balance = deposit(405		1,406		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,407	);408	pub DepositPerContract: Balance = TombstoneDeposit::get();409	pub const DepositPerStorageByte: Balance = deposit(0, 1);410	pub const DepositPerStorageItem: Balance = deposit(1, 0);411	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);412	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;413	pub const SignedClaimHandicap: u32 = 2;414	pub const MaxDepth: u32 = 32;415	pub const MaxValueSize: u32 = 16 * 1024;416	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb417	// The lazy deletion runs inside on_initialize.418	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *419		RuntimeBlockWeights::get().max_block;420	// The weight needed for decoding the queue should be less or equal than a fifth421	// of the overall weight dedicated to the lazy deletion.422	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (423			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -424			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)425		)) / 5) as u32;426	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();427}428429impl pallet_contracts::Config for Runtime {430	type Time = Timestamp;431	type Randomness = RandomnessCollectiveFlip;432	type Currency = Balances;433	type Event = Event;434	type RentPayment = ();435	type SignedClaimHandicap = SignedClaimHandicap;436	type TombstoneDeposit = TombstoneDeposit;437	type DepositPerContract = DepositPerContract;438	type DepositPerStorageByte = DepositPerStorageByte;439	type DepositPerStorageItem = DepositPerStorageItem;440	type RentFraction = RentFraction;441	type SurchargeReward = SurchargeReward;442	type WeightPrice = pallet_transaction_payment::Pallet<Self>;443	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;444	type ChainExtension = NFTExtension;445	type DeletionQueueDepth = DeletionQueueDepth;446	type DeletionWeightLimit = DeletionWeightLimit;447	type Schedule = Schedule;448	type CallStack = [pallet_contracts::Frame<Self>; 31];449}450*/451452parameter_types! {453	/// This value increases the priority of `Operational` transactions by adding454	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.455	pub const OperationalFeeMultiplier: u8 = 5;456}457458/// Linear implementor of `WeightToFeePolynomial`459pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);460461impl<T> WeightToFeePolynomial for LinearFee<T>462where463	T: BaseArithmetic + From<u32> + Copy + Unsigned,464{465	type Balance = T;466467	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {468		smallvec!(WeightToFeeCoefficient {469			// Targeting 0.1 Unique per NFT transfer470			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),471			coeff_frac: Perbill::zero(),472			negative: false,473			degree: 1,474		})475	}476}477478impl pallet_transaction_payment::Config for Runtime {479	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;480	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;481	type OperationalFeeMultiplier = OperationalFeeMultiplier;482	type WeightToFee = LinearFee<Balance>;483	type FeeMultiplierUpdate = ();484}485486parameter_types! {487	pub const ProposalBond: Permill = Permill::from_percent(5);488	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;489	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;490	pub const SpendPeriod: BlockNumber = 5 * MINUTES;491	pub const Burn: Permill = Permill::from_percent(0);492	pub const TipCountdown: BlockNumber = 1 * DAYS;493	pub const TipFindersFee: Percent = Percent::from_percent(20);494	pub const TipReportDepositBase: Balance = 1 * UNIQUE;495	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;496	pub const BountyDepositBase: Balance = 1 * UNIQUE;497	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;498	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");499	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;500	pub const MaximumReasonLength: u32 = 16384;501	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);502	pub const BountyValueMinimum: Balance = 5 * UNIQUE;503	pub const MaxApprovals: u32 = 100;504}505506impl pallet_treasury::Config for Runtime {507	type PalletId = TreasuryModuleId;508	type Currency = Balances;509	type ApproveOrigin = EnsureRoot<AccountId>;510	type RejectOrigin = EnsureRoot<AccountId>;511	type Event = Event;512	type OnSlash = ();513	type ProposalBond = ProposalBond;514	type ProposalBondMinimum = ProposalBondMinimum;515	type ProposalBondMaximum = ProposalBondMaximum;516	type SpendPeriod = SpendPeriod;517	type Burn = Burn;518	type BurnDestination = ();519	type SpendFunds = ();520	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;521	type MaxApprovals = MaxApprovals;522}523524impl pallet_sudo::Config for Runtime {525	type Event = Event;526	type Call = Call;527}528529pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);530531impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider532	for RelayChainBlockNumberProvider<T>533{534	type BlockNumber = BlockNumber;535536	fn current_block_number() -> Self::BlockNumber {537		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()538			.map(|d| d.relay_parent_number)539			.unwrap_or_default()540	}541}542543parameter_types! {544	pub const MinVestedTransfer: Balance = 10 * UNIQUE;545	pub const MaxVestingSchedules: u32 = 28;546}547548impl orml_vesting::Config for Runtime {549	type Event = Event;550	type Currency = pallet_balances::Pallet<Runtime>;551	type MinVestedTransfer = MinVestedTransfer;552	type VestedTransferOrigin = EnsureSigned<AccountId>;553	type WeightInfo = ();554	type MaxVestingSchedules = MaxVestingSchedules;555	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;556}557558parameter_types! {559	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;560	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;561}562563impl cumulus_pallet_parachain_system::Config for Runtime {564	type Event = Event;565	type SelfParaId = parachain_info::Pallet<Self>;566	type OnSystemEvent = ();567	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<568	// 	MaxDownwardMessageWeight,569	// 	XcmExecutor<XcmConfig>,570	// 	Call,571	// >;572	type OutboundXcmpMessageSource = XcmpQueue;573	type DmpMessageHandler = DmpQueue;574	type ReservedDmpWeight = ReservedDmpWeight;575	type ReservedXcmpWeight = ReservedXcmpWeight;576	type XcmpMessageHandler = XcmpQueue;577}578579impl parachain_info::Config for Runtime {}580581impl cumulus_pallet_aura_ext::Config for Runtime {}582583parameter_types! {584	pub const RelayLocation: MultiLocation = MultiLocation::parent();585	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;586	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();587	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();588}589590/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used591/// when determining ownership of accounts for asset transacting and when attempting to use XCM592/// `Transact` in order to determine the dispatch Origin.593pub type LocationToAccountId = (594	// The parent (Relay-chain) origin converts to the default `AccountId`.595	ParentIsPreset<AccountId>,596	// Sibling parachain origins convert to AccountId via the `ParaId::into`.597	SiblingParachainConvertsVia<Sibling, AccountId>,598	// Straight up local `AccountId32` origins just alias directly to `AccountId`.599	AccountId32Aliases<RelayNetwork, AccountId>,600);601602pub struct OnlySelfCurrency;603impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {604	fn matches_fungible(a: &MultiAsset) -> Option<B> {605		match (&a.id, &a.fun) {606			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),607			_ => None,608		}609	}610}611612/// Means for transacting assets on this chain.613pub type LocalAssetTransactor = CurrencyAdapter<614	// Use this currency:615	Balances,616	// Use this currency when it is a fungible asset matching the given location or name:617	OnlySelfCurrency,618	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:619	LocationToAccountId,620	// Our chain's account ID type (we can't get away without mentioning it explicitly):621	AccountId,622	// We don't track any teleports.623	(),624>;625626/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,627/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can628/// biases the kind of local `Origin` it will become.629pub type XcmOriginToTransactDispatchOrigin = (630	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location631	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for632	// foreign chains who want to have a local sovereign account on this chain which they control.633	SovereignSignedViaLocation<LocationToAccountId, Origin>,634	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when635	// recognised.636	RelayChainAsNative<RelayOrigin, Origin>,637	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when638	// recognised.639	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,640	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a641	// transaction from the Root origin.642	ParentAsSuperuser<Origin>,643	// Native signed account converter; this just converts an `AccountId32` origin into a normal644	// `Origin::Signed` origin of the same 32-byte value.645	SignedAccountId32AsNative<RelayNetwork, Origin>,646	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.647	XcmPassthrough<Origin>,648);649650parameter_types! {651	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.652	pub UnitWeightCost: Weight = 1_000_000;653	// 1200 UNIQUEs buy 1 second of weight.654	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);655	pub const MaxInstructions: u32 = 100;656	pub const MaxAuthorities: u32 = 100_000;657}658659match_types! {660	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {661		MultiLocation { parents: 1, interior: Here } |662		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }663	};664}665666pub type Barrier = (667	TakeWeightCredit,668	AllowTopLevelPaidExecutionFrom<Everything>,669	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,670	// ^^^ Parent & its unit plurality gets free execution671);672673pub struct UsingOnlySelfCurrencyComponents<674	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,675	AssetId: Get<MultiLocation>,676	AccountId,677	Currency: CurrencyT<AccountId>,678	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,679>(680	Weight,681	Currency::Balance,682	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,683);684impl<685		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,686		AssetId: Get<MultiLocation>,687		AccountId,688		Currency: CurrencyT<AccountId>,689		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,690	> WeightTrader691	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>692{693	fn new() -> Self {694		Self(0, Zero::zero(), PhantomData)695	}696697	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {698		let amount = WeightToFee::calc(&weight);699		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;700701		// location to this parachain through relay chain702		let option1: xcm::v1::AssetId = Concrete(MultiLocation {703			parents: 1,704			interior: X1(Parachain(ParachainInfo::parachain_id().into())),705		});706		// direct location707		let option2: xcm::v1::AssetId = Concrete(MultiLocation {708			parents: 0,709			interior: Here,710		});711712		let required = if payment.fungible.contains_key(&option1) {713			(option1, u128_amount).into()714		} else if payment.fungible.contains_key(&option2) {715			(option2, u128_amount).into()716		} else {717			(Concrete(MultiLocation::default()), u128_amount).into()718		};719720		let unused = payment721			.checked_sub(required)722			.map_err(|_| XcmError::TooExpensive)?;723		self.0 = self.0.saturating_add(weight);724		self.1 = self.1.saturating_add(amount);725		Ok(unused)726	}727728	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {729		let weight = weight.min(self.0);730		let amount = WeightToFee::calc(&weight);731		self.0 -= weight;732		self.1 = self.1.saturating_sub(amount);733		let amount: u128 = amount.saturated_into();734		if amount > 0 {735			Some((AssetId::get(), amount).into())736		} else {737			None738		}739	}740}741impl<742		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,743		AssetId: Get<MultiLocation>,744		AccountId,745		Currency: CurrencyT<AccountId>,746		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,747	> Drop748	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>749{750	fn drop(&mut self) {751		OnUnbalanced::on_unbalanced(Currency::issue(self.1));752	}753}754755pub struct XcmConfig;756impl Config for XcmConfig {757	type Call = Call;758	type XcmSender = XcmRouter;759	// How to withdraw and deposit an asset.760	type AssetTransactor = LocalAssetTransactor;761	type OriginConverter = XcmOriginToTransactDispatchOrigin;762	type IsReserve = NativeAsset;763	type IsTeleporter = (); // Teleportation is disabled764	type LocationInverter = LocationInverter<Ancestry>;765	type Barrier = Barrier;766	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;767	type Trader = UsingOnlySelfCurrencyComponents<768		IdentityFee<Balance>,769		RelayLocation,770		AccountId,771		Balances,772		(),773	>;774	type ResponseHandler = (); // Don't handle responses for now.775	type SubscriptionService = PolkadotXcm;776777	type AssetTrap = PolkadotXcm;778	type AssetClaims = PolkadotXcm;779}780781// parameter_types! {782// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;783// }784785/// No local origins on this chain are allowed to dispatch XCM sends/executions.786pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);787788/// The means for routing XCM messages which are not for local execution into the right message789/// queues.790pub type XcmRouter = (791	// Two routers - use UMP to communicate with the relay chain:792	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,793	// ..and XCMP to communicate with the sibling chains.794	XcmpQueue,795);796797impl pallet_evm_coder_substrate::Config for Runtime {798	type GasWeightMapping = FixedGasWeightMapping;799}800801impl pallet_xcm::Config for Runtime {802	type Event = Event;803	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;804	type XcmRouter = XcmRouter;805	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;806	type XcmExecuteFilter = Everything;807	type XcmExecutor = XcmExecutor<XcmConfig>;808	type XcmTeleportFilter = Everything;809	type XcmReserveTransferFilter = Everything;810	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;811	type LocationInverter = LocationInverter<Ancestry>;812	type Origin = Origin;813	type Call = Call;814	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;815	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;816}817818impl cumulus_pallet_xcm::Config for Runtime {819	type Event = Event;820	type XcmExecutor = XcmExecutor<XcmConfig>;821}822823impl cumulus_pallet_xcmp_queue::Config for Runtime {824	type WeightInfo = ();825	type Event = Event;826	type XcmExecutor = XcmExecutor<XcmConfig>;827	type ChannelInfo = ParachainSystem;828	type VersionWrapper = ();829	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;830	type ControllerOrigin = EnsureRoot<AccountId>;831	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;832}833834impl cumulus_pallet_dmp_queue::Config for Runtime {835	type Event = Event;836	type XcmExecutor = XcmExecutor<XcmConfig>;837	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;838}839840impl pallet_aura::Config for Runtime {841	type AuthorityId = AuraId;842	type DisabledValidators = ();843	type MaxAuthorities = MaxAuthorities;844}845846parameter_types! {847	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();848	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;849}850851impl pallet_common::Config for Runtime {852	type Event = Event;853854	type Currency = Balances;855	type CollectionCreationPrice = CollectionCreationPrice;856	type TreasuryAccountId = TreasuryAccountId;857	type CollectionDispatch = CollectionDispatchT<Self>;858859	type EvmTokenAddressMapping = EvmTokenAddressMapping;860	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;861}862863impl pallet_structure::Config for Runtime {864	type Event = Event;865	type Call = Call;866	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;867}868869impl pallet_evm::account::Config for Runtime {870	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;871	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;872	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;873}874875impl pallet_fungible::Config for Runtime {876	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;877}878impl pallet_refungible::Config for Runtime {879	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;880}881impl pallet_nonfungible::Config for Runtime {882	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;883}884885impl pallet_proxy_rmrk_core::Config for Runtime {886	type Event = Event;887}888889impl pallet_proxy_rmrk_equip::Config for Runtime {890	type Event = Event;891}892893impl pallet_unique::Config for Runtime {894	type Event = Event;895	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;896}897898parameter_types! {899	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied900}901902/// Used for the pallet inflation903impl pallet_inflation::Config for Runtime {904	type Currency = Balances;905	type TreasuryAccountId = TreasuryAccountId;906	type InflationBlockInterval = InflationBlockInterval;907	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;908}909910// parameter_types! {911// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *912// 		RuntimeBlockWeights::get().max_block;913// 	pub const MaxScheduledPerBlock: u32 = 50;914// }915916type EvmSponsorshipHandler = (917	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,918	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,919);920type SponsorshipHandler = (921	pallet_unique::UniqueSponsorshipHandler<Runtime>,922	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,923	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,924);925926// impl pallet_unq_scheduler::Config for Runtime {927// 	type Event = Event;928// 	type Origin = Origin;929// 	type PalletsOrigin = OriginCaller;930// 	type Call = Call;931// 	type MaximumWeight = MaximumSchedulerWeight;932// 	type ScheduleOrigin = EnsureSigned<AccountId>;933// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;934// 	type SponsorshipHandler = SponsorshipHandler;935// 	type WeightInfo = ();936// }937938impl pallet_evm_transaction_payment::Config for Runtime {939	type EvmSponsorshipHandler = EvmSponsorshipHandler;940	type Currency = Balances;941}942943impl pallet_charge_transaction::Config for Runtime {944	type SponsorshipHandler = SponsorshipHandler;945}946947// impl pallet_contract_helpers::Config for Runtime {948//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;949// }950951parameter_types! {952	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049953	pub const HelpersContractAddress: H160 = H160([954		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,955	]);956		957	// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f958	pub const EvmCollectionAddress: H160 = H160([959		0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,960	]);961}962963impl pallet_evm_contract_helpers::Config for Runtime {964	type ContractAddress = HelpersContractAddress;965	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;966}967968impl evm_collection::Config for Runtime {969	type ContractAddress = EvmCollectionAddress;970}971972construct_runtime!(973	pub enum Runtime where974		Block = Block,975		NodeBlock = opaque::Block,976		UncheckedExtrinsic = UncheckedExtrinsic977	{978		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,979		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,980981		Aura: pallet_aura::{Pallet, Config<T>} = 22,982		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,983984		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,985		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,986		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,987		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,988		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,989		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,990		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,991		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,992		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,993		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,994995		// XCM helpers.996		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,997		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,998		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,999		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10001001		// Unique Pallets1002		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1003		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1004		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1005		// free = 631006		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1007		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1008		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1009		Fungible: pallet_fungible::{Pallet, Storage} = 67,1010		Refungible: pallet_refungible::{Pallet, Storage} = 68,1011		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1012		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1013		RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1014		RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10151016		// Frontier1017		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1018		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10191020		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1021		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1022		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1023		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1024	}1025);10261027pub struct TransactionConverter;10281029impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1030	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1031		UncheckedExtrinsic::new_unsigned(1032			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1033		)1034	}1035}10361037impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1038	fn convert_transaction(1039		&self,1040		transaction: pallet_ethereum::Transaction,1041	) -> opaque::UncheckedExtrinsic {1042		let extrinsic = UncheckedExtrinsic::new_unsigned(1043			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1044		);1045		let encoded = extrinsic.encode();1046		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1047			.expect("Encoded extrinsic is always valid")1048	}1049}10501051/// The address format for describing accounts.1052pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1053/// Block header type as expected by this runtime.1054pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1055/// Block type as expected by this runtime.1056pub type Block = generic::Block<Header, UncheckedExtrinsic>;1057/// A Block signed with a Justification1058pub type SignedBlock = generic::SignedBlock<Block>;1059/// BlockId type as expected by this runtime.1060pub type BlockId = generic::BlockId<Block>;1061/// The SignedExtension to the basic transaction logic.1062pub type SignedExtra = (1063	frame_system::CheckSpecVersion<Runtime>,1064	// system::CheckTxVersion<Runtime>,1065	frame_system::CheckGenesis<Runtime>,1066	frame_system::CheckEra<Runtime>,1067	frame_system::CheckNonce<Runtime>,1068	frame_system::CheckWeight<Runtime>,1069	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1070	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1071	pallet_ethereum::FakeTransactionFinalizer<Runtime>,1072);1073/// Unchecked extrinsic type as expected by this runtime.1074pub type UncheckedExtrinsic =1075	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1076/// Extrinsic type that has already been checked.1077pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1078/// Executive: handles dispatch to the various modules.1079pub type Executive = frame_executive::Executive<1080	Runtime,1081	Block,1082	frame_system::ChainContext<Runtime>,1083	Runtime,1084	AllPalletsReversedWithSystemFirst,1085>;10861087impl_opaque_keys! {1088	pub struct SessionKeys {1089		pub aura: Aura,1090	}1091}10921093impl fp_self_contained::SelfContainedCall for Call {1094	type SignedInfo = H160;10951096	fn is_self_contained(&self) -> bool {1097		match self {1098			Call::Ethereum(call) => call.is_self_contained(),1099			_ => false,1100		}1101	}11021103	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1104		match self {1105			Call::Ethereum(call) => call.check_self_contained(),1106			_ => None,1107		}1108	}11091110	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1111		match self {1112			Call::Ethereum(call) => call.validate_self_contained(info),1113			_ => None,1114		}1115	}11161117	fn pre_dispatch_self_contained(1118		&self,1119		info: &Self::SignedInfo,1120	) -> Option<Result<(), TransactionValidityError>> {1121		match self {1122			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1123			_ => None,1124		}1125	}11261127	fn apply_self_contained(1128		self,1129		info: Self::SignedInfo,1130	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1131		match self {1132			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1133				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1134			)),1135			_ => None,1136		}1137	}1138}11391140macro_rules! dispatch_unique_runtime {1141	($collection:ident.$method:ident($($name:ident),*)) => {{1142		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1143		let dispatch = collection.as_dyn();11441145		Ok::<_, DispatchError>(dispatch.$method($($name),*))1146	}};1147}11481149impl_common_runtime_apis!();11501151struct CheckInherents;11521153impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1154	fn check_inherents(1155		block: &Block,1156		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1157	) -> sp_inherents::CheckInherentsResult {1158		let relay_chain_slot = relay_state_proof1159			.read_slot()1160			.expect("Could not read the relay chain slot from the proof");11611162		let inherent_data =1163			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1164				relay_chain_slot,1165				sp_std::time::Duration::from_secs(6),1166			)1167			.create_inherent_data()1168			.expect("Could not create the timestamp inherent data");11691170		inherent_data.check_extrinsics(block)1171	}1172}11731174cumulus_pallet_parachain_system::register_validate_block!(1175	Runtime = Runtime,1176	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1177	CheckInherents = CheckInherents,1178);
after · runtime/quartz/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, OnMethodCall};83use pallet_unique::evm_collection;84use fp_rpc::TransactionStatus;85use sp_runtime::{86	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},87	transaction_validity::TransactionValidityError,88	SaturatedConversion,89};9091// pub use pallet_timestamp::Call as TimestampCall;92pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9394// Polkadot imports95use pallet_xcm::XcmPassthrough;96use polkadot_parachain::primitives::Sibling;97use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};98use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};99use xcm_builder::{100	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,101	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,102	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,103	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,104	ParentIsPreset,105};106use xcm_executor::{Config, XcmExecutor, Assets};107use sp_std::{marker::PhantomData};108109use xcm::latest::{110	//	Xcm,111	AssetId::{Concrete},112	Fungibility::Fungible as XcmFungible,113	MultiAsset,114	Error as XcmError,115};116use xcm_executor::traits::{MatchesFungible, WeightTrader};117//use xcm_executor::traits::MatchesFungible;118use sp_runtime::traits::CheckedConversion;119120use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};121122pub const RUNTIME_NAME: &str = "quartz";123pub const TOKEN_SYMBOL: &str = "QTZ";124125type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;126127impl RuntimeInstance for Runtime {128	type CrossAccountId = self::CrossAccountId;129130	type TransactionConverter = self::TransactionConverter;131132	fn get_transaction_converter() -> TransactionConverter {133		TransactionConverter134	}135}136137/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know138/// the specifics of the runtime. They can then be made to be agnostic over specific formats139/// of data like extrinsics, allowing for them to continue syncing the network through upgrades140/// to even the core data structures.141pub mod opaque {142	use sp_std::prelude::*;143	use sp_runtime::impl_opaque_keys;144	use super::Aura;145146	pub use unique_runtime_common::types::*;147148	impl_opaque_keys! {149		pub struct SessionKeys {150			pub aura: Aura,151		}152	}153}154155/// This runtime version.156pub const VERSION: RuntimeVersion = RuntimeVersion {157	spec_name: create_runtime_str!(RUNTIME_NAME),158	impl_name: create_runtime_str!(RUNTIME_NAME),159	authoring_version: 1,160	spec_version: 920000,161	impl_version: 0,162	apis: RUNTIME_API_VERSIONS,163	transaction_version: 1,164	state_version: 0,165};166167#[derive(codec::Encode, codec::Decode)]168pub enum XCMPMessage<XAccountId, XBalance> {169	/// Transfer tokens to the given account from the Parachain account.170	TransferToken(XAccountId, XBalance),171}172173/// The version information used to identify this runtime when compiled natively.174#[cfg(feature = "std")]175pub fn native_version() -> NativeVersion {176	NativeVersion {177		runtime_version: VERSION,178		can_author_with: Default::default(),179	}180}181182type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;183184pub struct DealWithFees;185impl OnUnbalanced<NegativeImbalance> for DealWithFees {186	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {187		if let Some(fees) = fees_then_tips.next() {188			// for fees, 100% to treasury189			let mut split = fees.ration(100, 0);190			if let Some(tips) = fees_then_tips.next() {191				// for tips, if any, 100% to treasury192				tips.ration_merge_into(100, 0, &mut split);193			}194			Treasury::on_unbalanced(split.0);195			// Author::on_unbalanced(split.1);196		}197	}198}199200parameter_types! {201	pub const BlockHashCount: BlockNumber = 2400;202	pub RuntimeBlockLength: BlockLength =203		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);204	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);205	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;206	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()207		.base_block(BlockExecutionWeight::get())208		.for_class(DispatchClass::all(), |weights| {209			weights.base_extrinsic = ExtrinsicBaseWeight::get();210		})211		.for_class(DispatchClass::Normal, |weights| {212			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);213		})214		.for_class(DispatchClass::Operational, |weights| {215			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);216			// Operational transactions have some extra reserved space, so that they217			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.218			weights.reserved = Some(219				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT220			);221		})222		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)223		.build_or_panic();224	pub const Version: RuntimeVersion = VERSION;225	pub const SS58Prefix: u8 = 255;226}227228parameter_types! {229	pub const ChainId: u64 = 8881;230}231232pub struct FixedFee;233impl FeeCalculator for FixedFee {234	fn min_gas_price() -> U256 {235		MIN_GAS_PRICE.into()236	}237}238239// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case240// (contract, which only writes a lot of data),241// approximating on top of our real store write weight242parameter_types! {243	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;244	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;245	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();246}247248/// Limiting EVM execution to 50% of block for substrate users and management tasks249/// EVM transaction consumes more weight than substrate's, so we can't rely on them being250/// scheduled fairly251const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);252parameter_types! {253	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());254}255256pub enum FixedGasWeightMapping {}257impl GasWeightMapping for FixedGasWeightMapping {258	fn gas_to_weight(gas: u64) -> Weight {259		gas.saturating_mul(WeightPerGas::get())260	}261	fn weight_to_gas(weight: Weight) -> u64 {262		weight / WeightPerGas::get()263	}264}265266impl pallet_evm::Config for Runtime {267	type BlockGasLimit = BlockGasLimit;268	type FeeCalculator = FixedFee;269	type GasWeightMapping = FixedGasWeightMapping;270	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;271	type CallOrigin = EnsureAddressTruncated<Self>;272	type WithdrawOrigin = EnsureAddressTruncated<Self>;273	type AddressMapping = HashedAddressMapping<Self::Hashing>;274	type PrecompilesType = ();275	type PrecompilesValue = ();276	type Currency = Balances;277	type Event = Event;278	type OnMethodCall = (279		pallet_evm_migration::OnMethodCall<Self>,280		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,281		CollectionDispatchT<Self>,282		evm_collection::CollectionOnMethodCall<Self>,283		evm_collection::CollectionHelperOnMethodCall<Self>,284	);285	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;286	type ChainId = ChainId;287	type Runner = pallet_evm::runner::stack::Runner<Self>;288	type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;289	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;290	type FindAuthor = EthereumFindAuthor<Aura>;291}292293impl pallet_evm_migration::Config for Runtime {294	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;295}296297pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);298impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {299	fn find_author<'a, I>(digests: I) -> Option<H160>300	where301		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,302	{303		if let Some(author_index) = F::find_author(digests) {304			let authority_id = Aura::authorities()[author_index as usize].clone();305			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));306		}307		None308	}309}310311impl pallet_ethereum::Config for Runtime {312	type Event = Event;313	type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;314}315316impl pallet_randomness_collective_flip::Config for Runtime {}317318impl frame_system::Config for Runtime {319	/// The data to be stored in an account.320	type AccountData = pallet_balances::AccountData<Balance>;321	/// The identifier used to distinguish between accounts.322	type AccountId = AccountId;323	/// The basic call filter to use in dispatchable.324	type BaseCallFilter = Everything;325	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).326	type BlockHashCount = BlockHashCount;327	/// The maximum length of a block (in bytes).328	type BlockLength = RuntimeBlockLength;329	/// The index type for blocks.330	type BlockNumber = BlockNumber;331	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.332	type BlockWeights = RuntimeBlockWeights;333	/// The aggregated dispatch type that is available for extrinsics.334	type Call = Call;335	/// The weight of database operations that the runtime can invoke.336	type DbWeight = RocksDbWeight;337	/// The ubiquitous event type.338	type Event = Event;339	/// The type for hashing blocks and tries.340	type Hash = Hash;341	/// The hashing algorithm used.342	type Hashing = BlakeTwo256;343	/// The header type.344	type Header = generic::Header<BlockNumber, BlakeTwo256>;345	/// The index type for storing how many extrinsics an account has signed.346	type Index = Index;347	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.348	type Lookup = AccountIdLookup<AccountId, ()>;349	/// What to do if an account is fully reaped from the system.350	type OnKilledAccount = ();351	/// What to do if a new account is created.352	type OnNewAccount = ();353	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;354	/// The ubiquitous origin type.355	type Origin = Origin;356	/// This type is being generated by `construct_runtime!`.357	type PalletInfo = PalletInfo;358	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.359	type SS58Prefix = SS58Prefix;360	/// Weight information for the extrinsics of this pallet.361	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;362	/// Version of the runtime.363	type Version = Version;364	type MaxConsumers = ConstU32<16>;365}366367parameter_types! {368	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;369}370371impl pallet_timestamp::Config for Runtime {372	/// A timestamp: milliseconds since the unix epoch.373	type Moment = u64;374	type OnTimestampSet = ();375	type MinimumPeriod = MinimumPeriod;376	type WeightInfo = ();377}378379parameter_types! {380	// pub const ExistentialDeposit: u128 = 500;381	pub const ExistentialDeposit: u128 = 0;382	pub const MaxLocks: u32 = 50;383}384385impl pallet_balances::Config for Runtime {386	type MaxLocks = MaxLocks;387	type MaxReserves = ();388	type ReserveIdentifier = [u8; 8];389	/// The type for recording an account's balance.390	type Balance = Balance;391	/// The ubiquitous event type.392	type Event = Event;393	type DustRemoval = Treasury;394	type ExistentialDeposit = ExistentialDeposit;395	type AccountStore = System;396	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;397}398399pub const fn deposit(items: u32, bytes: u32) -> Balance {400	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE401}402403/*404parameter_types! {405	pub TombstoneDeposit: Balance = deposit(406		1,407		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,408	);409	pub DepositPerContract: Balance = TombstoneDeposit::get();410	pub const DepositPerStorageByte: Balance = deposit(0, 1);411	pub const DepositPerStorageItem: Balance = deposit(1, 0);412	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);413	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;414	pub const SignedClaimHandicap: u32 = 2;415	pub const MaxDepth: u32 = 32;416	pub const MaxValueSize: u32 = 16 * 1024;417	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb418	// The lazy deletion runs inside on_initialize.419	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *420		RuntimeBlockWeights::get().max_block;421	// The weight needed for decoding the queue should be less or equal than a fifth422	// of the overall weight dedicated to the lazy deletion.423	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (424			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -425			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)426		)) / 5) as u32;427	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();428}429430impl pallet_contracts::Config for Runtime {431	type Time = Timestamp;432	type Randomness = RandomnessCollectiveFlip;433	type Currency = Balances;434	type Event = Event;435	type RentPayment = ();436	type SignedClaimHandicap = SignedClaimHandicap;437	type TombstoneDeposit = TombstoneDeposit;438	type DepositPerContract = DepositPerContract;439	type DepositPerStorageByte = DepositPerStorageByte;440	type DepositPerStorageItem = DepositPerStorageItem;441	type RentFraction = RentFraction;442	type SurchargeReward = SurchargeReward;443	type WeightPrice = pallet_transaction_payment::Pallet<Self>;444	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;445	type ChainExtension = NFTExtension;446	type DeletionQueueDepth = DeletionQueueDepth;447	type DeletionWeightLimit = DeletionWeightLimit;448	type Schedule = Schedule;449	type CallStack = [pallet_contracts::Frame<Self>; 31];450}451*/452453parameter_types! {454	/// This value increases the priority of `Operational` transactions by adding455	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.456	pub const OperationalFeeMultiplier: u8 = 5;457}458459/// Linear implementor of `WeightToFeePolynomial`460pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);461462impl<T> WeightToFeePolynomial for LinearFee<T>463where464	T: BaseArithmetic + From<u32> + Copy + Unsigned,465{466	type Balance = T;467468	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {469		smallvec!(WeightToFeeCoefficient {470			// Targeting 0.1 Unique per NFT transfer471			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),472			coeff_frac: Perbill::zero(),473			negative: false,474			degree: 1,475		})476	}477}478479impl pallet_transaction_payment::Config for Runtime {480	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;481	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;482	type OperationalFeeMultiplier = OperationalFeeMultiplier;483	type WeightToFee = LinearFee<Balance>;484	type FeeMultiplierUpdate = ();485}486487parameter_types! {488	pub const ProposalBond: Permill = Permill::from_percent(5);489	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;490	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;491	pub const SpendPeriod: BlockNumber = 5 * MINUTES;492	pub const Burn: Permill = Permill::from_percent(0);493	pub const TipCountdown: BlockNumber = 1 * DAYS;494	pub const TipFindersFee: Percent = Percent::from_percent(20);495	pub const TipReportDepositBase: Balance = 1 * UNIQUE;496	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;497	pub const BountyDepositBase: Balance = 1 * UNIQUE;498	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;499	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");500	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;501	pub const MaximumReasonLength: u32 = 16384;502	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);503	pub const BountyValueMinimum: Balance = 5 * UNIQUE;504	pub const MaxApprovals: u32 = 100;505}506507impl pallet_treasury::Config for Runtime {508	type PalletId = TreasuryModuleId;509	type Currency = Balances;510	type ApproveOrigin = EnsureRoot<AccountId>;511	type RejectOrigin = EnsureRoot<AccountId>;512	type Event = Event;513	type OnSlash = ();514	type ProposalBond = ProposalBond;515	type ProposalBondMinimum = ProposalBondMinimum;516	type ProposalBondMaximum = ProposalBondMaximum;517	type SpendPeriod = SpendPeriod;518	type Burn = Burn;519	type BurnDestination = ();520	type SpendFunds = ();521	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;522	type MaxApprovals = MaxApprovals;523}524525impl pallet_sudo::Config for Runtime {526	type Event = Event;527	type Call = Call;528}529530pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);531532impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider533	for RelayChainBlockNumberProvider<T>534{535	type BlockNumber = BlockNumber;536537	fn current_block_number() -> Self::BlockNumber {538		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()539			.map(|d| d.relay_parent_number)540			.unwrap_or_default()541	}542}543544parameter_types! {545	pub const MinVestedTransfer: Balance = 10 * UNIQUE;546	pub const MaxVestingSchedules: u32 = 28;547}548549impl orml_vesting::Config for Runtime {550	type Event = Event;551	type Currency = pallet_balances::Pallet<Runtime>;552	type MinVestedTransfer = MinVestedTransfer;553	type VestedTransferOrigin = EnsureSigned<AccountId>;554	type WeightInfo = ();555	type MaxVestingSchedules = MaxVestingSchedules;556	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;557}558559parameter_types! {560	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;561	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562}563564impl cumulus_pallet_parachain_system::Config for Runtime {565	type Event = Event;566	type SelfParaId = parachain_info::Pallet<Self>;567	type OnSystemEvent = ();568	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<569	// 	MaxDownwardMessageWeight,570	// 	XcmExecutor<XcmConfig>,571	// 	Call,572	// >;573	type OutboundXcmpMessageSource = XcmpQueue;574	type DmpMessageHandler = DmpQueue;575	type ReservedDmpWeight = ReservedDmpWeight;576	type ReservedXcmpWeight = ReservedXcmpWeight;577	type XcmpMessageHandler = XcmpQueue;578}579580impl parachain_info::Config for Runtime {}581582impl cumulus_pallet_aura_ext::Config for Runtime {}583584parameter_types! {585	pub const RelayLocation: MultiLocation = MultiLocation::parent();586	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;587	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();588	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();589}590591/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used592/// when determining ownership of accounts for asset transacting and when attempting to use XCM593/// `Transact` in order to determine the dispatch Origin.594pub type LocationToAccountId = (595	// The parent (Relay-chain) origin converts to the default `AccountId`.596	ParentIsPreset<AccountId>,597	// Sibling parachain origins convert to AccountId via the `ParaId::into`.598	SiblingParachainConvertsVia<Sibling, AccountId>,599	// Straight up local `AccountId32` origins just alias directly to `AccountId`.600	AccountId32Aliases<RelayNetwork, AccountId>,601);602603pub struct OnlySelfCurrency;604impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {605	fn matches_fungible(a: &MultiAsset) -> Option<B> {606		match (&a.id, &a.fun) {607			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),608			_ => None,609		}610	}611}612613/// Means for transacting assets on this chain.614pub type LocalAssetTransactor = CurrencyAdapter<615	// Use this currency:616	Balances,617	// Use this currency when it is a fungible asset matching the given location or name:618	OnlySelfCurrency,619	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:620	LocationToAccountId,621	// Our chain's account ID type (we can't get away without mentioning it explicitly):622	AccountId,623	// We don't track any teleports.624	(),625>;626627/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,628/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can629/// biases the kind of local `Origin` it will become.630pub type XcmOriginToTransactDispatchOrigin = (631	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location632	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for633	// foreign chains who want to have a local sovereign account on this chain which they control.634	SovereignSignedViaLocation<LocationToAccountId, Origin>,635	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when636	// recognised.637	RelayChainAsNative<RelayOrigin, Origin>,638	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when639	// recognised.640	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,641	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a642	// transaction from the Root origin.643	ParentAsSuperuser<Origin>,644	// Native signed account converter; this just converts an `AccountId32` origin into a normal645	// `Origin::Signed` origin of the same 32-byte value.646	SignedAccountId32AsNative<RelayNetwork, Origin>,647	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.648	XcmPassthrough<Origin>,649);650651parameter_types! {652	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.653	pub UnitWeightCost: Weight = 1_000_000;654	// 1200 UNIQUEs buy 1 second of weight.655	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);656	pub const MaxInstructions: u32 = 100;657	pub const MaxAuthorities: u32 = 100_000;658}659660match_types! {661	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {662		MultiLocation { parents: 1, interior: Here } |663		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }664	};665}666667pub type Barrier = (668	TakeWeightCredit,669	AllowTopLevelPaidExecutionFrom<Everything>,670	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,671	// ^^^ Parent & its unit plurality gets free execution672);673674pub struct UsingOnlySelfCurrencyComponents<675	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,676	AssetId: Get<MultiLocation>,677	AccountId,678	Currency: CurrencyT<AccountId>,679	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,680>(681	Weight,682	Currency::Balance,683	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,684);685impl<686		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,687		AssetId: Get<MultiLocation>,688		AccountId,689		Currency: CurrencyT<AccountId>,690		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,691	> WeightTrader692	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>693{694	fn new() -> Self {695		Self(0, Zero::zero(), PhantomData)696	}697698	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {699		let amount = WeightToFee::calc(&weight);700		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;701702		// location to this parachain through relay chain703		let option1: xcm::v1::AssetId = Concrete(MultiLocation {704			parents: 1,705			interior: X1(Parachain(ParachainInfo::parachain_id().into())),706		});707		// direct location708		let option2: xcm::v1::AssetId = Concrete(MultiLocation {709			parents: 0,710			interior: Here,711		});712713		let required = if payment.fungible.contains_key(&option1) {714			(option1, u128_amount).into()715		} else if payment.fungible.contains_key(&option2) {716			(option2, u128_amount).into()717		} else {718			(Concrete(MultiLocation::default()), u128_amount).into()719		};720721		let unused = payment722			.checked_sub(required)723			.map_err(|_| XcmError::TooExpensive)?;724		self.0 = self.0.saturating_add(weight);725		self.1 = self.1.saturating_add(amount);726		Ok(unused)727	}728729	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {730		let weight = weight.min(self.0);731		let amount = WeightToFee::calc(&weight);732		self.0 -= weight;733		self.1 = self.1.saturating_sub(amount);734		let amount: u128 = amount.saturated_into();735		if amount > 0 {736			Some((AssetId::get(), amount).into())737		} else {738			None739		}740	}741}742impl<743		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,744		AssetId: Get<MultiLocation>,745		AccountId,746		Currency: CurrencyT<AccountId>,747		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,748	> Drop749	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>750{751	fn drop(&mut self) {752		OnUnbalanced::on_unbalanced(Currency::issue(self.1));753	}754}755756pub struct XcmConfig;757impl Config for XcmConfig {758	type Call = Call;759	type XcmSender = XcmRouter;760	// How to withdraw and deposit an asset.761	type AssetTransactor = LocalAssetTransactor;762	type OriginConverter = XcmOriginToTransactDispatchOrigin;763	type IsReserve = NativeAsset;764	type IsTeleporter = (); // Teleportation is disabled765	type LocationInverter = LocationInverter<Ancestry>;766	type Barrier = Barrier;767	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;768	type Trader = UsingOnlySelfCurrencyComponents<769		IdentityFee<Balance>,770		RelayLocation,771		AccountId,772		Balances,773		(),774	>;775	type ResponseHandler = (); // Don't handle responses for now.776	type SubscriptionService = PolkadotXcm;777778	type AssetTrap = PolkadotXcm;779	type AssetClaims = PolkadotXcm;780}781782// parameter_types! {783// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;784// }785786/// No local origins on this chain are allowed to dispatch XCM sends/executions.787pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);788789/// The means for routing XCM messages which are not for local execution into the right message790/// queues.791pub type XcmRouter = (792	// Two routers - use UMP to communicate with the relay chain:793	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,794	// ..and XCMP to communicate with the sibling chains.795	XcmpQueue,796);797798impl pallet_evm_coder_substrate::Config for Runtime {799	type GasWeightMapping = FixedGasWeightMapping;800}801802impl pallet_xcm::Config for Runtime {803	type Event = Event;804	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;805	type XcmRouter = XcmRouter;806	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;807	type XcmExecuteFilter = Everything;808	type XcmExecutor = XcmExecutor<XcmConfig>;809	type XcmTeleportFilter = Everything;810	type XcmReserveTransferFilter = Everything;811	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;812	type LocationInverter = LocationInverter<Ancestry>;813	type Origin = Origin;814	type Call = Call;815	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;816	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;817}818819impl cumulus_pallet_xcm::Config for Runtime {820	type Event = Event;821	type XcmExecutor = XcmExecutor<XcmConfig>;822}823824impl cumulus_pallet_xcmp_queue::Config for Runtime {825	type WeightInfo = ();826	type Event = Event;827	type XcmExecutor = XcmExecutor<XcmConfig>;828	type ChannelInfo = ParachainSystem;829	type VersionWrapper = ();830	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;831	type ControllerOrigin = EnsureRoot<AccountId>;832	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;833}834835impl cumulus_pallet_dmp_queue::Config for Runtime {836	type Event = Event;837	type XcmExecutor = XcmExecutor<XcmConfig>;838	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;839}840841impl pallet_aura::Config for Runtime {842	type AuthorityId = AuraId;843	type DisabledValidators = ();844	type MaxAuthorities = MaxAuthorities;845}846847parameter_types! {848	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();849	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;850}851852impl pallet_common::Config for Runtime {853	type Event = Event;854855	type Currency = Balances;856	type CollectionCreationPrice = CollectionCreationPrice;857	type TreasuryAccountId = TreasuryAccountId;858	type CollectionDispatch = CollectionDispatchT<Self>;859860	type EvmTokenAddressMapping = EvmTokenAddressMapping;861	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;862}863864impl pallet_structure::Config for Runtime {865	type Event = Event;866	type Call = Call;867	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;868}869870impl pallet_evm::account::Config for Runtime {871	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;872	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;873	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;874}875876impl pallet_fungible::Config for Runtime {877	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;878}879impl pallet_refungible::Config for Runtime {880	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;881}882impl pallet_nonfungible::Config for Runtime {883	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;884}885886impl pallet_proxy_rmrk_core::Config for Runtime {887	type Event = Event;888}889890impl pallet_proxy_rmrk_equip::Config for Runtime {891	type Event = Event;892}893894impl pallet_unique::Config for Runtime {895	type Event = Event;896	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;897}898899parameter_types! {900	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied901}902903/// Used for the pallet inflation904impl pallet_inflation::Config for Runtime {905	type Currency = Balances;906	type TreasuryAccountId = TreasuryAccountId;907	type InflationBlockInterval = InflationBlockInterval;908	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;909}910911// parameter_types! {912// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *913// 		RuntimeBlockWeights::get().max_block;914// 	pub const MaxScheduledPerBlock: u32 = 50;915// }916917type EvmSponsorshipHandler = (918	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,919	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,920);921type SponsorshipHandler = (922	pallet_unique::UniqueSponsorshipHandler<Runtime>,923	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,924	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,925);926927// impl pallet_unq_scheduler::Config for Runtime {928// 	type Event = Event;929// 	type Origin = Origin;930// 	type PalletsOrigin = OriginCaller;931// 	type Call = Call;932// 	type MaximumWeight = MaximumSchedulerWeight;933// 	type ScheduleOrigin = EnsureSigned<AccountId>;934// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;935// 	type SponsorshipHandler = SponsorshipHandler;936// 	type WeightInfo = ();937// }938939impl pallet_evm_transaction_payment::Config for Runtime {940	type EvmSponsorshipHandler = EvmSponsorshipHandler;941	type Currency = Balances;942}943944impl pallet_charge_transaction::Config for Runtime {945	type SponsorshipHandler = SponsorshipHandler;946}947948// impl pallet_contract_helpers::Config for Runtime {949//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;950// }951952parameter_types! {953	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049954	pub const HelpersContractAddress: H160 = H160([955		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,956	]);957		958	// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f959	pub const EvmCollectionHelperAddress: H160 = H160([960		0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,961	]);962}963964impl pallet_evm_contract_helpers::Config for Runtime {965	type ContractAddress = HelpersContractAddress;966	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;967}968969impl evm_collection::Config for Runtime {970	type ContractAddress = EvmCollectionHelperAddress;971}972973construct_runtime!(974	pub enum Runtime where975		Block = Block,976		NodeBlock = opaque::Block,977		UncheckedExtrinsic = UncheckedExtrinsic978	{979		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,980		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,981982		Aura: pallet_aura::{Pallet, Config<T>} = 22,983		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,984985		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,986		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,987		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,988		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,989		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,990		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,991		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,992		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,993		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,994		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,995996		// XCM helpers.997		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,998		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,999		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1000		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10011002		// Unique Pallets1003		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1004		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1005		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1006		// free = 631007		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1008		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1009		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1010		Fungible: pallet_fungible::{Pallet, Storage} = 67,1011		Refungible: pallet_refungible::{Pallet, Storage} = 68,1012		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1013		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1014		RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1015		RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10161017		// Frontier1018		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1019		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10201021		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1022		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1023		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1024		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1025	}1026);10271028pub struct TransactionConverter;10291030impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1031	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1032		UncheckedExtrinsic::new_unsigned(1033			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1034		)1035	}1036}10371038impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1039	fn convert_transaction(1040		&self,1041		transaction: pallet_ethereum::Transaction,1042	) -> opaque::UncheckedExtrinsic {1043		let extrinsic = UncheckedExtrinsic::new_unsigned(1044			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1045		);1046		let encoded = extrinsic.encode();1047		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1048			.expect("Encoded extrinsic is always valid")1049	}1050}10511052/// The address format for describing accounts.1053pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1054/// Block header type as expected by this runtime.1055pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1056/// Block type as expected by this runtime.1057pub type Block = generic::Block<Header, UncheckedExtrinsic>;1058/// A Block signed with a Justification1059pub type SignedBlock = generic::SignedBlock<Block>;1060/// BlockId type as expected by this runtime.1061pub type BlockId = generic::BlockId<Block>;1062/// The SignedExtension to the basic transaction logic.1063pub type SignedExtra = (1064	frame_system::CheckSpecVersion<Runtime>,1065	// system::CheckTxVersion<Runtime>,1066	frame_system::CheckGenesis<Runtime>,1067	frame_system::CheckEra<Runtime>,1068	frame_system::CheckNonce<Runtime>,1069	frame_system::CheckWeight<Runtime>,1070	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1071	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1072	pallet_ethereum::FakeTransactionFinalizer<Runtime>,1073);1074/// Unchecked extrinsic type as expected by this runtime.1075pub type UncheckedExtrinsic =1076	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1077/// Extrinsic type that has already been checked.1078pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1079/// Executive: handles dispatch to the various modules.1080pub type Executive = frame_executive::Executive<1081	Runtime,1082	Block,1083	frame_system::ChainContext<Runtime>,1084	Runtime,1085	AllPalletsReversedWithSystemFirst,1086>;10871088impl_opaque_keys! {1089	pub struct SessionKeys {1090		pub aura: Aura,1091	}1092}10931094impl fp_self_contained::SelfContainedCall for Call {1095	type SignedInfo = H160;10961097	fn is_self_contained(&self) -> bool {1098		match self {1099			Call::Ethereum(call) => call.is_self_contained(),1100			_ => false,1101		}1102	}11031104	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1105		match self {1106			Call::Ethereum(call) => call.check_self_contained(),1107			_ => None,1108		}1109	}11101111	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1112		match self {1113			Call::Ethereum(call) => call.validate_self_contained(info),1114			_ => None,1115		}1116	}11171118	fn pre_dispatch_self_contained(1119		&self,1120		info: &Self::SignedInfo,1121	) -> Option<Result<(), TransactionValidityError>> {1122		match self {1123			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1124			_ => None,1125		}1126	}11271128	fn apply_self_contained(1129		self,1130		info: Self::SignedInfo,1131	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1132		match self {1133			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1134				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1135			)),1136			_ => None,1137		}1138	}1139}11401141macro_rules! dispatch_unique_runtime {1142	($collection:ident.$method:ident($($name:ident),*)) => {{1143		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1144		let dispatch = collection.as_dyn();11451146		Ok::<_, DispatchError>(dispatch.$method($($name),*))1147	}};1148}11491150impl_common_runtime_apis!();11511152struct CheckInherents;11531154impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1155	fn check_inherents(1156		block: &Block,1157		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1158	) -> sp_inherents::CheckInherentsResult {1159		let relay_chain_slot = relay_state_proof1160			.read_slot()1161			.expect("Could not read the relay chain slot from the proof");11621163		let inherent_data =1164			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1165				relay_chain_slot,1166				sp_std::time::Duration::from_secs(6),1167			)1168			.create_inherent_data()1169			.expect("Could not create the timestamp inherent data");11701171		inherent_data.check_extrinsics(block)1172	}1173}11741175cumulus_pallet_parachain_system::register_validate_block!(1176	Runtime = Runtime,1177	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1178	CheckInherents = CheckInherents,1179);
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -284,6 +284,7 @@
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
 		CollectionDispatchT<Self>,
 		evm_collection::CollectionOnMethodCall<Self>,
+		evm_collection::CollectionHelperOnMethodCall<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -960,7 +961,7 @@
 	]);
 		
 	// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
-	pub const EvmCollectionAddress: H160 = H160([
+	pub const EvmCollectionHelperAddress: H160 = H160([
 		0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
 	]);
 }
@@ -971,7 +972,7 @@
 }
 
 impl evm_collection::Config for Runtime {
-	type ContractAddress = EvmCollectionAddress;
+	type ContractAddress = EvmCollectionHelperAddress;
 }
 
 construct_runtime!(
modifiedtests/src/eth/api/Collection.soldiffbeforeafterboth
--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,25 +12,17 @@
 	function supportsInterface(bytes4 interfaceID) external view returns (bool);
 }
 
-// Selector: 1e95830f
+// Selector: 15cc740e
 interface Collection is Dummy, ERC165 {
-	// Selector: create721Collection(string,string,string) 951c0151
-	function create721Collection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix
-	) external view returns (address);
+	// Selector: setSponsor(address) 59753fb1
+	function setSponsor(address sponsor) external view;
 
-	// Selector: setSponsor(address,address) f01fba93
-	function setSponsor(address collectionAddress, address sponsor)
-		external
-		view;
+	// Selector: confirmSponsorship() c8c6a056
+	function confirmSponsorship() external view;
 
-	// Selector: confirmSponsorship(address) abc00001
-	function confirmSponsorship(address collectionAddress) external view;
+	// Selector: setLimits(string) 72cb345d
+	function setLimits(string memory limitsJson) external view;
 
-	// Selector: setLimits(address,string) d05638cc
-	function setLimits(address collectionAddress, string memory limitsJson)
-		external
-		view;
+	// Selector: contractAddress() f6b4dfb4
+	function contractAddress() external view returns (address);
 }
addedtests/src/eth/api/CollectionHelper.soldiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/api/CollectionHelper.sol
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+	function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+// Selector: 951c0151
+interface CollectionHelper is Dummy, ERC165 {
+	// Selector: create721Collection(string,string,string) 951c0151
+	function create721Collection(
+		string memory name,
+		string memory description,
+		string memory tokenPrefix
+	) external view returns (address);
+}
modifiedtests/src/eth/collectionAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,35 +1,20 @@
 [
   {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "collectionAddress",
-        "type": "address"
-      }
-    ],
+    "inputs": [],
     "name": "confirmSponsorship",
     "outputs": [],
     "stateMutability": "view",
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "string", "name": "name", "type": "string" },
-      { "internalType": "string", "name": "description", "type": "string" },
-      { "internalType": "string", "name": "tokenPrefix", "type": "string" }
-    ],
-    "name": "create721Collection",
+    "inputs": [],
+    "name": "contractAddress",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
     "stateMutability": "view",
     "type": "function"
   },
   {
     "inputs": [
-      {
-        "internalType": "address",
-        "name": "collectionAddress",
-        "type": "address"
-      },
       { "internalType": "string", "name": "limitsJson", "type": "string" }
     ],
     "name": "setLimits",
@@ -39,11 +24,6 @@
   },
   {
     "inputs": [
-      {
-        "internalType": "address",
-        "name": "collectionAddress",
-        "type": "address"
-      },
       { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
     "name": "setSponsor",
addedtests/src/eth/collectionHelperAbi.jsondiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/collectionHelperAbi.json
@@ -0,0 +1,22 @@
+[
+  {
+    "inputs": [
+      { "internalType": "string", "name": "name", "type": "string" },
+      { "internalType": "string", "name": "description", "type": "string" },
+      { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+    ],
+    "name": "create721Collection",
+    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+    ],
+    "name": "supportsInterface",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
+  }
+]
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -20,11 +20,12 @@
 import {expect} from 'chai';
 import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
 import {
-  collectionHelper,
+  evmCollectionHelper,
   collectionIdFromAddress,
   collectionIdToAddress,
   createEthAccount,
   createEthAccountWithBalance,
+  evmCollection,
   GAS_ARGS,
   itWeb3,
   normalizeAddress,
@@ -41,7 +42,7 @@
 describe('Create collection from EVM', () => {
   itWeb3('Create collection', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
+    const helper = evmCollectionHelper(web3, owner);
     const collectionName = 'CollectionEVM';
     const description = 'Some description';
     const tokenPrefix = 'token prefix';
@@ -63,26 +64,27 @@
   
   itWeb3('Set sponsorship', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
-    let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();
+    const collectionHelper = evmCollectionHelper(web3, owner);
+    let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const sponsor = await createEthAccountWithBalance(api, web3);
-    result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();
-    let collection = (await getDetailedCollectionInfo(api, collectionId))!;
-    expect(collection.sponsorship.isUnconfirmed).to.be.true;
-    expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
-    await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');
-    const sponsorHelper = collectionHelper(web3, sponsor);
-    await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();
-    collection = (await getDetailedCollectionInfo(api, collectionId))!;
-    expect(collection.sponsorship.isConfirmed).to.be.true;
-    expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+    result = await collectionEvm.methods.setSponsor(sponsor).send();
+    let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+    expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
+    expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+    await expect(collectionEvm.methods.confirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
+    const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+    await sponsorCollection.methods.confirmSponsorship().send();
+    collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+    expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+    expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
   });
 
   itWeb3('Set limits', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
-    const result = await helper.methods.create721Collection('Const collection', '5', '5').send();
+    const collectionHelper = evmCollectionHelper(web3, owner);
+    const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const limits = {
       accountTokenOwnershipLimit: 1000,
@@ -97,23 +99,24 @@
     };
 
     const limitsJson = JSON.stringify(limits, null, 1);
-    await helper.methods.setLimits(collectionIdAddress, limitsJson).send();
+    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+    await collectionEvm.methods.setLimits(limitsJson).send();
     
-    const collection = (await getDetailedCollectionInfo(api, collectionId))!;
-    expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
-    expect(collection.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
-    expect(collection.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
-    expect(collection.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
-    expect(collection.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
-    expect(collection.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
-    expect(collection.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
-    expect(collection.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
-    expect(collection.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
+    const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+    expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
+    expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
+    expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
+    expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
+    expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
+    expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
+    expect(collectionSub.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
+    expect(collectionSub.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
+    expect(collectionSub.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
   });
 
   itWeb3('Check tokenURI', async ({web3, api}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
+    const helper = evmCollectionHelper(web3, owner);
     let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const receiver = createEthAccount(web3);
@@ -154,7 +157,7 @@
 describe('(!negative tests!) Create collection from EVM', () => {
   itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
+    const helper = evmCollectionHelper(web3, owner);
     {
       const MAX_NAME_LENGHT = 64;
       const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);
@@ -188,7 +191,7 @@
   
   itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
     const owner = await createEthAccount(web3);
-    const helper = collectionHelper(web3, owner);
+    const helper = evmCollectionHelper(web3, owner);
     const collectionName = 'A';
     const description = 'A';
     const tokenPrefix = 'A';
@@ -200,24 +203,24 @@
 
   itWeb3('(!negative test!) Collection address (Contract is not an unique collection)', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
     const collectionAddressWithBadPrefix = '0x00112233445566778899AABBCCDDEEFF00112233';
+    const collectionEvm = evmCollection(web3, owner, collectionAddressWithBadPrefix);
     const EXPECTED_ERROR = 'Contract is not an unique collection';
     {
       const sponsor = await createEthAccountWithBalance(api, web3);
-      await expect(helper.methods
-        .setSponsor(collectionAddressWithBadPrefix, sponsor)
+      await expect(collectionEvm.methods
+        .setSponsor(sponsor)
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
       
-      const sponsorHelper = collectionHelper(web3, sponsor);
-      await expect(sponsorHelper.methods
-        .confirmSponsorship(collectionAddressWithBadPrefix)
+      const sponsorCollection = evmCollection(web3, sponsor, collectionAddressWithBadPrefix);
+      await expect(sponsorCollection.methods
+        .confirmSponsorship()
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
     {
       const limits = '{"account_token_ownership_limit":1000}';
-      await expect(helper.methods
-        .setLimits(collectionAddressWithBadPrefix, limits)
+      await expect(collectionEvm.methods
+        .setLimits(limits)
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
@@ -225,38 +228,39 @@
   itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
     const notOwner = await createEthAccount(web3);
-    const helperFromOwner = collectionHelper(web3, owner);
-    const helperFromNotOwner = collectionHelper(web3, notOwner);
-    const result = await helperFromOwner.methods.create721Collection('A', 'A', 'A').send();
+    const collectionHelper = evmCollectionHelper(web3, owner);
+    const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();
     const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+    const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);
     const EXPECTED_ERROR = 'NoPermission';
     {
       const sponsor = await createEthAccountWithBalance(api, web3);
-      await expect(helperFromNotOwner.methods
-        .setSponsor(collectionIdAddress, sponsor)
+      await expect(contractEvmFromNotOwner.methods
+        .setSponsor(sponsor)
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
       
-      const sponsorHelper = collectionHelper(web3, sponsor);
-      await expect(sponsorHelper.methods
-        .confirmSponsorship(collectionIdAddress)
+      const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+      await expect(sponsorCollection.methods
+        .confirmSponsorship()
         .call()).to.be.rejectedWith('Caller is not set as sponsor');
     }
     {
       const limits = '{"account_token_ownership_limit":1000}';
-      await expect(helperFromNotOwner.methods
-        .setLimits(collectionIdAddress, limits)
+      await expect(contractEvmFromNotOwner.methods
+        .setLimits(limits)
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
 
   itWeb3('(!negative test!) Set limits', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helper = collectionHelper(web3, owner);
-    const result = await helper.methods.create721Collection('Schema collection', 'A', 'A').send();
+    const collectionHelper = evmCollectionHelper(web3, owner);
+    const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
     const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
     const badJson = '{accountTokenOwnershipLimit: 1000}';
-    await expect(helper.methods
-      .setLimits(collectionIdAddress, badJson)
+    await expect(collectionEvm.methods
+      .setLimits(badJson)
       .call()).to.be.rejectedWith('Parse JSON error:');
   });
 });
\ No newline at end of file
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -29,6 +29,7 @@
 import privateKey from '../../substrate/privateKey';
 import contractHelpersAbi from './contractHelpersAbi.json';
 import collectionAbi from '../collectionAbi.json';
+import collectionHelperAbi from '../collectionHelperAbi.json';
 import getBalance from '../../substrate/get-balance';
 import waitNewBlocks from '../../substrate/wait-new-blocks';
 
@@ -283,13 +284,23 @@
 }
 
 /** 
- * pallet evm_collection
+ * evm collection helper
  * @param web3 
  * @param caller - eth address
  * @returns 
  */
-export function collectionHelper(web3: Web3, caller: string) {
-  return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+export function evmCollectionHelper(web3: Web3, caller: string) {
+  return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/** 
+ * evm collection
+ * @param web3 
+ * @param caller - eth address
+ * @returns 
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string) {
+  return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});
 }
 
 /**
modifiedtests/src/interfaces/unique/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -6,9 +6,6 @@
 import type { AccountId32, Call, H160, H256, MultiAddress, Perbill, Permill } from '@polkadot/types/interfaces/runtime';
 import type { Event } from '@polkadot/types/interfaces/system';
 
-/** @name BTreeSet */
-export interface BTreeSet extends BTreeSet<Bytes> {}
-
 /** @name CumulusPalletDmpQueueCall */
 export interface CumulusPalletDmpQueueCall extends Enum {
   readonly isServiceOverweight: boolean;