git.delta.rocks / unique-network / refs/commits / 890b4afabe76

difftreelog

Merge branch 'develop' into feature/CORE-324

Yaroslav Bolyukin2022-04-01parents: #4b84a72 #a961c1a.patch.diff
in: master

17 files changed

modified.envdiffbeforeafterboth
--- a/.env
+++ b/.env
@@ -1,6 +1,6 @@
 RUST_TOOLCHAIN=nightly-2021-11-11
 RUST_C=1.58.0-nightly
-POLKA_VERSION=release-v0.9.17
+POLKA_VERSION=release-v0.9.18
 UNIQUE_BRANCH=develop
 USER=***
 PASS=***
modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5575,7 +5575,7 @@
 
 [[package]]
 name = "opal-runtime"
-version = "0.1.0"
+version = "0.9.18"
 dependencies = [
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
@@ -8709,7 +8709,7 @@
 
 [[package]]
 name = "quartz-runtime"
-version = "0.1.0"
+version = "0.9.18"
 dependencies = [
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
@@ -8723,13 +8723,10 @@
  "fp-evm-mapping",
  "fp-rpc",
  "fp-self-contained",
- "frame-benchmarking",
  "frame-executive",
  "frame-support",
  "frame-system",
- "frame-system-benchmarking",
  "frame-system-rpc-runtime-api",
- "hex-literal",
  "orml-vesting",
  "pallet-aura",
  "pallet-balances",
@@ -12551,7 +12548,7 @@
 
 [[package]]
 name = "unique-runtime"
-version = "0.9.17"
+version = "0.9.18"
 dependencies = [
  "cumulus-pallet-aura-ext",
  "cumulus-pallet-dmp-queue",
@@ -12627,7 +12624,7 @@
 
 [[package]]
 name = "unique-runtime-common"
-version = "0.1.0"
+version = "0.9.18"
 dependencies = [
  "fp-rpc",
  "frame-support",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,8 +5,11 @@
     'pallets/*',
     'client/*',
     'primitives/*',
-    'runtime/*',
     'crates/*',
 ]
+exclude = [
+    "runtime/unique",
+    "runtime/quartz"
+]
 [profile.release]
 panic = 'unwind'
modifiedDockerfile-parachaindiffbeforeafterboth
--- a/Dockerfile-parachain
+++ b/Dockerfile-parachain
@@ -1,5 +1,5 @@
 # ===== Rust builder =====
-FROM phusion/baseimage:focal-1.0.0 as rust-builder
+FROM phusion/baseimage:focal-1.1.0 as rust-builder
 LABEL maintainer="Unique.Network"
 
 ARG RUST_TOOLCHAIN=nightly-2021-11-11
@@ -77,7 +77,7 @@
 
 # ===== RUN ======
 
-FROM phusion/baseimage:focal-1.0.0
+FROM phusion/baseimage:focal-1.1.0
 
 ARG PROFILE=release
 
modifiedREADME.mddiffbeforeafterboth
--- a/README.md
+++ b/README.md
@@ -63,12 +63,7 @@
 
 5. Build:
 ```bash
-cargo build
-```
-
-optionally, build in release:
-```bash
-cargo build --release
+cargo build --features=unique-runtime,quartz-runtime --release
 ```
 
 ## Building as Parachain locally
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -312,7 +312,7 @@
 unique-rpc = { default-features = false, path = "../rpc" }
 
 [features]
-default = ["unique-runtime", "quartz-runtime"]
+default = []
 runtime-benchmarks = [
     'unique-runtime/runtime-benchmarks',
     'polkadot-service/runtime-benchmarks',
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -14,7 +14,6 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-use cumulus_primitives_core::ParaId;
 use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
 use sc_service::ChainType;
 use sp_core::{sr25519, Pair, Public};
@@ -26,6 +25,15 @@
 
 use unique_runtime_common::types::*;
 
+#[cfg(feature = "unique-runtime")]
+use unique_runtime as default_runtime;
+
+#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]
+use quartz_runtime as default_runtime;
+
+#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
+use opal_runtime as default_runtime;
+
 /// The `ChainSpec` parameterized for the unique runtime.
 #[cfg(feature = "unique-runtime")]
 pub type UniqueChainSpec = sc_service::GenericChainSpec<unique_runtime::GenesisConfig, Extensions>;
@@ -37,9 +45,22 @@
 /// The `ChainSpec` parameterized for the opal runtime.
 pub type OpalChainSpec = sc_service::GenericChainSpec<opal_runtime::GenesisConfig, Extensions>;
 
+#[cfg(feature = "unique-runtime")]
+pub type DefaultChainSpec = UniqueChainSpec;
+
+#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]
+pub type DefaultChainSpec = QuartzChainSpec;
+
+#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
+pub type DefaultChainSpec = OpalChainSpec;
+
 pub enum RuntimeId {
+	#[cfg(feature = "unique-runtime")]
 	Unique,
+
+	#[cfg(feature = "quartz-runtime")]
 	Quartz,
+
 	Opal,
 	Unknown(String),
 }
@@ -51,12 +72,12 @@
 impl RuntimeIdentification for Box<dyn sc_service::ChainSpec> {
 	fn runtime_id(&self) -> RuntimeId {
 		#[cfg(feature = "unique-runtime")]
-		if self.id().starts_with("unique") {
+		if self.id().starts_with("unique") || self.id().starts_with("unq") {
 			return RuntimeId::Unique;
 		}
 
 		#[cfg(feature = "quartz-runtime")]
-		if self.id().starts_with("quartz") {
+		if self.id().starts_with("quartz") || self.id().starts_with("qtz") {
 			return RuntimeId::Quartz;
 		}
 
@@ -121,20 +142,66 @@
 	AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
 }
 
+macro_rules! testnet_genesis {
+	(
+		$runtime:path,
+		$root_key:expr,
+		$initial_authorities:expr,
+		$endowed_accounts:expr,
+		$id:expr
+	) => {{
+		use $runtime::*;
+
+		GenesisConfig {
+			system: SystemConfig {
+				code: WASM_BINARY
+					.expect("WASM binary was not build, please build it!")
+					.to_vec(),
+			},
+			balances: BalancesConfig {
+				balances: $endowed_accounts
+					.iter()
+					.cloned()
+					// 1e13 UNQ
+					.map(|k| (k, 1 << 100))
+					.collect(),
+			},
+			treasury: Default::default(),
+			sudo: SudoConfig {
+				key: Some($root_key),
+			},
+			vesting: VestingConfig { vesting: vec![] },
+			parachain_info: ParachainInfoConfig {
+				parachain_id: $id.into(),
+			},
+			parachain_system: Default::default(),
+			aura: AuraConfig {
+				authorities: $initial_authorities,
+			},
+			aura_ext: Default::default(),
+			evm: EVMConfig {
+				accounts: BTreeMap::new(),
+			},
+			ethereum: EthereumConfig {},
+		}
+	}};
+}
+
 pub fn development_config() -> OpalChainSpec {
 	let mut properties = Map::new();
-	properties.insert("tokenSymbol".into(), "OPL".into());
-	properties.insert("tokenDecimals".into(), 15.into());
-	properties.insert("ss58Format".into(), 42.into());
+	properties.insert("tokenSymbol".into(), opal_runtime::TOKEN_SYMBOL.into());
+	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("ss58Format".into(), opal_runtime::SS58Prefix::get().into());
 
 	OpalChainSpec::from_genesis(
 		// Name
-		"Development",
+		"OPAL by UNIQUE",
 		// ID
-		"dev",
+		"opal_dev",
 		ChainType::Local,
 		move || {
-			testnet_genesis(
+			testnet_genesis!(
+				opal_runtime,
 				// Sudo account
 				get_account_id_from_seed::<sr25519::Public>("Alice"),
 				vec![
@@ -146,7 +213,7 @@
 					get_account_id_from_seed::<sr25519::Public>("Alice"),
 					get_account_id_from_seed::<sr25519::Public>("Bob"),
 				],
-				1000.into(),
+				1000
 			)
 		},
 		// Bootnodes
@@ -166,15 +233,33 @@
 	)
 }
 
-pub fn local_testnet_rococo_config() -> OpalChainSpec {
-	OpalChainSpec::from_genesis(
+pub fn local_testnet_rococo_config() -> DefaultChainSpec {
+	let mut properties = Map::new();
+	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
+	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert(
+		"ss58Format".into(),
+		default_runtime::SS58Prefix::get().into(),
+	);
+
+	DefaultChainSpec::from_genesis(
 		// Name
-		"Local Testnet",
+		format!(
+			"{}{}",
+			default_runtime::RUNTIME_NAME.to_uppercase(),
+			if cfg!(feature = "unique-runtime") {
+				""
+			} else {
+				" by UNIQUE"
+			}
+		)
+		.as_str(),
 		// ID
-		"local_testnet",
+		format!("{}_local", default_runtime::RUNTIME_NAME).as_str(),
 		ChainType::Local,
 		move || {
-			testnet_genesis(
+			testnet_genesis!(
+				default_runtime,
 				// Sudo account
 				get_account_id_from_seed::<sr25519::Public>("Alice"),
 				vec![
@@ -196,7 +281,7 @@
 					get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
 					get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
 				],
-				1000.into(),
+				1000
 			)
 		},
 		// Bootnodes
@@ -207,51 +292,11 @@
 		None,
 		None,
 		// Properties
-		None,
+		Some(properties),
 		// Extensions
 		Extensions {
 			relay_chain: "rococo-local".into(),
 			para_id: 1000,
 		},
 	)
-}
-
-fn testnet_genesis(
-	root_key: AccountId,
-	initial_authorities: Vec<AuraId>,
-	endowed_accounts: Vec<AccountId>,
-	id: ParaId,
-) -> opal_runtime::GenesisConfig {
-	use opal_runtime::*;
-
-	GenesisConfig {
-		system: SystemConfig {
-			code: WASM_BINARY
-				.expect("WASM binary was not build, please build it!")
-				.to_vec(),
-		},
-		balances: BalancesConfig {
-			balances: endowed_accounts
-				.iter()
-				.cloned()
-				// 1e13 UNQ
-				.map(|k| (k, 1 << 100))
-				.collect(),
-		},
-		treasury: Default::default(),
-		sudo: SudoConfig {
-			key: Some(root_key),
-		},
-		vesting: VestingConfig { vesting: vec![] },
-		parachain_info: ParachainInfoConfig { parachain_id: id },
-		parachain_system: Default::default(),
-		aura: AuraConfig {
-			authorities: initial_authorities,
-		},
-		aura_ext: Default::default(),
-		evm: EVMConfig {
-			accounts: BTreeMap::new(),
-		},
-		ethereum: EthereumConfig {},
-	}
 }
modifiednode/cli/src/service.rsdiffbeforeafterboth
--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -61,9 +61,16 @@
 
 use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};
 
-/// Native executor instance.
+/// Unique native executor instance.
+#[cfg(feature = "unique-runtime")]
 pub struct UniqueRuntimeExecutor;
+
+#[cfg(feature = "quartz-runtime")]
+/// Quartz native executor instance.
+
 pub struct QuartzRuntimeExecutor;
+
+/// Opal native executor instance.
 pub struct OpalRuntimeExecutor;
 
 #[cfg(feature = "unique-runtime")]
modifiedpallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/sponsoring.rs
+++ b/pallets/unique/src/eth/sponsoring.rs
@@ -24,12 +24,13 @@
 use up_sponsorship::SponsorshipHandler;
 use core::marker::PhantomData;
 use core::convert::TryInto;
-use up_data_structs::TokenId;
 use pallet_evm::account::CrossAccountId;
 
-use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
+use pallet_nonfungible::erc::{
+	UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
+};
 use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
-use up_data_structs::{CreateItemData, CreateNftData};
+use up_data_structs::{TokenId, CreateItemData, CreateNftData};
 
 pub struct UniqueEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
 impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>
@@ -50,6 +51,18 @@
 						let token_id: TokenId = token_id.try_into().ok()?;
 						withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
 					}
+					UniqueNFTCall::ERC721Mintable(
+						ERC721MintableCall::Mint { token_id, .. }
+						| ERC721MintableCall::MintWithTokenUri { token_id, .. },
+					) => {
+						let _token_id: TokenId = token_id.try_into().ok()?;
+						withdraw_create_item::<T>(
+							&collection,
+							&who,
+							&CreateItemData::NFT(CreateNftData::default()),
+						)
+						.map(|()| sponsor)
+					}
 					UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
 						let token_id: TokenId = token_id.try_into().ok()?;
 						let from = T::CrossAccountId::from_eth(from);
@@ -60,18 +73,6 @@
 						withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
 							.map(|()| sponsor)
 					}
-					UniqueNFTCall::ERC721Mintable(call) => match call {
-						pallet_nonfungible::erc::ERC721MintableCall::Mint { .. }
-						| pallet_nonfungible::erc::ERC721MintableCall::MintWithTokenUri {
-							..
-						} => withdraw_create_item(
-							&collection,
-							who.as_sub(),
-							&CreateItemData::NFT(CreateNftData::default()),
-						)
-						.map(|()| sponsor),
-						_ => None,
-					},
 					_ => None,
 				}
 			}
modifiedpallets/unique/src/sponsorship.rsdiffbeforeafterboth
--- a/pallets/unique/src/sponsorship.rs
+++ b/pallets/unique/src/sponsorship.rs
@@ -103,7 +103,7 @@
 
 pub fn withdraw_create_item<T: Config>(
 	collection: &CollectionHandle<T>,
-	who: &T::AccountId,
+	who: &T::CrossAccountId,
 	_properties: &CreateItemData,
 ) -> Option<()> {
 	if _properties.data_size() as u32 > collection.limits.sponsored_data_size() {
@@ -120,14 +120,14 @@
 			CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
 		});
 
-	if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, &who)) {
+	if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, who.as_sub())) {
 		let timeout = last_tx_block + limit.into();
 		if block_number < timeout {
 			return None;
 		}
 	}
 
-	CreateItemBasket::<T>::insert((collection.id, who.clone()), block_number);
+	CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);
 
 	Some(())
 }
@@ -246,7 +246,12 @@
 				..
 			} => {
 				let (sponsor, collection) = load(*collection_id)?;
-				withdraw_create_item::<T>(&collection, who, data).map(|()| sponsor)
+				withdraw_create_item::<T>(
+					&collection,
+					&T::CrossAccountId::from_sub(who.clone()),
+					data,
+				)
+				.map(|()| sponsor)
 			}
 			Call::transfer {
 				collection_id,
modifiedruntime/common/Cargo.tomldiffbeforeafterboth
--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -6,7 +6,7 @@
 license = 'All Rights Reserved'
 name = 'unique-runtime-common'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.0'
+version = '0.9.18'
 
 [features]
 default = ['std']
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -10,7 +10,7 @@
 license = 'GPLv3'
 name = 'opal-runtime'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.0'
+version = '0.9.18'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -116,7 +116,8 @@
 
 use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
 
-pub const RUNTIME_NAME: &str = "Opal";
+pub const RUNTIME_NAME: &str = "opal";
+pub const TOKEN_SYMBOL: &str = "OPL";
 
 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;
 
@@ -168,7 +169,7 @@
 	spec_name: create_runtime_str!(RUNTIME_NAME),
 	impl_name: create_runtime_str!(RUNTIME_NAME),
 	authoring_version: 1,
-	spec_version: 917004,
+	spec_version: 918001,
 	impl_version: 0,
 	apis: RUNTIME_API_VERSIONS,
 	transaction_version: 1,
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -10,7 +10,7 @@
 license = 'GPLv3'
 name = 'quartz-runtime'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.0'
+version = '0.9.18'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -116,7 +116,8 @@
 
 use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
 
-pub const RUNTIME_NAME: &str = "Quartz";
+pub const RUNTIME_NAME: &str = "quartz";
+pub const TOKEN_SYMBOL: &str = "QTZ";
 
 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;
 
@@ -153,7 +154,7 @@
 	spec_name: create_runtime_str!(RUNTIME_NAME),
 	impl_name: create_runtime_str!(RUNTIME_NAME),
 	authoring_version: 1,
-	spec_version: 917004,
+	spec_version: 918001,
 	impl_version: 0,
 	apis: RUNTIME_API_VERSIONS,
 	transaction_version: 1,
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -10,7 +10,7 @@
 license = 'GPLv3'
 name = 'unique-runtime'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.9.17'
+version = '0.9.18'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
before · runtime/unique/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37	transaction_validity::{TransactionSource, TransactionValidity},38	ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52	EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55	construct_runtime, match_type,56	dispatch::DispatchResult,57	PalletId, parameter_types, StorageValue, ConsensusEngineId,58	traits::{59		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61		OnUnbalanced, Randomness, FindAuthor,62	},63	weights::{64		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,67	},68};69use up_data_structs::*;70// use pallet_contracts::weights::WeightInfo;71// #[cfg(any(feature = "std", test))]72use frame_system::{73	self as frame_system, EnsureRoot, EnsureSigned,74	limits::{BlockWeights, BlockLength},75};76use sp_arithmetic::{77	traits::{BaseArithmetic, Unsigned},78};79use smallvec::smallvec;80use codec::{Encode, Decode};81use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};82use fp_rpc::TransactionStatus;83use sp_runtime::{84	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85	transaction_validity::TransactionValidityError,86	SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;9091// Polkadot imports92use pallet_xcm::XcmPassthrough;93use polkadot_parachain::primitives::Sibling;94use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};95use xcm_builder::{96	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,97	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,98	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,99	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,100	ParentIsPreset,101};102use xcm_executor::{Config, XcmExecutor, Assets};103use sp_std::{marker::PhantomData};104105use xcm::latest::{106	//	Xcm,107	AssetId::{Concrete},108	Fungibility::Fungible as XcmFungible,109	MultiAsset,110	Error as XcmError,111};112use xcm_executor::traits::{MatchesFungible, WeightTrader};113//use xcm_executor::traits::MatchesFungible;114use sp_runtime::traits::CheckedConversion;115116use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};117118pub const RUNTIME_NAME: &str = "Unique";119120type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;121122impl RuntimeInstance for Runtime {123	type CrossAccountId = self::CrossAccountId;124125	type TransactionConverter = self::TransactionConverter;126127	fn get_transaction_converter() -> TransactionConverter {128		TransactionConverter129	}130}131132/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know133/// the specifics of the runtime. They can then be made to be agnostic over specific formats134/// of data like extrinsics, allowing for them to continue syncing the network through upgrades135/// to even the core data structures.136pub mod opaque {137	use sp_std::prelude::*;138	use sp_runtime::impl_opaque_keys;139	use super::Aura;140141	pub use unique_runtime_common::types::*;142143	impl_opaque_keys! {144		pub struct SessionKeys {145			pub aura: Aura,146		}147	}148}149150/// This runtime version.151pub const VERSION: RuntimeVersion = RuntimeVersion {152	spec_name: create_runtime_str!(RUNTIME_NAME),153	impl_name: create_runtime_str!(RUNTIME_NAME),154	authoring_version: 1,155	spec_version: 917004,156	impl_version: 0,157	apis: RUNTIME_API_VERSIONS,158	transaction_version: 1,159	state_version: 0,160};161162#[derive(codec::Encode, codec::Decode)]163pub enum XCMPMessage<XAccountId, XBalance> {164	/// Transfer tokens to the given account from the Parachain account.165	TransferToken(XAccountId, XBalance),166}167168/// The version information used to identify this runtime when compiled natively.169#[cfg(feature = "std")]170pub fn native_version() -> NativeVersion {171	NativeVersion {172		runtime_version: VERSION,173		can_author_with: Default::default(),174	}175}176177type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;178179pub struct DealWithFees;180impl OnUnbalanced<NegativeImbalance> for DealWithFees {181	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {182		if let Some(fees) = fees_then_tips.next() {183			// for fees, 100% to treasury184			let mut split = fees.ration(100, 0);185			if let Some(tips) = fees_then_tips.next() {186				// for tips, if any, 100% to treasury187				tips.ration_merge_into(100, 0, &mut split);188			}189			Treasury::on_unbalanced(split.0);190			// Author::on_unbalanced(split.1);191		}192	}193}194195parameter_types! {196	pub const BlockHashCount: BlockNumber = 2400;197	pub RuntimeBlockLength: BlockLength =198		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);199	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);200	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;201	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()202		.base_block(BlockExecutionWeight::get())203		.for_class(DispatchClass::all(), |weights| {204			weights.base_extrinsic = ExtrinsicBaseWeight::get();205		})206		.for_class(DispatchClass::Normal, |weights| {207			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);208		})209		.for_class(DispatchClass::Operational, |weights| {210			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);211			// Operational transactions have some extra reserved space, so that they212			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.213			weights.reserved = Some(214				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT215			);216		})217		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)218		.build_or_panic();219	pub const Version: RuntimeVersion = VERSION;220	pub const SS58Prefix: u16 = 7391;221}222223parameter_types! {224	pub const ChainId: u64 = 8880;225}226227pub struct FixedFee;228impl FeeCalculator for FixedFee {229	fn min_gas_price() -> U256 {230		MIN_GAS_PRICE.into()231	}232}233234// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case235// (contract, which only writes a lot of data),236// approximating on top of our real store write weight237parameter_types! {238	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;239	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;240	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();241}242243/// Limiting EVM execution to 50% of block for substrate users and management tasks244/// EVM transaction consumes more weight than substrate's, so we can't rely on them being245/// scheduled fairly246const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);247parameter_types! {248	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());249}250251pub enum FixedGasWeightMapping {}252impl GasWeightMapping for FixedGasWeightMapping {253	fn gas_to_weight(gas: u64) -> Weight {254		gas.saturating_mul(WeightPerGas::get())255	}256	fn weight_to_gas(weight: Weight) -> u64 {257		weight / WeightPerGas::get()258	}259}260261impl pallet_evm::Config for Runtime {262	type BlockGasLimit = BlockGasLimit;263	type FeeCalculator = FixedFee;264	type GasWeightMapping = FixedGasWeightMapping;265	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;266	type CallOrigin = EnsureAddressTruncated;267	type WithdrawOrigin = EnsureAddressTruncated;268	type AddressMapping = HashedAddressMapping<Self::Hashing>;269	type PrecompilesType = ();270	type PrecompilesValue = ();271	type Currency = Balances;272	type Event = Event;273	type OnMethodCall = (274		pallet_evm_migration::OnMethodCall<Self>,275		pallet_unique::UniqueErcSupport<Self>,276		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,277	);278	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;279	type ChainId = ChainId;280	type Runner = pallet_evm::runner::stack::Runner<Self>;281	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;282	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;283	type FindAuthor = EthereumFindAuthor<Aura>;284}285286impl pallet_evm_migration::Config for Runtime {287	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;288}289290pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);291impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {292	fn find_author<'a, I>(digests: I) -> Option<H160>293	where294		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,295	{296		if let Some(author_index) = F::find_author(digests) {297			let authority_id = Aura::authorities()[author_index as usize].clone();298			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));299		}300		None301	}302}303304impl pallet_ethereum::Config for Runtime {305	type Event = Event;306	type StateRoot = pallet_ethereum::IntermediateStateRoot;307}308309impl pallet_randomness_collective_flip::Config for Runtime {}310311impl frame_system::Config for Runtime {312	/// The data to be stored in an account.313	type AccountData = pallet_balances::AccountData<Balance>;314	/// The identifier used to distinguish between accounts.315	type AccountId = AccountId;316	/// The basic call filter to use in dispatchable.317	type BaseCallFilter = Everything;318	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).319	type BlockHashCount = BlockHashCount;320	/// The maximum length of a block (in bytes).321	type BlockLength = RuntimeBlockLength;322	/// The index type for blocks.323	type BlockNumber = BlockNumber;324	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.325	type BlockWeights = RuntimeBlockWeights;326	/// The aggregated dispatch type that is available for extrinsics.327	type Call = Call;328	/// The weight of database operations that the runtime can invoke.329	type DbWeight = RocksDbWeight;330	/// The ubiquitous event type.331	type Event = Event;332	/// The type for hashing blocks and tries.333	type Hash = Hash;334	/// The hashing algorithm used.335	type Hashing = BlakeTwo256;336	/// The header type.337	type Header = generic::Header<BlockNumber, BlakeTwo256>;338	/// The index type for storing how many extrinsics an account has signed.339	type Index = Index;340	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.341	type Lookup = AccountIdLookup<AccountId, ()>;342	/// What to do if an account is fully reaped from the system.343	type OnKilledAccount = ();344	/// What to do if a new account is created.345	type OnNewAccount = ();346	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;347	/// The ubiquitous origin type.348	type Origin = Origin;349	/// This type is being generated by `construct_runtime!`.350	type PalletInfo = PalletInfo;351	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.352	type SS58Prefix = SS58Prefix;353	/// Weight information for the extrinsics of this pallet.354	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;355	/// Version of the runtime.356	type Version = Version;357	type MaxConsumers = ConstU32<16>;358}359360parameter_types! {361	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;362}363364impl pallet_timestamp::Config for Runtime {365	/// A timestamp: milliseconds since the unix epoch.366	type Moment = u64;367	type OnTimestampSet = ();368	type MinimumPeriod = MinimumPeriod;369	type WeightInfo = ();370}371372parameter_types! {373	// pub const ExistentialDeposit: u128 = 500;374	pub const ExistentialDeposit: u128 = 0;375	pub const MaxLocks: u32 = 50;376}377378impl pallet_balances::Config for Runtime {379	type MaxLocks = MaxLocks;380	type MaxReserves = ();381	type ReserveIdentifier = [u8; 8];382	/// The type for recording an account's balance.383	type Balance = Balance;384	/// The ubiquitous event type.385	type Event = Event;386	type DustRemoval = Treasury;387	type ExistentialDeposit = ExistentialDeposit;388	type AccountStore = System;389	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;390}391392pub const fn deposit(items: u32, bytes: u32) -> Balance {393	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE394}395396/*397parameter_types! {398	pub TombstoneDeposit: Balance = deposit(399		1,400		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,401	);402	pub DepositPerContract: Balance = TombstoneDeposit::get();403	pub const DepositPerStorageByte: Balance = deposit(0, 1);404	pub const DepositPerStorageItem: Balance = deposit(1, 0);405	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);406	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;407	pub const SignedClaimHandicap: u32 = 2;408	pub const MaxDepth: u32 = 32;409	pub const MaxValueSize: u32 = 16 * 1024;410	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb411	// The lazy deletion runs inside on_initialize.412	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *413		RuntimeBlockWeights::get().max_block;414	// The weight needed for decoding the queue should be less or equal than a fifth415	// of the overall weight dedicated to the lazy deletion.416	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (417			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -418			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)419		)) / 5) as u32;420	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();421}422423impl pallet_contracts::Config for Runtime {424	type Time = Timestamp;425	type Randomness = RandomnessCollectiveFlip;426	type Currency = Balances;427	type Event = Event;428	type RentPayment = ();429	type SignedClaimHandicap = SignedClaimHandicap;430	type TombstoneDeposit = TombstoneDeposit;431	type DepositPerContract = DepositPerContract;432	type DepositPerStorageByte = DepositPerStorageByte;433	type DepositPerStorageItem = DepositPerStorageItem;434	type RentFraction = RentFraction;435	type SurchargeReward = SurchargeReward;436	type WeightPrice = pallet_transaction_payment::Pallet<Self>;437	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;438	type ChainExtension = NFTExtension;439	type DeletionQueueDepth = DeletionQueueDepth;440	type DeletionWeightLimit = DeletionWeightLimit;441	type Schedule = Schedule;442	type CallStack = [pallet_contracts::Frame<Self>; 31];443}444*/445446parameter_types! {447	/// This value increases the priority of `Operational` transactions by adding448	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.449	pub const OperationalFeeMultiplier: u8 = 5;450}451452/// Linear implementor of `WeightToFeePolynomial`453pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);454455impl<T> WeightToFeePolynomial for LinearFee<T>456where457	T: BaseArithmetic + From<u32> + Copy + Unsigned,458{459	type Balance = T;460461	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {462		smallvec!(WeightToFeeCoefficient {463			// Targeting 0.1 Unique per NFT transfer464			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),465			coeff_frac: Perbill::zero(),466			negative: false,467			degree: 1,468		})469	}470}471472impl pallet_transaction_payment::Config for Runtime {473	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;474	type TransactionByteFee = TransactionByteFee;475	type OperationalFeeMultiplier = OperationalFeeMultiplier;476	type WeightToFee = LinearFee<Balance>;477	type FeeMultiplierUpdate = ();478}479480parameter_types! {481	pub const ProposalBond: Permill = Permill::from_percent(5);482	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;483	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;484	pub const SpendPeriod: BlockNumber = 5 * MINUTES;485	pub const Burn: Permill = Permill::from_percent(0);486	pub const TipCountdown: BlockNumber = 1 * DAYS;487	pub const TipFindersFee: Percent = Percent::from_percent(20);488	pub const TipReportDepositBase: Balance = 1 * UNIQUE;489	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;490	pub const BountyDepositBase: Balance = 1 * UNIQUE;491	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;492	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");493	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;494	pub const MaximumReasonLength: u32 = 16384;495	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);496	pub const BountyValueMinimum: Balance = 5 * UNIQUE;497	pub const MaxApprovals: u32 = 100;498}499500impl pallet_treasury::Config for Runtime {501	type PalletId = TreasuryModuleId;502	type Currency = Balances;503	type ApproveOrigin = EnsureRoot<AccountId>;504	type RejectOrigin = EnsureRoot<AccountId>;505	type Event = Event;506	type OnSlash = ();507	type ProposalBond = ProposalBond;508	type ProposalBondMinimum = ProposalBondMinimum;509	type ProposalBondMaximum = ProposalBondMaximum;510	type SpendPeriod = SpendPeriod;511	type Burn = Burn;512	type BurnDestination = ();513	type SpendFunds = ();514	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;515	type MaxApprovals = MaxApprovals;516}517518impl pallet_sudo::Config for Runtime {519	type Event = Event;520	type Call = Call;521}522523pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);524525impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider526	for RelayChainBlockNumberProvider<T>527{528	type BlockNumber = BlockNumber;529530	fn current_block_number() -> Self::BlockNumber {531		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()532			.map(|d| d.relay_parent_number)533			.unwrap_or_default()534	}535}536537parameter_types! {538	pub const MinVestedTransfer: Balance = 10 * UNIQUE;539	pub const MaxVestingSchedules: u32 = 28;540}541542impl orml_vesting::Config for Runtime {543	type Event = Event;544	type Currency = pallet_balances::Pallet<Runtime>;545	type MinVestedTransfer = MinVestedTransfer;546	type VestedTransferOrigin = EnsureSigned<AccountId>;547	type WeightInfo = ();548	type MaxVestingSchedules = MaxVestingSchedules;549	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;550}551552parameter_types! {553	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;554	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;555}556557impl cumulus_pallet_parachain_system::Config for Runtime {558	type Event = Event;559	type SelfParaId = parachain_info::Pallet<Self>;560	type OnSystemEvent = ();561	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<562	// 	MaxDownwardMessageWeight,563	// 	XcmExecutor<XcmConfig>,564	// 	Call,565	// >;566	type OutboundXcmpMessageSource = XcmpQueue;567	type DmpMessageHandler = DmpQueue;568	type ReservedDmpWeight = ReservedDmpWeight;569	type ReservedXcmpWeight = ReservedXcmpWeight;570	type XcmpMessageHandler = XcmpQueue;571}572573impl parachain_info::Config for Runtime {}574575impl cumulus_pallet_aura_ext::Config for Runtime {}576577parameter_types! {578	pub const RelayLocation: MultiLocation = MultiLocation::parent();579	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;580	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();581	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();582}583584/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used585/// when determining ownership of accounts for asset transacting and when attempting to use XCM586/// `Transact` in order to determine the dispatch Origin.587pub type LocationToAccountId = (588	// The parent (Relay-chain) origin converts to the default `AccountId`.589	ParentIsPreset<AccountId>,590	// Sibling parachain origins convert to AccountId via the `ParaId::into`.591	SiblingParachainConvertsVia<Sibling, AccountId>,592	// Straight up local `AccountId32` origins just alias directly to `AccountId`.593	AccountId32Aliases<RelayNetwork, AccountId>,594);595596pub struct OnlySelfCurrency;597impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {598	fn matches_fungible(a: &MultiAsset) -> Option<B> {599		match (&a.id, &a.fun) {600			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),601			_ => None,602		}603	}604}605606/// Means for transacting assets on this chain.607pub type LocalAssetTransactor = CurrencyAdapter<608	// Use this currency:609	Balances,610	// Use this currency when it is a fungible asset matching the given location or name:611	OnlySelfCurrency,612	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:613	LocationToAccountId,614	// Our chain's account ID type (we can't get away without mentioning it explicitly):615	AccountId,616	// We don't track any teleports.617	(),618>;619620/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,621/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can622/// biases the kind of local `Origin` it will become.623pub type XcmOriginToTransactDispatchOrigin = (624	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location625	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for626	// foreign chains who want to have a local sovereign account on this chain which they control.627	SovereignSignedViaLocation<LocationToAccountId, Origin>,628	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when629	// recognised.630	RelayChainAsNative<RelayOrigin, Origin>,631	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when632	// recognised.633	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,634	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a635	// transaction from the Root origin.636	ParentAsSuperuser<Origin>,637	// Native signed account converter; this just converts an `AccountId32` origin into a normal638	// `Origin::Signed` origin of the same 32-byte value.639	SignedAccountId32AsNative<RelayNetwork, Origin>,640	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.641	XcmPassthrough<Origin>,642);643644parameter_types! {645	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.646	pub UnitWeightCost: Weight = 1_000_000;647	// 1200 UNIQUEs buy 1 second of weight.648	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);649	pub const MaxInstructions: u32 = 100;650	pub const MaxAuthorities: u32 = 100_000;651}652653match_type! {654	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {655		MultiLocation { parents: 1, interior: Here } |656		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }657	};658}659660pub type Barrier = (661	TakeWeightCredit,662	AllowTopLevelPaidExecutionFrom<Everything>,663	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,664	// ^^^ Parent & its unit plurality gets free execution665);666667pub struct UsingOnlySelfCurrencyComponents<668	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,669	AssetId: Get<MultiLocation>,670	AccountId,671	Currency: CurrencyT<AccountId>,672	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,673>(674	Weight,675	Currency::Balance,676	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,677);678impl<679		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,680		AssetId: Get<MultiLocation>,681		AccountId,682		Currency: CurrencyT<AccountId>,683		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,684	> WeightTrader685	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>686{687	fn new() -> Self {688		Self(0, Zero::zero(), PhantomData)689	}690691	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {692		let amount = WeightToFee::calc(&weight);693		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;694695		// location to this parachain through relay chain696		let option1: xcm::v1::AssetId = Concrete(MultiLocation {697			parents: 1,698			interior: X1(Parachain(ParachainInfo::parachain_id().into())),699		});700		// direct location701		let option2: xcm::v1::AssetId = Concrete(MultiLocation {702			parents: 0,703			interior: Here,704		});705706		let required = if payment.fungible.contains_key(&option1) {707			(option1, u128_amount).into()708		} else if payment.fungible.contains_key(&option2) {709			(option2, u128_amount).into()710		} else {711			(Concrete(MultiLocation::default()), u128_amount).into()712		};713714		let unused = payment715			.checked_sub(required)716			.map_err(|_| XcmError::TooExpensive)?;717		self.0 = self.0.saturating_add(weight);718		self.1 = self.1.saturating_add(amount);719		Ok(unused)720	}721722	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {723		let weight = weight.min(self.0);724		let amount = WeightToFee::calc(&weight);725		self.0 -= weight;726		self.1 = self.1.saturating_sub(amount);727		let amount: u128 = amount.saturated_into();728		if amount > 0 {729			Some((AssetId::get(), amount).into())730		} else {731			None732		}733	}734}735impl<736		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,737		AssetId: Get<MultiLocation>,738		AccountId,739		Currency: CurrencyT<AccountId>,740		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,741	> Drop742	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>743{744	fn drop(&mut self) {745		OnUnbalanced::on_unbalanced(Currency::issue(self.1));746	}747}748749pub struct XcmConfig;750impl Config for XcmConfig {751	type Call = Call;752	type XcmSender = XcmRouter;753	// How to withdraw and deposit an asset.754	type AssetTransactor = LocalAssetTransactor;755	type OriginConverter = XcmOriginToTransactDispatchOrigin;756	type IsReserve = NativeAsset;757	type IsTeleporter = (); // Teleportation is disabled758	type LocationInverter = LocationInverter<Ancestry>;759	type Barrier = Barrier;760	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;761	type Trader = UsingOnlySelfCurrencyComponents<762		IdentityFee<Balance>,763		RelayLocation,764		AccountId,765		Balances,766		(),767	>;768	type ResponseHandler = (); // Don't handle responses for now.769	type SubscriptionService = PolkadotXcm;770771	type AssetTrap = PolkadotXcm;772	type AssetClaims = PolkadotXcm;773}774775// parameter_types! {776// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;777// }778779/// No local origins on this chain are allowed to dispatch XCM sends/executions.780pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);781782/// The means for routing XCM messages which are not for local execution into the right message783/// queues.784pub type XcmRouter = (785	// Two routers - use UMP to communicate with the relay chain:786	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,787	// ..and XCMP to communicate with the sibling chains.788	XcmpQueue,789);790791impl pallet_evm_coder_substrate::Config for Runtime {792	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;793	type GasWeightMapping = FixedGasWeightMapping;794}795796impl pallet_xcm::Config for Runtime {797	type Event = Event;798	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;799	type XcmRouter = XcmRouter;800	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;801	type XcmExecuteFilter = Everything;802	type XcmExecutor = XcmExecutor<XcmConfig>;803	type XcmTeleportFilter = Everything;804	type XcmReserveTransferFilter = Everything;805	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;806	type LocationInverter = LocationInverter<Ancestry>;807	type Origin = Origin;808	type Call = Call;809	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;810	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;811}812813impl cumulus_pallet_xcm::Config for Runtime {814	type Event = Event;815	type XcmExecutor = XcmExecutor<XcmConfig>;816}817818impl cumulus_pallet_xcmp_queue::Config for Runtime {819	type WeightInfo = ();820	type Event = Event;821	type XcmExecutor = XcmExecutor<XcmConfig>;822	type ChannelInfo = ParachainSystem;823	type VersionWrapper = ();824	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;825	type ControllerOrigin = EnsureRoot<AccountId>;826	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;827}828829impl cumulus_pallet_dmp_queue::Config for Runtime {830	type Event = Event;831	type XcmExecutor = XcmExecutor<XcmConfig>;832	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;833}834835impl pallet_aura::Config for Runtime {836	type AuthorityId = AuraId;837	type DisabledValidators = ();838	type MaxAuthorities = MaxAuthorities;839}840841parameter_types! {842	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();843	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;844}845846impl pallet_common::Config for Runtime {847	type Event = Event;848	type Currency = Balances;849	type CollectionCreationPrice = CollectionCreationPrice;850	type TreasuryAccountId = TreasuryAccountId;851}852853impl pallet_evm::account::Config for Runtime {854	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;855	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;856	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;857}858859impl pallet_fungible::Config for Runtime {860	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;861}862impl pallet_refungible::Config for Runtime {863	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;864}865impl pallet_nonfungible::Config for Runtime {866	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;867}868869impl pallet_unique::Config for Runtime {870	type Event = Event;871	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;872}873874parameter_types! {875	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied876}877878/// Used for the pallet inflation879impl pallet_inflation::Config for Runtime {880	type Currency = Balances;881	type TreasuryAccountId = TreasuryAccountId;882	type InflationBlockInterval = InflationBlockInterval;883	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;884}885886// parameter_types! {887// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *888// 		RuntimeBlockWeights::get().max_block;889// 	pub const MaxScheduledPerBlock: u32 = 50;890// }891892type EvmSponsorshipHandler = (893	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,894	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,895);896type SponsorshipHandler = (897	pallet_unique::UniqueSponsorshipHandler<Runtime>,898	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,899	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,900);901902// impl pallet_unq_scheduler::Config for Runtime {903// 	type Event = Event;904// 	type Origin = Origin;905// 	type PalletsOrigin = OriginCaller;906// 	type Call = Call;907// 	type MaximumWeight = MaximumSchedulerWeight;908// 	type ScheduleOrigin = EnsureSigned<AccountId>;909// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;910// 	type SponsorshipHandler = SponsorshipHandler;911// 	type WeightInfo = ();912// }913914impl pallet_evm_transaction_payment::Config for Runtime {915	type EvmSponsorshipHandler = EvmSponsorshipHandler;916	type Currency = Balances;917}918919impl pallet_charge_transaction::Config for Runtime {920	type SponsorshipHandler = SponsorshipHandler;921}922923// impl pallet_contract_helpers::Config for Runtime {924//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;925// }926927parameter_types! {928	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049929	pub const HelpersContractAddress: H160 = H160([930		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,931	]);932}933934impl pallet_evm_contract_helpers::Config for Runtime {935	type ContractAddress = HelpersContractAddress;936	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;937}938939construct_runtime!(940	pub enum Runtime where941		Block = Block,942		NodeBlock = opaque::Block,943		UncheckedExtrinsic = UncheckedExtrinsic944	{945		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,946		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,947948		Aura: pallet_aura::{Pallet, Config<T>} = 22,949		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,950951		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,952		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,953		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,954		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,955		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,956		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,957		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,958		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,959		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,960		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,961962		// XCM helpers.963		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,964		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,965		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,966		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,967968		// Unique Pallets969		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,970		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,971		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,972		// free = 63973		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,974		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,975		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,976		Fungible: pallet_fungible::{Pallet, Storage} = 67,977		Refungible: pallet_refungible::{Pallet, Storage} = 68,978		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,979980		// Frontier981		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,982		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,983984		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,985		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,986		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,987		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,988	}989);990991pub struct TransactionConverter;992993impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {994	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {995		UncheckedExtrinsic::new_unsigned(996			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),997		)998	}999}10001001impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1002	fn convert_transaction(1003		&self,1004		transaction: pallet_ethereum::Transaction,1005	) -> opaque::UncheckedExtrinsic {1006		let extrinsic = UncheckedExtrinsic::new_unsigned(1007			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1008		);1009		let encoded = extrinsic.encode();1010		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1011			.expect("Encoded extrinsic is always valid")1012	}1013}10141015/// The address format for describing accounts.1016pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1017/// Block header type as expected by this runtime.1018pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1019/// Block type as expected by this runtime.1020pub type Block = generic::Block<Header, UncheckedExtrinsic>;1021/// A Block signed with a Justification1022pub type SignedBlock = generic::SignedBlock<Block>;1023/// BlockId type as expected by this runtime.1024pub type BlockId = generic::BlockId<Block>;1025/// The SignedExtension to the basic transaction logic.1026pub type SignedExtra = (1027	frame_system::CheckSpecVersion<Runtime>,1028	// system::CheckTxVersion<Runtime>,1029	frame_system::CheckGenesis<Runtime>,1030	frame_system::CheckEra<Runtime>,1031	frame_system::CheckNonce<Runtime>,1032	frame_system::CheckWeight<Runtime>,1033	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1034	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1035);1036/// Unchecked extrinsic type as expected by this runtime.1037pub type UncheckedExtrinsic =1038	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1039/// Extrinsic type that has already been checked.1040pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1041/// Executive: handles dispatch to the various modules.1042pub type Executive = frame_executive::Executive<1043	Runtime,1044	Block,1045	frame_system::ChainContext<Runtime>,1046	Runtime,1047	AllPalletsReversedWithSystemFirst,1048>;10491050impl_opaque_keys! {1051	pub struct SessionKeys {1052		pub aura: Aura,1053	}1054}10551056impl fp_self_contained::SelfContainedCall for Call {1057	type SignedInfo = H160;10581059	fn is_self_contained(&self) -> bool {1060		match self {1061			Call::Ethereum(call) => call.is_self_contained(),1062			_ => false,1063		}1064	}10651066	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1067		match self {1068			Call::Ethereum(call) => call.check_self_contained(),1069			_ => None,1070		}1071	}10721073	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1074		match self {1075			Call::Ethereum(call) => call.validate_self_contained(info),1076			_ => None,1077		}1078	}10791080	fn pre_dispatch_self_contained(1081		&self,1082		info: &Self::SignedInfo,1083	) -> Option<Result<(), TransactionValidityError>> {1084		match self {1085			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1086			_ => None,1087		}1088	}10891090	fn apply_self_contained(1091		self,1092		info: Self::SignedInfo,1093	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1094		match self {1095			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1096				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1097			)),1098			_ => None,1099		}1100	}1101}11021103macro_rules! dispatch_unique_runtime {1104	($collection:ident.$method:ident($($name:ident),*)) => {{1105		use pallet_unique::dispatch::Dispatched;11061107		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1108		let dispatch = collection.as_dyn();11091110		Ok(dispatch.$method($($name),*))1111	}};1112}11131114impl_common_runtime_apis!();11151116struct CheckInherents;11171118impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1119	fn check_inherents(1120		block: &Block,1121		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1122	) -> sp_inherents::CheckInherentsResult {1123		let relay_chain_slot = relay_state_proof1124			.read_slot()1125			.expect("Could not read the relay chain slot from the proof");11261127		let inherent_data =1128			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1129				relay_chain_slot,1130				sp_std::time::Duration::from_secs(6),1131			)1132			.create_inherent_data()1133			.expect("Could not create the timestamp inherent data");11341135		inherent_data.check_extrinsics(block)1136	}1137}11381139cumulus_pallet_parachain_system::register_validate_block!(1140	Runtime = Runtime,1141	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1142	CheckInherents = CheckInherents,1143);
after · runtime/unique/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37	transaction_validity::{TransactionSource, TransactionValidity},38	ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52	EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55	construct_runtime, match_type,56	dispatch::DispatchResult,57	PalletId, parameter_types, StorageValue, ConsensusEngineId,58	traits::{59		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61		OnUnbalanced, Randomness, FindAuthor,62	},63	weights::{64		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,67	},68};69use up_data_structs::*;70// use pallet_contracts::weights::WeightInfo;71// #[cfg(any(feature = "std", test))]72use frame_system::{73	self as frame_system, EnsureRoot, EnsureSigned,74	limits::{BlockWeights, BlockLength},75};76use sp_arithmetic::{77	traits::{BaseArithmetic, Unsigned},78};79use smallvec::smallvec;80use codec::{Encode, Decode};81use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};82use fp_rpc::TransactionStatus;83use sp_runtime::{84	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85	transaction_validity::TransactionValidityError,86	SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;9091// Polkadot imports92use pallet_xcm::XcmPassthrough;93use polkadot_parachain::primitives::Sibling;94use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};95use xcm_builder::{96	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,97	EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,98	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,99	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,100	ParentIsPreset,101};102use xcm_executor::{Config, XcmExecutor, Assets};103use sp_std::{marker::PhantomData};104105use xcm::latest::{106	//	Xcm,107	AssetId::{Concrete},108	Fungibility::Fungible as XcmFungible,109	MultiAsset,110	Error as XcmError,111};112use xcm_executor::traits::{MatchesFungible, WeightTrader};113//use xcm_executor::traits::MatchesFungible;114use sp_runtime::traits::CheckedConversion;115116use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};117118pub const RUNTIME_NAME: &str = "unique";119pub const TOKEN_SYMBOL: &str = "UNQ";120121type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;122123impl RuntimeInstance for Runtime {124	type CrossAccountId = self::CrossAccountId;125126	type TransactionConverter = self::TransactionConverter;127128	fn get_transaction_converter() -> TransactionConverter {129		TransactionConverter130	}131}132133/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know134/// the specifics of the runtime. They can then be made to be agnostic over specific formats135/// of data like extrinsics, allowing for them to continue syncing the network through upgrades136/// to even the core data structures.137pub mod opaque {138	use sp_std::prelude::*;139	use sp_runtime::impl_opaque_keys;140	use super::Aura;141142	pub use unique_runtime_common::types::*;143144	impl_opaque_keys! {145		pub struct SessionKeys {146			pub aura: Aura,147		}148	}149}150151/// This runtime version.152pub const VERSION: RuntimeVersion = RuntimeVersion {153	spec_name: create_runtime_str!(RUNTIME_NAME),154	impl_name: create_runtime_str!(RUNTIME_NAME),155	authoring_version: 1,156	spec_version: 918001,157	impl_version: 0,158	apis: RUNTIME_API_VERSIONS,159	transaction_version: 1,160	state_version: 0,161};162163#[derive(codec::Encode, codec::Decode)]164pub enum XCMPMessage<XAccountId, XBalance> {165	/// Transfer tokens to the given account from the Parachain account.166	TransferToken(XAccountId, XBalance),167}168169/// The version information used to identify this runtime when compiled natively.170#[cfg(feature = "std")]171pub fn native_version() -> NativeVersion {172	NativeVersion {173		runtime_version: VERSION,174		can_author_with: Default::default(),175	}176}177178type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;179180pub struct DealWithFees;181impl OnUnbalanced<NegativeImbalance> for DealWithFees {182	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {183		if let Some(fees) = fees_then_tips.next() {184			// for fees, 100% to treasury185			let mut split = fees.ration(100, 0);186			if let Some(tips) = fees_then_tips.next() {187				// for tips, if any, 100% to treasury188				tips.ration_merge_into(100, 0, &mut split);189			}190			Treasury::on_unbalanced(split.0);191			// Author::on_unbalanced(split.1);192		}193	}194}195196parameter_types! {197	pub const BlockHashCount: BlockNumber = 2400;198	pub RuntimeBlockLength: BlockLength =199		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);200	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);201	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;202	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()203		.base_block(BlockExecutionWeight::get())204		.for_class(DispatchClass::all(), |weights| {205			weights.base_extrinsic = ExtrinsicBaseWeight::get();206		})207		.for_class(DispatchClass::Normal, |weights| {208			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);209		})210		.for_class(DispatchClass::Operational, |weights| {211			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);212			// Operational transactions have some extra reserved space, so that they213			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.214			weights.reserved = Some(215				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT216			);217		})218		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)219		.build_or_panic();220	pub const Version: RuntimeVersion = VERSION;221	pub const SS58Prefix: u16 = 7391;222}223224parameter_types! {225	pub const ChainId: u64 = 8880;226}227228pub struct FixedFee;229impl FeeCalculator for FixedFee {230	fn min_gas_price() -> U256 {231		MIN_GAS_PRICE.into()232	}233}234235// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case236// (contract, which only writes a lot of data),237// approximating on top of our real store write weight238parameter_types! {239	pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;240	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;241	pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();242}243244/// Limiting EVM execution to 50% of block for substrate users and management tasks245/// EVM transaction consumes more weight than substrate's, so we can't rely on them being246/// scheduled fairly247const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);248parameter_types! {249	pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());250}251252pub enum FixedGasWeightMapping {}253impl GasWeightMapping for FixedGasWeightMapping {254	fn gas_to_weight(gas: u64) -> Weight {255		gas.saturating_mul(WeightPerGas::get())256	}257	fn weight_to_gas(weight: Weight) -> u64 {258		weight / WeightPerGas::get()259	}260}261262impl pallet_evm::Config for Runtime {263	type BlockGasLimit = BlockGasLimit;264	type FeeCalculator = FixedFee;265	type GasWeightMapping = FixedGasWeightMapping;266	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;267	type CallOrigin = EnsureAddressTruncated;268	type WithdrawOrigin = EnsureAddressTruncated;269	type AddressMapping = HashedAddressMapping<Self::Hashing>;270	type PrecompilesType = ();271	type PrecompilesValue = ();272	type Currency = Balances;273	type Event = Event;274	type OnMethodCall = (275		pallet_evm_migration::OnMethodCall<Self>,276		pallet_unique::UniqueErcSupport<Self>,277		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,278	);279	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;280	type ChainId = ChainId;281	type Runner = pallet_evm::runner::stack::Runner<Self>;282	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;283	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;284	type FindAuthor = EthereumFindAuthor<Aura>;285}286287impl pallet_evm_migration::Config for Runtime {288	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;289}290291pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);292impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {293	fn find_author<'a, I>(digests: I) -> Option<H160>294	where295		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,296	{297		if let Some(author_index) = F::find_author(digests) {298			let authority_id = Aura::authorities()[author_index as usize].clone();299			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));300		}301		None302	}303}304305impl pallet_ethereum::Config for Runtime {306	type Event = Event;307	type StateRoot = pallet_ethereum::IntermediateStateRoot;308}309310impl pallet_randomness_collective_flip::Config for Runtime {}311312impl frame_system::Config for Runtime {313	/// The data to be stored in an account.314	type AccountData = pallet_balances::AccountData<Balance>;315	/// The identifier used to distinguish between accounts.316	type AccountId = AccountId;317	/// The basic call filter to use in dispatchable.318	type BaseCallFilter = Everything;319	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).320	type BlockHashCount = BlockHashCount;321	/// The maximum length of a block (in bytes).322	type BlockLength = RuntimeBlockLength;323	/// The index type for blocks.324	type BlockNumber = BlockNumber;325	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.326	type BlockWeights = RuntimeBlockWeights;327	/// The aggregated dispatch type that is available for extrinsics.328	type Call = Call;329	/// The weight of database operations that the runtime can invoke.330	type DbWeight = RocksDbWeight;331	/// The ubiquitous event type.332	type Event = Event;333	/// The type for hashing blocks and tries.334	type Hash = Hash;335	/// The hashing algorithm used.336	type Hashing = BlakeTwo256;337	/// The header type.338	type Header = generic::Header<BlockNumber, BlakeTwo256>;339	/// The index type for storing how many extrinsics an account has signed.340	type Index = Index;341	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.342	type Lookup = AccountIdLookup<AccountId, ()>;343	/// What to do if an account is fully reaped from the system.344	type OnKilledAccount = ();345	/// What to do if a new account is created.346	type OnNewAccount = ();347	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;348	/// The ubiquitous origin type.349	type Origin = Origin;350	/// This type is being generated by `construct_runtime!`.351	type PalletInfo = PalletInfo;352	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.353	type SS58Prefix = SS58Prefix;354	/// Weight information for the extrinsics of this pallet.355	type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;356	/// Version of the runtime.357	type Version = Version;358	type MaxConsumers = ConstU32<16>;359}360361parameter_types! {362	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;363}364365impl pallet_timestamp::Config for Runtime {366	/// A timestamp: milliseconds since the unix epoch.367	type Moment = u64;368	type OnTimestampSet = ();369	type MinimumPeriod = MinimumPeriod;370	type WeightInfo = ();371}372373parameter_types! {374	// pub const ExistentialDeposit: u128 = 500;375	pub const ExistentialDeposit: u128 = 0;376	pub const MaxLocks: u32 = 50;377}378379impl pallet_balances::Config for Runtime {380	type MaxLocks = MaxLocks;381	type MaxReserves = ();382	type ReserveIdentifier = [u8; 8];383	/// The type for recording an account's balance.384	type Balance = Balance;385	/// The ubiquitous event type.386	type Event = Event;387	type DustRemoval = Treasury;388	type ExistentialDeposit = ExistentialDeposit;389	type AccountStore = System;390	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;391}392393pub const fn deposit(items: u32, bytes: u32) -> Balance {394	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE395}396397/*398parameter_types! {399	pub TombstoneDeposit: Balance = deposit(400		1,401		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,402	);403	pub DepositPerContract: Balance = TombstoneDeposit::get();404	pub const DepositPerStorageByte: Balance = deposit(0, 1);405	pub const DepositPerStorageItem: Balance = deposit(1, 0);406	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);407	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;408	pub const SignedClaimHandicap: u32 = 2;409	pub const MaxDepth: u32 = 32;410	pub const MaxValueSize: u32 = 16 * 1024;411	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb412	// The lazy deletion runs inside on_initialize.413	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *414		RuntimeBlockWeights::get().max_block;415	// The weight needed for decoding the queue should be less or equal than a fifth416	// of the overall weight dedicated to the lazy deletion.417	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (418			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -419			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)420		)) / 5) as u32;421	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();422}423424impl pallet_contracts::Config for Runtime {425	type Time = Timestamp;426	type Randomness = RandomnessCollectiveFlip;427	type Currency = Balances;428	type Event = Event;429	type RentPayment = ();430	type SignedClaimHandicap = SignedClaimHandicap;431	type TombstoneDeposit = TombstoneDeposit;432	type DepositPerContract = DepositPerContract;433	type DepositPerStorageByte = DepositPerStorageByte;434	type DepositPerStorageItem = DepositPerStorageItem;435	type RentFraction = RentFraction;436	type SurchargeReward = SurchargeReward;437	type WeightPrice = pallet_transaction_payment::Pallet<Self>;438	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;439	type ChainExtension = NFTExtension;440	type DeletionQueueDepth = DeletionQueueDepth;441	type DeletionWeightLimit = DeletionWeightLimit;442	type Schedule = Schedule;443	type CallStack = [pallet_contracts::Frame<Self>; 31];444}445*/446447parameter_types! {448	/// This value increases the priority of `Operational` transactions by adding449	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.450	pub const OperationalFeeMultiplier: u8 = 5;451}452453/// Linear implementor of `WeightToFeePolynomial`454pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);455456impl<T> WeightToFeePolynomial for LinearFee<T>457where458	T: BaseArithmetic + From<u32> + Copy + Unsigned,459{460	type Balance = T;461462	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {463		smallvec!(WeightToFeeCoefficient {464			// Targeting 0.1 Unique per NFT transfer465			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),466			coeff_frac: Perbill::zero(),467			negative: false,468			degree: 1,469		})470	}471}472473impl pallet_transaction_payment::Config for Runtime {474	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;475	type TransactionByteFee = TransactionByteFee;476	type OperationalFeeMultiplier = OperationalFeeMultiplier;477	type WeightToFee = LinearFee<Balance>;478	type FeeMultiplierUpdate = ();479}480481parameter_types! {482	pub const ProposalBond: Permill = Permill::from_percent(5);483	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;484	pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;485	pub const SpendPeriod: BlockNumber = 5 * MINUTES;486	pub const Burn: Permill = Permill::from_percent(0);487	pub const TipCountdown: BlockNumber = 1 * DAYS;488	pub const TipFindersFee: Percent = Percent::from_percent(20);489	pub const TipReportDepositBase: Balance = 1 * UNIQUE;490	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;491	pub const BountyDepositBase: Balance = 1 * UNIQUE;492	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;493	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");494	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;495	pub const MaximumReasonLength: u32 = 16384;496	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);497	pub const BountyValueMinimum: Balance = 5 * UNIQUE;498	pub const MaxApprovals: u32 = 100;499}500501impl pallet_treasury::Config for Runtime {502	type PalletId = TreasuryModuleId;503	type Currency = Balances;504	type ApproveOrigin = EnsureRoot<AccountId>;505	type RejectOrigin = EnsureRoot<AccountId>;506	type Event = Event;507	type OnSlash = ();508	type ProposalBond = ProposalBond;509	type ProposalBondMinimum = ProposalBondMinimum;510	type ProposalBondMaximum = ProposalBondMaximum;511	type SpendPeriod = SpendPeriod;512	type Burn = Burn;513	type BurnDestination = ();514	type SpendFunds = ();515	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;516	type MaxApprovals = MaxApprovals;517}518519impl pallet_sudo::Config for Runtime {520	type Event = Event;521	type Call = Call;522}523524pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);525526impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider527	for RelayChainBlockNumberProvider<T>528{529	type BlockNumber = BlockNumber;530531	fn current_block_number() -> Self::BlockNumber {532		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()533			.map(|d| d.relay_parent_number)534			.unwrap_or_default()535	}536}537538parameter_types! {539	pub const MinVestedTransfer: Balance = 10 * UNIQUE;540	pub const MaxVestingSchedules: u32 = 28;541}542543impl orml_vesting::Config for Runtime {544	type Event = Event;545	type Currency = pallet_balances::Pallet<Runtime>;546	type MinVestedTransfer = MinVestedTransfer;547	type VestedTransferOrigin = EnsureSigned<AccountId>;548	type WeightInfo = ();549	type MaxVestingSchedules = MaxVestingSchedules;550	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;551}552553parameter_types! {554	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;555	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;556}557558impl cumulus_pallet_parachain_system::Config for Runtime {559	type Event = Event;560	type SelfParaId = parachain_info::Pallet<Self>;561	type OnSystemEvent = ();562	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<563	// 	MaxDownwardMessageWeight,564	// 	XcmExecutor<XcmConfig>,565	// 	Call,566	// >;567	type OutboundXcmpMessageSource = XcmpQueue;568	type DmpMessageHandler = DmpQueue;569	type ReservedDmpWeight = ReservedDmpWeight;570	type ReservedXcmpWeight = ReservedXcmpWeight;571	type XcmpMessageHandler = XcmpQueue;572}573574impl parachain_info::Config for Runtime {}575576impl cumulus_pallet_aura_ext::Config for Runtime {}577578parameter_types! {579	pub const RelayLocation: MultiLocation = MultiLocation::parent();580	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;581	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();582	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();583}584585/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used586/// when determining ownership of accounts for asset transacting and when attempting to use XCM587/// `Transact` in order to determine the dispatch Origin.588pub type LocationToAccountId = (589	// The parent (Relay-chain) origin converts to the default `AccountId`.590	ParentIsPreset<AccountId>,591	// Sibling parachain origins convert to AccountId via the `ParaId::into`.592	SiblingParachainConvertsVia<Sibling, AccountId>,593	// Straight up local `AccountId32` origins just alias directly to `AccountId`.594	AccountId32Aliases<RelayNetwork, AccountId>,595);596597pub struct OnlySelfCurrency;598impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {599	fn matches_fungible(a: &MultiAsset) -> Option<B> {600		match (&a.id, &a.fun) {601			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),602			_ => None,603		}604	}605}606607/// Means for transacting assets on this chain.608pub type LocalAssetTransactor = CurrencyAdapter<609	// Use this currency:610	Balances,611	// Use this currency when it is a fungible asset matching the given location or name:612	OnlySelfCurrency,613	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:614	LocationToAccountId,615	// Our chain's account ID type (we can't get away without mentioning it explicitly):616	AccountId,617	// We don't track any teleports.618	(),619>;620621/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,622/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can623/// biases the kind of local `Origin` it will become.624pub type XcmOriginToTransactDispatchOrigin = (625	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location626	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for627	// foreign chains who want to have a local sovereign account on this chain which they control.628	SovereignSignedViaLocation<LocationToAccountId, Origin>,629	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when630	// recognised.631	RelayChainAsNative<RelayOrigin, Origin>,632	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when633	// recognised.634	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,635	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a636	// transaction from the Root origin.637	ParentAsSuperuser<Origin>,638	// Native signed account converter; this just converts an `AccountId32` origin into a normal639	// `Origin::Signed` origin of the same 32-byte value.640	SignedAccountId32AsNative<RelayNetwork, Origin>,641	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.642	XcmPassthrough<Origin>,643);644645parameter_types! {646	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.647	pub UnitWeightCost: Weight = 1_000_000;648	// 1200 UNIQUEs buy 1 second of weight.649	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);650	pub const MaxInstructions: u32 = 100;651	pub const MaxAuthorities: u32 = 100_000;652}653654match_type! {655	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {656		MultiLocation { parents: 1, interior: Here } |657		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }658	};659}660661pub type Barrier = (662	TakeWeightCredit,663	AllowTopLevelPaidExecutionFrom<Everything>,664	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,665	// ^^^ Parent & its unit plurality gets free execution666);667668pub struct UsingOnlySelfCurrencyComponents<669	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,670	AssetId: Get<MultiLocation>,671	AccountId,672	Currency: CurrencyT<AccountId>,673	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,674>(675	Weight,676	Currency::Balance,677	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,678);679impl<680		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,681		AssetId: Get<MultiLocation>,682		AccountId,683		Currency: CurrencyT<AccountId>,684		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,685	> WeightTrader686	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>687{688	fn new() -> Self {689		Self(0, Zero::zero(), PhantomData)690	}691692	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {693		let amount = WeightToFee::calc(&weight);694		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;695696		// location to this parachain through relay chain697		let option1: xcm::v1::AssetId = Concrete(MultiLocation {698			parents: 1,699			interior: X1(Parachain(ParachainInfo::parachain_id().into())),700		});701		// direct location702		let option2: xcm::v1::AssetId = Concrete(MultiLocation {703			parents: 0,704			interior: Here,705		});706707		let required = if payment.fungible.contains_key(&option1) {708			(option1, u128_amount).into()709		} else if payment.fungible.contains_key(&option2) {710			(option2, u128_amount).into()711		} else {712			(Concrete(MultiLocation::default()), u128_amount).into()713		};714715		let unused = payment716			.checked_sub(required)717			.map_err(|_| XcmError::TooExpensive)?;718		self.0 = self.0.saturating_add(weight);719		self.1 = self.1.saturating_add(amount);720		Ok(unused)721	}722723	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {724		let weight = weight.min(self.0);725		let amount = WeightToFee::calc(&weight);726		self.0 -= weight;727		self.1 = self.1.saturating_sub(amount);728		let amount: u128 = amount.saturated_into();729		if amount > 0 {730			Some((AssetId::get(), amount).into())731		} else {732			None733		}734	}735}736impl<737		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,738		AssetId: Get<MultiLocation>,739		AccountId,740		Currency: CurrencyT<AccountId>,741		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,742	> Drop743	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>744{745	fn drop(&mut self) {746		OnUnbalanced::on_unbalanced(Currency::issue(self.1));747	}748}749750pub struct XcmConfig;751impl Config for XcmConfig {752	type Call = Call;753	type XcmSender = XcmRouter;754	// How to withdraw and deposit an asset.755	type AssetTransactor = LocalAssetTransactor;756	type OriginConverter = XcmOriginToTransactDispatchOrigin;757	type IsReserve = NativeAsset;758	type IsTeleporter = (); // Teleportation is disabled759	type LocationInverter = LocationInverter<Ancestry>;760	type Barrier = Barrier;761	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;762	type Trader = UsingOnlySelfCurrencyComponents<763		IdentityFee<Balance>,764		RelayLocation,765		AccountId,766		Balances,767		(),768	>;769	type ResponseHandler = (); // Don't handle responses for now.770	type SubscriptionService = PolkadotXcm;771772	type AssetTrap = PolkadotXcm;773	type AssetClaims = PolkadotXcm;774}775776// parameter_types! {777// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;778// }779780/// No local origins on this chain are allowed to dispatch XCM sends/executions.781pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);782783/// The means for routing XCM messages which are not for local execution into the right message784/// queues.785pub type XcmRouter = (786	// Two routers - use UMP to communicate with the relay chain:787	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,788	// ..and XCMP to communicate with the sibling chains.789	XcmpQueue,790);791792impl pallet_evm_coder_substrate::Config for Runtime {793	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;794	type GasWeightMapping = FixedGasWeightMapping;795}796797impl pallet_xcm::Config for Runtime {798	type Event = Event;799	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;800	type XcmRouter = XcmRouter;801	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;802	type XcmExecuteFilter = Everything;803	type XcmExecutor = XcmExecutor<XcmConfig>;804	type XcmTeleportFilter = Everything;805	type XcmReserveTransferFilter = Everything;806	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;807	type LocationInverter = LocationInverter<Ancestry>;808	type Origin = Origin;809	type Call = Call;810	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;811	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;812}813814impl cumulus_pallet_xcm::Config for Runtime {815	type Event = Event;816	type XcmExecutor = XcmExecutor<XcmConfig>;817}818819impl cumulus_pallet_xcmp_queue::Config for Runtime {820	type WeightInfo = ();821	type Event = Event;822	type XcmExecutor = XcmExecutor<XcmConfig>;823	type ChannelInfo = ParachainSystem;824	type VersionWrapper = ();825	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;826	type ControllerOrigin = EnsureRoot<AccountId>;827	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;828}829830impl cumulus_pallet_dmp_queue::Config for Runtime {831	type Event = Event;832	type XcmExecutor = XcmExecutor<XcmConfig>;833	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;834}835836impl pallet_aura::Config for Runtime {837	type AuthorityId = AuraId;838	type DisabledValidators = ();839	type MaxAuthorities = MaxAuthorities;840}841842parameter_types! {843	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();844	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;845}846847impl pallet_common::Config for Runtime {848	type Event = Event;849	type Currency = Balances;850	type CollectionCreationPrice = CollectionCreationPrice;851	type TreasuryAccountId = TreasuryAccountId;852}853854impl pallet_evm::account::Config for Runtime {855	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;856	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;857	type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;858}859860impl pallet_fungible::Config for Runtime {861	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;862}863impl pallet_refungible::Config for Runtime {864	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;865}866impl pallet_nonfungible::Config for Runtime {867	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;868}869870impl pallet_unique::Config for Runtime {871	type Event = Event;872	type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;873}874875parameter_types! {876	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied877}878879/// Used for the pallet inflation880impl pallet_inflation::Config for Runtime {881	type Currency = Balances;882	type TreasuryAccountId = TreasuryAccountId;883	type InflationBlockInterval = InflationBlockInterval;884	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;885}886887// parameter_types! {888// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *889// 		RuntimeBlockWeights::get().max_block;890// 	pub const MaxScheduledPerBlock: u32 = 50;891// }892893type EvmSponsorshipHandler = (894	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,895	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,896);897type SponsorshipHandler = (898	pallet_unique::UniqueSponsorshipHandler<Runtime>,899	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,900	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,901);902903// impl pallet_unq_scheduler::Config for Runtime {904// 	type Event = Event;905// 	type Origin = Origin;906// 	type PalletsOrigin = OriginCaller;907// 	type Call = Call;908// 	type MaximumWeight = MaximumSchedulerWeight;909// 	type ScheduleOrigin = EnsureSigned<AccountId>;910// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;911// 	type SponsorshipHandler = SponsorshipHandler;912// 	type WeightInfo = ();913// }914915impl pallet_evm_transaction_payment::Config for Runtime {916	type EvmSponsorshipHandler = EvmSponsorshipHandler;917	type Currency = Balances;918}919920impl pallet_charge_transaction::Config for Runtime {921	type SponsorshipHandler = SponsorshipHandler;922}923924// impl pallet_contract_helpers::Config for Runtime {925//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;926// }927928parameter_types! {929	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049930	pub const HelpersContractAddress: H160 = H160([931		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,932	]);933}934935impl pallet_evm_contract_helpers::Config for Runtime {936	type ContractAddress = HelpersContractAddress;937	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;938}939940construct_runtime!(941	pub enum Runtime where942		Block = Block,943		NodeBlock = opaque::Block,944		UncheckedExtrinsic = UncheckedExtrinsic945	{946		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,947		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,948949		Aura: pallet_aura::{Pallet, Config<T>} = 22,950		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,951952		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,953		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,954		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,955		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,956		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,957		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,958		System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,959		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,960		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,961		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,962963		// XCM helpers.964		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,965		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,966		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,967		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,968969		// Unique Pallets970		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,971		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,972		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,973		// free = 63974		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,975		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,976		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,977		Fungible: pallet_fungible::{Pallet, Storage} = 67,978		Refungible: pallet_refungible::{Pallet, Storage} = 68,979		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,980981		// Frontier982		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,983		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,984985		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,986		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,987		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,988		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,989	}990);991992pub struct TransactionConverter;993994impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {995	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {996		UncheckedExtrinsic::new_unsigned(997			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),998		)999	}1000}10011002impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1003	fn convert_transaction(1004		&self,1005		transaction: pallet_ethereum::Transaction,1006	) -> opaque::UncheckedExtrinsic {1007		let extrinsic = UncheckedExtrinsic::new_unsigned(1008			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1009		);1010		let encoded = extrinsic.encode();1011		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1012			.expect("Encoded extrinsic is always valid")1013	}1014}10151016/// The address format for describing accounts.1017pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1018/// Block header type as expected by this runtime.1019pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1020/// Block type as expected by this runtime.1021pub type Block = generic::Block<Header, UncheckedExtrinsic>;1022/// A Block signed with a Justification1023pub type SignedBlock = generic::SignedBlock<Block>;1024/// BlockId type as expected by this runtime.1025pub type BlockId = generic::BlockId<Block>;1026/// The SignedExtension to the basic transaction logic.1027pub type SignedExtra = (1028	frame_system::CheckSpecVersion<Runtime>,1029	// system::CheckTxVersion<Runtime>,1030	frame_system::CheckGenesis<Runtime>,1031	frame_system::CheckEra<Runtime>,1032	frame_system::CheckNonce<Runtime>,1033	frame_system::CheckWeight<Runtime>,1034	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1035	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,1036);1037/// Unchecked extrinsic type as expected by this runtime.1038pub type UncheckedExtrinsic =1039	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1040/// Extrinsic type that has already been checked.1041pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1042/// Executive: handles dispatch to the various modules.1043pub type Executive = frame_executive::Executive<1044	Runtime,1045	Block,1046	frame_system::ChainContext<Runtime>,1047	Runtime,1048	AllPalletsReversedWithSystemFirst,1049>;10501051impl_opaque_keys! {1052	pub struct SessionKeys {1053		pub aura: Aura,1054	}1055}10561057impl fp_self_contained::SelfContainedCall for Call {1058	type SignedInfo = H160;10591060	fn is_self_contained(&self) -> bool {1061		match self {1062			Call::Ethereum(call) => call.is_self_contained(),1063			_ => false,1064		}1065	}10661067	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1068		match self {1069			Call::Ethereum(call) => call.check_self_contained(),1070			_ => None,1071		}1072	}10731074	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1075		match self {1076			Call::Ethereum(call) => call.validate_self_contained(info),1077			_ => None,1078		}1079	}10801081	fn pre_dispatch_self_contained(1082		&self,1083		info: &Self::SignedInfo,1084	) -> Option<Result<(), TransactionValidityError>> {1085		match self {1086			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1087			_ => None,1088		}1089	}10901091	fn apply_self_contained(1092		self,1093		info: Self::SignedInfo,1094	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1095		match self {1096			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1097				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1098			)),1099			_ => None,1100		}1101	}1102}11031104macro_rules! dispatch_unique_runtime {1105	($collection:ident.$method:ident($($name:ident),*)) => {{1106		use pallet_unique::dispatch::Dispatched;11071108		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1109		let dispatch = collection.as_dyn();11101111		Ok(dispatch.$method($($name),*))1112	}};1113}11141115impl_common_runtime_apis!();11161117struct CheckInherents;11181119impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1120	fn check_inherents(1121		block: &Block,1122		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1123	) -> sp_inherents::CheckInherentsResult {1124		let relay_chain_slot = relay_state_proof1125			.read_slot()1126			.expect("Could not read the relay chain slot from the proof");11271128		let inherent_data =1129			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1130				relay_chain_slot,1131				sp_std::time::Duration::from_secs(6),1132			)1133			.create_inherent_data()1134			.expect("Could not create the timestamp inherent data");11351136		inherent_data.check_extrinsics(block)1137	}1138}11391140cumulus_pallet_parachain_system::register_validate_block!(1141	Runtime = Runtime,1142	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1143	CheckInherents = CheckInherents,1144);