git.delta.rocks / unique-network / refs/commits / 90fcef986d5a

difftreelog

Merge pull request #158 from usetech-llc/feature/sponsorship-refactor

Greg Zaitsev2021-06-25parents: #73e89cc #c1a55f7.patch.diff
in: master
Refactor sponsorship logic to reduce cross-crate dependencies

24 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5113,6 +5113,7 @@
  "nft-data-structs",
  "pallet-aura",
  "pallet-balances",
+ "pallet-contract-helpers",
  "pallet-contracts",
  "pallet-contracts-primitives",
  "pallet-contracts-rpc-runtime-api",
@@ -5481,6 +5482,19 @@
 ]
 
 [[package]]
+name = "pallet-contract-helpers"
+version = "0.1.0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "pallet-contracts",
+ "parity-scale-codec 2.1.3",
+ "sp-runtime",
+ "sp-std",
+ "up-sponsorship",
+]
+
+[[package]]
 name = "pallet-contracts"
 version = "3.0.0"
 source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
@@ -5871,6 +5885,7 @@
  "sp-io",
  "sp-runtime",
  "sp-std",
+ "up-sponsorship",
 ]
 
 [[package]]
@@ -5880,13 +5895,8 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
- "nft-data-structs",
  "pallet-balances",
- "pallet-contracts",
- "pallet-nft",
  "pallet-nft-transaction-payment",
- "pallet-randomness-collective-flip",
- "pallet-timestamp",
  "pallet-transaction-payment",
  "parity-scale-codec 2.1.3",
  "serde",
@@ -5903,12 +5913,6 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
- "nft-data-structs",
- "pallet-balances",
- "pallet-contracts",
- "pallet-nft",
- "pallet-randomness-collective-flip",
- "pallet-timestamp",
  "pallet-transaction-payment",
  "parity-scale-codec 2.1.3",
  "serde",
@@ -5916,6 +5920,7 @@
  "sp-io",
  "sp-runtime",
  "sp-std",
+ "up-sponsorship",
 ]
 
 [[package]]
@@ -5996,10 +6001,6 @@
  "frame-support",
  "frame-system",
  "log",
- "nft-data-structs",
- "pallet-contracts",
- "pallet-nft",
- "pallet-nft-transaction-payment",
  "parity-scale-codec 2.1.3",
  "serde",
  "sp-core",
@@ -6007,6 +6008,7 @@
  "sp-runtime",
  "sp-std",
  "substrate-test-utils",
+ "up-sponsorship",
 ]
 
 [[package]]
@@ -11760,6 +11762,13 @@
 checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
 
 [[package]]
+name = "up-sponsorship"
+version = "0.1.0"
+dependencies = [
+ "impl-trait-for-tuples 0.2.1",
+]
+
+[[package]]
 name = "url"
 version = "1.7.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
 members = [
     'node/*',
     'pallets/*',
-    'primitives',
+    'primitives/*',
     'runtime',
     'crates/evm-coder',
     'crates/evm-coder-macros',
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -284,7 +284,7 @@
 version = '3.0.0'
 
 [dependencies.nft-data-structs]
-path="../../primitives"
+path="../../primitives/nft"
 default-features = false
 
 ################################################################################
addedpallets/contract-helpers/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/contract-helpers/Cargo.toml
@@ -0,0 +1,32 @@
+[package]
+name = "pallet-contract-helpers"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies.up-sponsorship]
+default-features = false
+path = '../../primitives/sponsorship'
+version = '0.1.0'
+
+[dependencies]
+frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+
+[features]
+default = ["std"]
+std = [
+    "frame-support/std",
+    "frame-system/std",
+    "pallet-contracts/std",
+    "sp-runtime/std",
+    "sp-std/std",
+]
\ No newline at end of file
addedpallets/contract-helpers/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/contract-helpers/src/lib.rs
@@ -0,0 +1,261 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+pub use pallet::*;
+
+#[frame_support::pallet]
+pub mod pallet {
+	use frame_support::sp_runtime::traits::StaticLookup;
+	use frame_support::{pallet_prelude::*, traits::IsSubType};
+	use frame_system::pallet_prelude::*;
+	use pallet_contracts::chain_extension::UncheckedFrom;
+	use sp_runtime::{
+		traits::{DispatchInfoOf, Hash, PostDispatchInfoOf, SignedExtension},
+		transaction_validity,
+	};
+	use sp_std::vec::Vec;
+	use up_sponsorship::SponsorshipHandler;
+
+    #[pallet::error]
+    pub enum Error<T> {
+        /// Should be contract owner
+        NoPermission,
+    }
+
+	#[pallet::config]
+	pub trait Config: frame_system::Config + pallet_contracts::Config {}
+
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	pub struct Pallet<T>(_);
+
+	#[pallet::storage]
+	pub(super) type Owner<T: Config> = StorageMap<
+		Hasher = Twox128,
+		Key = T::AccountId,
+		Value = T::AccountId,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type AllowlistEnabled<T: Config> =
+		StorageMap<Hasher = Twox128, Key = T::AccountId, Value = bool, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type Allowlist<T: Config> = StorageDoubleMap<
+		Hasher1 = Twox128,
+		Key1 = T::AccountId,
+		Hasher2 = Twox64Concat,
+		Key2 = T::AccountId,
+		Value = bool,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type SelfSponsoring<T: Config> =
+		StorageMap<Hasher = Twox128, Key = T::AccountId, Value = bool, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
+		Hasher = Twox128,
+		Key = T::AccountId,
+		Value = T::BlockNumber,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type SponsorBasket<T: Config> = StorageDoubleMap<
+		Hasher1 = Twox128,
+		Key1 = T::AccountId,
+		Hasher2 = Twox128,
+		Key2 = T::AccountId,
+		Value = T::BlockNumber,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::call]
+	impl<T: Config> Pallet<T> {
+		#[pallet::weight(0)]
+		fn toggle_sponsoring(
+			origin: OriginFor<T>,
+			contract: T::AccountId,
+			sponsoring: bool,
+		) -> DispatchResult {
+			let sender = ensure_signed(origin)?;
+			ensure!(<Owner<T>>::get(&contract) == sender, <Error<T>>::NoPermission);
+
+			if sponsoring {
+				<SelfSponsoring<T>>::insert(contract, true);
+			} else {
+				<SelfSponsoring<T>>::remove(contract);
+			}
+			Ok(())
+		}
+
+		#[pallet::weight(0)]
+		fn toggle_allowlist(
+			origin: OriginFor<T>,
+			contract: T::AccountId,
+			enabled: bool,
+		) -> DispatchResult {
+			let sender = ensure_signed(origin)?;
+			ensure!(<Owner<T>>::get(&contract) == sender, <Error<T>>::NoPermission);
+
+			if enabled {
+				<AllowlistEnabled<T>>::insert(contract, true);
+			} else {
+				<AllowlistEnabled<T>>::remove(contract);
+			}
+			Ok(())
+		}
+
+		#[pallet::weight(0)]
+		fn toggle_allowed(
+			origin: OriginFor<T>,
+			contract: T::AccountId,
+			user: T::AccountId,
+			allowed: bool,
+		) -> DispatchResult {
+			let sender = ensure_signed(origin)?;
+			ensure!(<Owner<T>>::get(&contract) == sender, <Error<T>>::NoPermission);
+
+			if allowed {
+				<Allowlist<T>>::insert(contract, user, true);
+			} else {
+				<Allowlist<T>>::remove(contract, user);
+			}
+			Ok(())
+		}
+
+		#[pallet::weight(0)]
+		fn set_sponsoring_rate_limit(
+			origin: OriginFor<T>,
+			contract: T::AccountId,
+			rate_limit: T::BlockNumber,
+		) -> DispatchResult {
+			let sender = ensure_signed(origin)?;
+			ensure!(<Owner<T>>::get(&contract) == sender, <Error<T>>::NoPermission);
+
+			<SponsoringRateLimit<T>>::insert(contract, rate_limit);
+			Ok(())
+		}
+	}
+
+	#[derive(Encode, Decode, Clone, PartialEq, Eq)]
+	pub struct ContractHelpersExtension<T>(PhantomData<T>);
+	impl<T> core::fmt::Debug for ContractHelpersExtension<T> {
+		fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
+			fmt.debug_struct("ContractHelpersExtension").finish()
+		}
+	}
+
+	type CodeHash<T> = <T as frame_system::Config>::Hash;
+	impl<T> SignedExtension for ContractHelpersExtension<T>
+	where
+		T: Config + Send + Sync,
+		T::Call: sp_runtime::traits::Dispatchable,
+		T::Call: IsSubType<pallet_contracts::Call<T>>,
+		T::AccountId: UncheckedFrom<T::Hash>,
+		T::AccountId: AsRef<[u8]>,
+	{
+		const IDENTIFIER: &'static str = "ContractHelpers";
+		type AccountId = T::AccountId;
+		type Call = T::Call;
+		type AdditionalSigned = ();
+		type Pre = Option<(Self::AccountId, CodeHash<T>, Vec<u8>)>;
+
+		fn additional_signed(&self) -> Result<(), transaction_validity::TransactionValidityError> {
+			Ok(())
+		}
+
+		fn validate(
+			&self,
+			who: &T::AccountId,
+			call: &Self::Call,
+			_info: &DispatchInfoOf<Self::Call>,
+			_len: usize,
+		) -> transaction_validity::TransactionValidity {
+			match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+				Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
+					let called_contract: T::AccountId =
+						T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
+					if <AllowlistEnabled<T>>::get(&called_contract) {
+						if !<Allowlist<T>>::get(&called_contract, who)
+							&& &<Owner<T>>::get(&called_contract) != who
+						{
+							return Err(transaction_validity::InvalidTransaction::Call.into());
+						}
+					}
+				}
+				_ => {}
+			}
+			Ok(transaction_validity::ValidTransaction::default())
+		}
+
+		fn pre_dispatch(
+			self,
+			who: &Self::AccountId,
+			call: &Self::Call,
+			_info: &DispatchInfoOf<Self::Call>,
+			_len: usize,
+		) -> Result<Self::Pre, TransactionValidityError> {
+			match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+				Some(pallet_contracts::Call::instantiate(_, _, code_hash, _, salt)) => {
+					Ok(Some((who.clone(), code_hash.clone(), salt.clone())))
+				}
+				Some(pallet_contracts::Call::instantiate_with_code(_, _, code, _, salt)) => {
+					let code_hash = &T::Hashing::hash(&code);
+					Ok(Some((who.clone(), code_hash.clone(), salt.clone())))
+				}
+				_ => Ok(None),
+			}
+		}
+
+		fn post_dispatch(
+			pre: Self::Pre,
+			_info: &DispatchInfoOf<Self::Call>,
+			_post_info: &PostDispatchInfoOf<Self::Call>,
+			_len: usize,
+			_result: &DispatchResult,
+		) -> Result<(), TransactionValidityError> {
+			if let Some((who, code_hash, salt)) = pre {
+				let new_contract_address =
+					<pallet_contracts::Pallet<T>>::contract_address(&who, &code_hash, &salt);
+				<Owner<T>>::insert(&new_contract_address, &who);
+			}
+
+			Ok(())
+		}
+	}
+
+	pub struct ContractSponsorshipHandler<T>(PhantomData<T>);
+	impl<T, C> SponsorshipHandler<T::AccountId, C> for ContractSponsorshipHandler<T>
+	where
+		T: Config,
+		C: IsSubType<pallet_contracts::Call<T>>,
+		T::AccountId: UncheckedFrom<T::Hash>,
+		T::AccountId: AsRef<[u8]>,
+	{
+		fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {
+			match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+				Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
+					let called_contract: T::AccountId =
+						T::Lookup::lookup((*dest).clone()).unwrap_or_default();
+					if <SelfSponsoring<T>>::get(&called_contract) {
+						let last_tx_block = SponsorBasket::<T>::get(&called_contract, &who);
+						let block_number =
+							<frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+						let rate_limit = SponsoringRateLimit::<T>::get(&called_contract);
+						let limit_time = last_tx_block + rate_limit;
+
+						if block_number >= limit_time {
+							SponsorBasket::<T>::insert(&called_contract, who, block_number);
+							return Some(called_contract);
+						}
+					}
+				}
+				_ => {}
+			}
+			None
+		}
+	}
+}
modifiedpallets/nft-charge-transaction/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft-charge-transaction/Cargo.toml
+++ b/pallets/nft-charge-transaction/Cargo.toml
@@ -23,19 +23,14 @@
 frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 pallet-balances = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-timestamp = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-randomness-collective-flip = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 
-pallet-nft = { default-features = false, path="../nft" }
 pallet-nft-transaction-payment = { default-features = false, path="../nft-transaction-payment" }
-nft-data-structs = { default-features = false, path="../../primitives", version = "0.9.0" }
 
 [features]
 default = ['std']
@@ -45,15 +40,10 @@
     'frame-support/std',
     'frame-system/std',
     'pallet-balances/std',
-    'pallet-timestamp/std',
-    'pallet-randomness-collective-flip/std',
-    'pallet-contracts/std',
-    'pallet-nft/std',
     'pallet-transaction-payment/std',
     'pallet-nft-transaction-payment/std',
     'sp-std/std',
     'sp-runtime/std',
-    'nft-data-structs/std',
     'frame-benchmarking/std',
 ]
 runtime-benchmarks = ["frame-benchmarking"]
modifiedpallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft-charge-transaction/src/lib.rs
+++ b/pallets/nft-charge-transaction/src/lib.rs
@@ -14,16 +14,10 @@
 #[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
 
-#[cfg(test)]
-mod tests;
-
 use codec::{Decode, Encode};
-use frame_support::traits::{ Get};
+use frame_support::traits::Get;
 use frame_support::{
 	decl_module, decl_storage,
-	traits::{
-		IsSubType, 
-	},
 	weights::{
 		DispatchInfo, PostDispatchInfo, DispatchClass
 	}
@@ -37,7 +31,6 @@
 	},
 	FixedPointOperand, DispatchResult
 };
-use pallet_contracts::chain_extension::UncheckedFrom;
 use pallet_transaction_payment::OnChargeTransaction;
 use sp_std::prelude::*;
 
@@ -83,10 +76,8 @@
 
 impl<T: Config> ChargeTransactionPayment<T>
 where
-	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,
+	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo>,
     BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
-    T::AccountId: AsRef<[u8]>,
-    T::AccountId: UncheckedFrom<T::Hash>,
 {
     fn traditional_fee(
         len: usize,
@@ -134,13 +125,6 @@
 			.map(|i| (fee, i));
         }
 
-        // check errors
-        let _error = <pallet_nft_transaction_payment::Module<T>>::check_error(who, call);
-        match _error {
-            Err(_error) => return Err(_error),
-            Ok(_error) => {}
-        };
-
         // Determine who is paying transaction fee based on ecnomic model
 		// Parse call to extract collection ID and access collection sponsor	
 		let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);
@@ -156,9 +140,7 @@
     for ChargeTransactionPayment<T>
 where
     BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
-	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,
-    T::AccountId: AsRef<[u8]>,
-    T::AccountId: UncheckedFrom<T::Hash>,
+	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo>,
 {
     const IDENTIFIER: &'static str = "ChargeTransactionPayment";
     type AccountId = T::AccountId;
@@ -209,7 +191,7 @@
         _result: &DispatchResult,
     ) -> Result<(), TransactionValidityError> {
 		let (tip, who, imbalance) = pre;
-		let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(
+		let actual_fee = pallet_transaction_payment::Pallet::<T>::compute_actual_fee(
 			len as u32,
 			info,
 			post_info,
modifiedpallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft-transaction-payment/Cargo.toml
+++ b/pallets/nft-transaction-payment/Cargo.toml
@@ -22,19 +22,14 @@
 serde = { version = "1.0.119", default-features = false }
 frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-balances = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-timestamp = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-randomness-collective-flip = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 
-pallet-nft = { default-features = false, path="../nft" }
-nft-data-structs = { default-features = false, path="../../primitives", version = "0.9.0" }
+up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
 
 [features]
 default = ['std']
@@ -43,15 +38,13 @@
     'serde/std',
     'frame-support/std',
     'frame-system/std',
-    'pallet-balances/std',
-    'pallet-timestamp/std',
-    'pallet-randomness-collective-flip/std',
-    'pallet-contracts/std',
-    'pallet-nft/std',
+    'sp-core/std',
+    'sp-io/std',
     'pallet-transaction-payment/std',
     'sp-std/std',
     'sp-runtime/std',
-    'nft-data-structs/std',
     'frame-benchmarking/std',
+
+    'up-sponsorship/std',
 ]
 runtime-benchmarks = ["frame-benchmarking"]
modifiedpallets/nft-transaction-payment/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nft-transaction-payment/src/benchmarking.rs
+++ b/pallets/nft-transaction-payment/src/benchmarking.rs
@@ -1,7 +1,6 @@
 #![cfg(feature = "runtime-benchmarks")]
 
 use super::*;
-use crate::Module as NftTransactionPayment;
 
 use sp_std::prelude::*;
 use frame_system::RawOrigin;
modifiedpallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft-transaction-payment/src/lib.rs
+++ b/pallets/nft-transaction-payment/src/lib.rs
@@ -14,388 +14,32 @@
 #[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
 
-#[cfg(test)]
-mod tests;
-
-use frame_support::{
-	decl_error, decl_module, decl_storage,
-	traits::{
-		IsSubType, 
-	},
-	weights::{
-		DispatchInfo
-	}
-};
-use sp_runtime::traits::StaticLookup;
-use sp_runtime::{
-	traits::{ 
-		Hash, Dispatchable,
-	},
-	transaction_validity::{
-        InvalidTransaction, TransactionValidityError,
-    },
-};
-use pallet_contracts::chain_extension::UncheckedFrom;
+use frame_support::{decl_module, decl_storage};
 use sp_std::prelude::*;
-use nft_data_structs::{
-	CreateItemData,
-	CollectionId, CollectionMode, TokenId
-};
-
-type CodeHash<T> = <T as frame_system::Config>::Hash;
+use up_sponsorship::SponsorshipHandler;
 
-	pub trait Config: frame_system::Config + pallet_contracts::Config + pallet_transaction_payment::Config + pallet_nft::Config {
-	}
-
-	// Error for non-fungible-token module.
-	
-	decl_error! {
-		/// Error for non-fungible-token module.
-		pub enum Error for Module<T: Config> {
-		/// No available class ID
-		NoAvailableClassId,
-		/// No available token ID
-		NoAvailableTokenId,
-		/// Token(ClassId, TokenId) not found
-		TokenNotFound,
-		/// Class not found
-		CollectionNotFound,
-		/// The operator is not the owner of the token and has no permission
-		NoPermission,
-		/// Arithmetic calculation overflow
-		NumOverflow,
-		/// Can not destroy class
-		/// Total issuance is not 0
-		CannotDestroyClass,
-	}
+pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
+	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, Self::Call>;
 }
-
-	decl_storage! {
-		trait Store for Module<T: Config> as NftTransactionPayment{
 
+decl_storage! {
+	trait Store for Module<T: Config> as NftTransactionPayment{
 	}
 }
 
 decl_module! {
-
 	pub struct Module<T: Config> for enum Call 
     where 
 		origin: T::Origin,
     {
 	}
 }
-
-impl<T: Config> Module<T> 
-{
 
-	pub fn check_error(
-		who: &T::AccountId,
-		call: &T::Call
-	) -> Result<bool, TransactionValidityError> where 
-		T::Call: Dispatchable<Info=DispatchInfo>,
-		T::Call: IsSubType<pallet_nft::Call<T>>, 
-		T::Call: IsSubType<pallet_contracts::Call<T>>,
-		T::AccountId: AsRef<[u8]>,
-		T::AccountId: UncheckedFrom<T::Hash>
-		{
-
-			match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
-				Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
-	
-					let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
-	
-					let owned_contract = pallet_nft::ContractOwner::<T>::get(called_contract.clone()).as_ref() == Some(who);
-					let white_list_enabled = pallet_nft::ContractWhiteListEnabled::<T>::contains_key(called_contract.clone());
-					  
-					if !owned_contract && white_list_enabled {
-						if !pallet_nft::ContractWhiteList::<T>::contains_key(called_contract.clone(), who) {
-							return Err(InvalidTransaction::Call.into());
-						}
-					}
-					Ok(true)
-				},
-				_ => { Ok(true) },
-			}
-		}
-
+impl<T: Config> Module<T> {
 	pub fn withdraw_type(
 		who: &T::AccountId,
 		call: &T::Call
-	) -> Option<T::AccountId> where 
-		T::Call: Dispatchable<Info=DispatchInfo>,
-		T::Call: IsSubType<pallet_nft::Call<T>>, 
-		T::Call: IsSubType<pallet_contracts::Call<T>>,
-		T::AccountId: AsRef<[u8]>,
-		T::AccountId: UncheckedFrom<T::Hash>
-		{
-
-        let mut sponsor: Option<T::AccountId> = match IsSubType::<pallet_nft::Call<T>>::is_sub_type(call)  {
-            Some(pallet_nft::Call::create_item(collection_id, _owner, _properties)) => {
-
-                Self::withdraw_create_item(who, collection_id, &_properties)
-            },
-            Some(pallet_nft::Call::transfer(_new_owner, collection_id, item_id, _value)) => {
-
-                Self::withdraw_transfer(who, collection_id, item_id)
-            },
-            Some(pallet_nft::Call::set_variable_meta_data(collection_id, item_id, data)) => {
-
-                Self::withdraw_set_variable_meta_data(collection_id, item_id, &data)
-			},
-			_ => None,
-        };
-
-        sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
-            Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
-
-                Self::withdraw_contract_call(who, dest)
-            },
-            Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {
-
-                Self::withdraw_contract_instantiate(&who, code_hash, salt)
-            },
-            Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt))  => {
-
-                Self::withdraw_contract_instantiate(&who, &T::Hashing::hash(&_code), _salt)
-			},
-			_ => None,
-        });
-
-		sponsor
-	}
-
-
-
-	pub fn withdraw_create_item(
-		who: &T::AccountId,
-		collection_id: &CollectionId,
-		_properties: &CreateItemData,
 	) -> Option<T::AccountId> {
-	
-		let collection = pallet_nft::CollectionById::<T>::get(collection_id)?;
-
-		// sponsor timeout
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-
-		let limit = collection.limits.sponsor_transfer_timeout;
-		if pallet_nft::CreateItemBasket::<T>::contains_key((collection_id, &who)) {
-			let last_tx_block = pallet_nft::CreateItemBasket::<T>::get((collection_id, &who));
-			let limit_time = last_tx_block + limit.into();
-			if block_number <= limit_time {
-				return None;
-			}
-		}
-		pallet_nft::CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);
-
-		// check free create limit
-		if collection.limits.sponsored_data_size >= (_properties.len() as u32) {
-			collection.sponsorship.sponsor()
-				.cloned()
-		} else {
-			None
-		}
-	}
-
-	pub fn withdraw_transfer(
-		who: &T::AccountId,
-		collection_id: &CollectionId,
-		item_id: &TokenId,
-	) -> Option<T::AccountId> {
-
-		let collection = pallet_nft::CollectionById::<T>::get(collection_id)?;
-		let limits = pallet_nft::ChainLimit::get();
-
-		let mut sponsor_transfer = false;
-		if collection.sponsorship.confirmed() {
-
-			let collection_limits = collection.limits.clone();
-			let collection_mode = collection.mode.clone();
-
-			// sponsor timeout
-			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-			sponsor_transfer = match collection_mode {
-				CollectionMode::NFT => {
-
-					// get correct limit
-					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
-						collection_limits.sponsor_transfer_timeout
-					} else {
-						limits.nft_sponsor_transfer_timeout
-					};
-
-					let mut sponsored = true;
-					if pallet_nft::NftTransferBasket::<T>::contains_key(collection_id, item_id) {
-						let last_tx_block = pallet_nft::NftTransferBasket::<T>::get(collection_id, item_id);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						pallet_nft::NftTransferBasket::<T>::insert(collection_id, item_id, block_number);
-					}
-
-					sponsored
-				}
-				CollectionMode::Fungible(_) => {
-
-					// get correct limit
-					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
-						collection_limits.sponsor_transfer_timeout
-					} else {
-						limits.fungible_sponsor_transfer_timeout
-					};
-
-					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-					let mut sponsored = true;
-					if pallet_nft::FungibleTransferBasket::<T>::contains_key(collection_id, who) {
-						let last_tx_block = pallet_nft::FungibleTransferBasket::<T>::get(collection_id, who);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						pallet_nft::FungibleTransferBasket::<T>::insert(collection_id, who, block_number);
-					}
-
-					sponsored
-				}
-				CollectionMode::ReFungible => {
-
-					// get correct limit
-					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
-						collection_limits.sponsor_transfer_timeout
-					} else {
-						limits.refungible_sponsor_transfer_timeout
-					};
-
-					let mut sponsored = true;
-					if pallet_nft::ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {
-						let last_tx_block = pallet_nft::ReFungibleTransferBasket::<T>::get(collection_id, item_id);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						pallet_nft::ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);
-					}
-
-					sponsored
-				}
-				_ => {
-					false
-				},
-			};
-		}
-
-		if !sponsor_transfer {
-			None
-		} else {
-			collection.sponsorship.sponsor()
-				.cloned()
-		}
-	}
-	
-	pub fn withdraw_set_variable_meta_data(
-		collection_id: &CollectionId,
-		item_id: &TokenId,
-		data: &Vec<u8>,
-	) -> Option<T::AccountId> {
-
-		let mut sponsor_metadata_changes = false;
-
-		let collection = pallet_nft::CollectionById::<T>::get(collection_id)?;
-
-		if
-			collection.sponsorship.confirmed() &&
-			// Can't sponsor fungible collection, this tx will be rejected
-			// as invalid
-			!matches!(collection.mode, CollectionMode::Fungible(_)) &&
-			data.len() <= collection.limits.sponsored_data_size as usize
-		{
-			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {
-				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-
-				if pallet_nft::VariableMetaDataBasket::<T>::get(collection_id, item_id)
-					.map(|last_block| block_number - last_block > rate_limit)
-					.unwrap_or(true) 
-				{
-					sponsor_metadata_changes = true;
-					pallet_nft::VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);
-				}
-			}
-		}
-
-		if !sponsor_metadata_changes {
-			None
-		} else {
-			collection.sponsorship.sponsor().cloned()
-		}
-
-	}
-
-	pub fn withdraw_contract_call(
-		who: &T::AccountId,
-		dest: &<T::Lookup as StaticLookup>::Source
-	) -> Option<T::AccountId> {
-
-		let called_contract: T::AccountId = T::Lookup::lookup((dest).clone()).unwrap_or(T::AccountId::default());
-
-		let owned_contract = pallet_nft::ContractOwner::<T>::get(called_contract.clone()).as_ref() == Some(who);
-		let white_list_enabled = pallet_nft::ContractWhiteListEnabled::<T>::contains_key(called_contract.clone());
-		  
-		// ???
-		if !owned_contract && white_list_enabled {
-		 	if !pallet_nft::ContractWhiteList::<T>::contains_key(called_contract.clone(), who) {
-				return Some(who.clone())
-		 		// return Err(InvalidTransaction::Call.into());
-		 	}
-		}
-
-		let mut sponsor_transfer = false;
-		if pallet_nft::ContractSponsoringRateLimit::<T>::contains_key(called_contract.clone()) {
-			let last_tx_block = pallet_nft::ContractSponsorBasket::<T>::get((&called_contract, &who));
-			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-			let rate_limit = pallet_nft::ContractSponsoringRateLimit::<T>::get(&called_contract);
-			let limit_time = last_tx_block + rate_limit;
-
-			if block_number >= limit_time {
-				pallet_nft::ContractSponsorBasket::<T>::insert((called_contract.clone(), who.clone()), block_number);
-				sponsor_transfer = true;
-			}
-		} else {
-			sponsor_transfer = false;
-		}
-	   
-		if sponsor_transfer {
-			if pallet_nft::ContractSelfSponsoring::<T>::contains_key(called_contract.clone()) {
-				if pallet_nft::ContractSelfSponsoring::<T>::get(called_contract.clone()) {
-					return Some(called_contract);
-				}
-			}
-		}
-
-		None
-	}
-
-	pub fn withdraw_contract_instantiate(
-		who: &T::AccountId,
-		code_hash: &CodeHash<T>,
-		salt: &[u8],
-	) -> Option<T::AccountId> where
-	T::AccountId: AsRef<[u8]>,
-	T::AccountId: UncheckedFrom<T::Hash>
-	{
-
-		let new_contract_address = <pallet_contracts::Pallet<T>>::contract_address(
-			&who,
-			code_hash,
-			salt,
-		);
-		pallet_nft::ContractOwner::<T>::insert(new_contract_address.clone(), who.clone());
-
-		None
+		T::SponsorshipHandler::get_sponsor(who, call)
 	}
 }
\ No newline at end of file
deletedpallets/nft-transaction-payment/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft-transaction-payment/src/tests.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-#[cfg(test)]
-mod tests {
-	use crate as pallet_inflation;
-
-	use frame_system;
-	use frame_support::{traits::{Currency}, parameter_types};
-	use frame_support::{traits::OnInitialize};
-	use sp_core::H256;
-	use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header};
-
-	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
-	type Block = frame_system::mocking::MockBlock<Test>;
-
-	const YEAR: u64 = 5_259_600;
-
-	parameter_types! {
-		pub const ExistentialDeposit: u64 = 1;
-		pub const MaxLocks: u32 = 50;
-	}
-	
-	impl pallet_balances::Config for Test {
-		type AccountStore = System;
-		type Balance = u64;
-		type DustRemoval = ();
-		type Event = ();
-		type ExistentialDeposit = ExistentialDeposit;
-		type WeightInfo = ();
-		type MaxLocks = MaxLocks;
-	}
-	
-	frame_support::construct_runtime!(
-		pub enum Test where
-			Block = Block,
-			NodeBlock = Block,
-			UncheckedExtrinsic = UncheckedExtrinsic,
-		{
-			Balances: pallet_balances::{Module, Call, Storage},
-			System: frame_system::{Module, Call, Config, Storage, Event<T>},
-			Inflation: pallet_inflation::{Module, Call, Storage},
-		}
-	);
-
-	parameter_types! {
-		pub const BlockHashCount: u64 = 250;
-		pub BlockWeights: frame_system::limits::BlockWeights =
-			frame_system::limits::BlockWeights::simple_max(1024);
-		pub const SS58Prefix: u8 = 42;
-	}
-
-	impl frame_system::Config for Test {
-		type BaseCallFilter = ();
-		type BlockWeights = ();
-		type BlockLength = ();
-		type DbWeight = ();
-		type Origin = Origin;
-		type Call = Call;
-		type Index = u64;
-		type BlockNumber = u64;
-		type Hash = H256;
-		type Hashing = BlakeTwo256;
-		type AccountId = u64;
-		type Lookup = IdentityLookup<Self::AccountId>;
-		type Header = Header;
-		type Event = ();
-		type BlockHashCount = BlockHashCount;
-		type Version = ();
-		type PalletInfo = PalletInfo;
-		type AccountData = pallet_balances::AccountData<u64>;
-		type OnNewAccount = ();
-		type OnKilledAccount = ();
-		type SystemWeightInfo = ();
-		type SS58Prefix = SS58Prefix;
-	}
-
-	parameter_types! {
-		pub TreasuryAccountId: u64 = 1234;
-		pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
-	}
-		
-	impl pallet_inflation::Config for Test {
-		type Currency = Balances;
-		type TreasuryAccountId = TreasuryAccountId;
-		type InflationBlockInterval = InflationBlockInterval;
-	}
-
-	// Build genesis storage according to the mock runtime.
-	pub fn new_test_ext() -> sp_io::TestExternalities {
-		frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into()
-	}
-
-	#[test]
-	fn inflation_works() {
-		new_test_ext().execute_with(|| {
-			// Total issuance = 1_000_000_000
-			let initial_issuance: u64 = 1_000_000_000;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-
-			// BlockInflation should be set after 1st block and 
-			// first inflation deposit should be equal to BlockInflation
-			Inflation::on_initialize(1);
-			assert!(Inflation::block_inflation() > 0);
-			assert_eq!(Balances::free_balance(1234) - initial_issuance, Inflation::block_inflation());
-		});
-	}
-
-	#[test]
-	fn inflation_second_deposit() {
-		new_test_ext().execute_with(|| {
-			// Total issuance = 1_000_000_000
-			let initial_issuance: u64 = 1_000_000_000;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-			Inflation::on_initialize(1);
-
-			// Next inflation deposit happens when block is multiple of InflationBlockInterval
-			let mut block: u32 = 2;
-			let balance_before: u64 = Balances::free_balance(1234);
-			while block % InflationBlockInterval::get() != 0 {
-				Inflation::on_initialize(block as u64);
-				block += 1;
-			}
-			let balance_just_before: u64 = Balances::free_balance(1234);
-			assert_eq!(balance_before, balance_just_before);
-
-			// The block with inflation
-			Inflation::on_initialize(block as u64);
-			let balance_after: u64 = Balances::free_balance(1234);
-			assert_eq!(balance_after - balance_just_before, Inflation::block_inflation());
-		});
-	}
-
-	#[test]
-	fn inflation_in_1_year() {
-		new_test_ext().execute_with(|| {
-			// Total issuance = 1_000_000_000
-			let initial_issuance: u64 = 1_000_000_000;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-			Inflation::on_initialize(1);
-			let block_inflation_year_0 = Inflation::block_inflation();
-
-			Inflation::on_initialize(YEAR);
-			let block_inflation_year_1 = Inflation::block_inflation();
-
-			// Assert that year 1 inflation is less than year 0
-			assert!(block_inflation_year_0 > block_inflation_year_1);
-		});
-	}
-
-	#[test]
-	fn inflation_in_1_to_9_years() {
-		new_test_ext().execute_with(|| {
-			// Total issuance = 1_000_000_000
-			let initial_issuance: u64 = 1_000_000_000;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-			Inflation::on_initialize(1);
-
-			for year in 1..=9 {
-				let block_inflation_year_before = Inflation::block_inflation();
-				Inflation::on_initialize(YEAR * year);
-				let block_inflation_year_after = Inflation::block_inflation();
-
-				// Assert that next year inflation is less than previous year inflation
-				assert!(block_inflation_year_before > block_inflation_year_after);
-			}
-
-		});
-	}
-
-	#[test]
-	fn inflation_after_year_10_is_flat() {
-		new_test_ext().execute_with(|| {
-			// Total issuance = 1_000_000_000
-			let initial_issuance: u64 = 1_000_000_000;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-			Inflation::on_initialize(YEAR * 9);
-
-			for year in 10..=20 {
-				let block_inflation_year_before = Inflation::block_inflation();
-				Inflation::on_initialize(YEAR * year);
-				let block_inflation_year_after = Inflation::block_inflation();
-
-				// Assert that next year inflation is equal to previous year inflation
-				assert_eq!(block_inflation_year_before, block_inflation_year_after);
-			}
-		});
-	}
-
-	#[test]
-	fn inflation_rate_by_year() {
-		new_test_ext().execute_with(|| {
-			let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;
-
-			// Inflation starts at 10% and does down by 2/3% every year until year 9 (included), 
-			// then it is flat.
-			let payout_by_year: [u64; 11] = [
-				1000,
-				933,
-				867,
-				800,
-				733,
-				667,
-				600,
-				533,
-				467,
-				400,
-				400
-			];
-
-			// For accuracy total issuance = payout0 * payouts * 10;
-			let initial_issuance: u64 = payout_by_year[0] * payouts * 10;
-			let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
-			assert_eq!(Balances::free_balance(1234), initial_issuance);
-
-			for year in 0..=10 {
-				// Year first block
-				Inflation::on_initialize(year*YEAR);
-				let mut actual_payout = Inflation::block_inflation();
-				assert_eq!(actual_payout, payout_by_year[year as usize]);
-
-				// Year second block
-				Inflation::on_initialize(year*YEAR+1);
-				actual_payout = Inflation::block_inflation();
-				assert_eq!(actual_payout, payout_by_year[year as usize]);
-
-				// Year middle block
-				Inflation::on_initialize(year*YEAR + YEAR/2);
-				actual_payout = Inflation::block_inflation();
-				assert_eq!(actual_payout, payout_by_year[year as usize]);
-
-				// Year last block
-				Inflation::on_initialize((year + 1)*YEAR-1);
-				actual_payout = Inflation::block_inflation();
-				assert_eq!(actual_payout, payout_by_year[year as usize]);
-			}
-		});
-	}
-}
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -30,6 +30,7 @@
     'pallet-transaction-payment/std',
     'fp-evm/std',
     'nft-data-structs/std',
+    'up-sponsorship/std',
     'sp-std/std',
     'sp-api/std',
     'sp-runtime/std',
@@ -135,9 +136,14 @@
 
 [dependencies.nft-data-structs]
 default-features = false
-path = '../../primitives'
+path = '../../primitives/nft'
 version = '0.9.0'
 
+[dependencies.up-sponsorship]
+default-features = false
+path = '../../primitives/sponsorship'
+version = '0.1.0'
+
 
 [dependencies]
 ethereum-tx-sign = { version = "3.0.4", optional = true }
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -50,6 +50,8 @@
 
 mod default_weights;
 mod eth;
+mod sponsorship;
+pub use sponsorship::NftSponsorshipHandler;
 
 pub use eth::NftErcSupport;
 pub use eth::account::*;
@@ -343,21 +345,6 @@
         /// Variable metadata sponsoring
         /// Collection id (controlled?2), token id (controlled?2)
         pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
-      
-        //#region Contract Sponsorship and Ownership
-        /// Contract address (real)
-        pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => Option<T::AccountId>;
-        /// Contract address (real)
-        pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
-        /// (Contract address(real), caller (real))
-        pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;
-        /// Contract address (real)
-        pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;
-        /// Contract address (real)
-        pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 
-        /// Contract address (real) => Whitelisted user (controlled?3)
-        pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool; 
-        //#endregion
     }
     add_extra_genesis {
         build(|config: &GenesisConfig<T>| {
@@ -1233,161 +1220,9 @@
             ensure_root(origin)?;
 
             <ChainLimit>::put(limits);
-            Ok(())
-        }
-
-        /// Enable smart contract self-sponsoring.
-        /// 
-        /// # Permissions
-        /// 
-        /// * Contract Owner
-        /// 
-        /// # Arguments
-        /// 
-        /// * contract address
-        /// * enable flag
-        /// 
-        #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]
-        #[transactional]
-        pub fn enable_contract_sponsoring(
-            origin,
-            contract_address: T::AccountId,
-            enable: bool
-        ) -> DispatchResult {
-
-            let sender = ensure_signed(origin)?;
-
-            #[cfg(feature = "runtime-benchmarks")]
-            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
-
-            Self::ensure_contract_owned(sender, &contract_address)?;
-
-            <ContractSelfSponsoring<T>>::insert(contract_address, enable);
-            Ok(())
-        }
-
-        /// Set the rate limit for contract sponsoring to specified number of blocks.
-        /// 
-        /// If not set (has the default value of 0 blocks), the sponsoring will be disabled. 
-        /// If set to the number B (for blocks), the transactions will be sponsored with a rate 
-        /// limit of B, i.e. fees for every transaction sent to this smart contract will be paid 
-        /// from contract endowment if there are at least B blocks between such transactions. 
-        /// Nonetheless, if transactions are sent more frequently, the fees are paid by the sender.
-        /// 
-        /// # Permissions
-        /// 
-        /// * Contract Owner
-        /// 
-        /// # Arguments
-        /// 
-        /// -`contract_address`: Address of the contract to sponsor
-        /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed
-        /// 
-        #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]
-        #[transactional]
-        pub fn set_contract_sponsoring_rate_limit(
-            origin,
-            contract_address: T::AccountId,
-            rate_limit: T::BlockNumber
-        ) -> DispatchResult {
-            let sender = ensure_signed(origin)?;
-
-            #[cfg(feature = "runtime-benchmarks")]
-            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
-
-            Self::ensure_contract_owned(sender, &contract_address)?;
-            <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);
             Ok(())
         }
 
-        /// Enable the white list for a contract. Only addresses added to the white list with addToContractWhiteList will be able to call this smart contract.
-        /// 
-        /// # Permissions
-        /// 
-        /// * Address that deployed smart contract.
-        /// 
-        /// # Arguments
-        /// 
-        /// -`contract_address`: Address of the contract.
-        /// 
-        /// - `enable`: .  
-        #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]
-        #[transactional]
-        pub fn toggle_contract_white_list(
-            origin,
-            contract_address: T::AccountId,
-            enable: bool
-        ) -> DispatchResult {
-            let sender = ensure_signed(origin)?;
-
-            #[cfg(feature = "runtime-benchmarks")]
-            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
-
-            Self::ensure_contract_owned(sender, &contract_address)?;
-            if enable {
-                <ContractWhiteListEnabled<T>>::insert(contract_address, true);
-            } else {
-                <ContractWhiteListEnabled<T>>::remove(contract_address);
-            }
-            Ok(())
-        }
-        
-        /// Add an address to smart contract white list.
-        /// 
-        /// # Permissions
-        /// 
-        /// * Address that deployed smart contract.
-        /// 
-        /// # Arguments
-        /// 
-        /// -`contract_address`: Address of the contract.
-        ///
-        /// -`account_address`: Address to add.
-        #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]
-        #[transactional]
-        pub fn add_to_contract_white_list(
-            origin,
-            contract_address: T::AccountId,
-            account_address: T::AccountId
-        ) -> DispatchResult {
-            let sender = ensure_signed(origin)?;
-
-            #[cfg(feature = "runtime-benchmarks")]
-            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
-            
-            Self::ensure_contract_owned(sender, &contract_address)?;      
-            <ContractWhiteList<T>>::insert(contract_address, account_address, true);
-            Ok(())
-        }
-
-        /// Remove an address from smart contract white list.
-        /// 
-        /// # Permissions
-        /// 
-        /// * Address that deployed smart contract.
-        /// 
-        /// # Arguments
-        /// 
-        /// -`contract_address`: Address of the contract.
-        ///
-        /// -`account_address`: Address to remove.
-        #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]
-        #[transactional]
-        pub fn remove_from_contract_white_list(
-            origin,
-            contract_address: T::AccountId,
-            account_address: T::AccountId
-        ) -> DispatchResult {
-            let sender = ensure_signed(origin)?;
-
-            #[cfg(feature = "runtime-benchmarks")]
-            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
-
-            Self::ensure_contract_owned(sender, &contract_address)?;
-            <ContractWhiteList<T>>::remove(contract_address, account_address);
-            Ok(())
-        }
-
         #[weight = <T as Config>::WeightInfo::set_collection_limits()]
         #[transactional]
         pub fn set_collection_limits(
@@ -2399,12 +2234,6 @@
     ) -> DispatchResult {
         Self::remove_token_index(collection_id, item_index, old_owner)?;
         Self::add_token_index(collection_id, item_index, new_owner)?;
-
-        Ok(())
-    }
-    
-    fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {
-        ensure!(<ContractOwner<T>>::get(contract) == Some(account), Error::<T>::NoPermission);
 
         Ok(())
     }
addedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/nft/src/sponsorship.rs
@@ -0,0 +1,203 @@
+use crate::{Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit, CreateItemData, CollectionMode};
+use core::marker::PhantomData;
+use up_sponsorship::SponsorshipHandler;
+use frame_support::{
+	traits::IsSubType,
+	storage::{StorageMap, StorageDoubleMap, StorageValue},
+};
+use nft_data_structs::{TokenId, CollectionId};
+use alloc::vec::Vec;
+
+pub struct NftSponsorshipHandler<T>(PhantomData<T>);
+impl<T: Config> NftSponsorshipHandler<T> {
+	pub fn withdraw_create_item(
+		who: &T::AccountId,
+		collection_id: &CollectionId,
+		_properties: &CreateItemData,
+	) -> Option<T::AccountId> {
+	
+		let collection = CollectionById::<T>::get(collection_id)?;
+
+		// sponsor timeout
+		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+
+		let limit = collection.limits.sponsor_transfer_timeout;
+		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {
+			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));
+			let limit_time = last_tx_block + limit.into();
+			if block_number <= limit_time {
+				return None;
+			}
+		}
+		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);
+
+		// check free create limit
+		if collection.limits.sponsored_data_size >= (_properties.len() as u32) {
+			collection.sponsorship.sponsor()
+				.cloned()
+		} else {
+			None
+		}
+	}
+
+	pub fn withdraw_transfer(
+		who: &T::AccountId,
+		collection_id: &CollectionId,
+		item_id: &TokenId,
+	) -> Option<T::AccountId> {
+
+		let collection = CollectionById::<T>::get(collection_id)?;
+		let limits = ChainLimit::get();
+
+		let mut sponsor_transfer = false;
+		if collection.sponsorship.confirmed() {
+
+			let collection_limits = collection.limits.clone();
+			let collection_mode = collection.mode.clone();
+
+			// sponsor timeout
+			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+			sponsor_transfer = match collection_mode {
+				CollectionMode::NFT => {
+
+					// get correct limit
+					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+						collection_limits.sponsor_transfer_timeout
+					} else {
+						limits.nft_sponsor_transfer_timeout
+					};
+
+					let mut sponsored = true;
+					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {
+						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);
+						let limit_time = last_tx_block + limit.into();
+						if block_number <= limit_time {
+							sponsored = false;
+						}
+					}
+					if sponsored {
+						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);
+					}
+
+					sponsored
+				}
+				CollectionMode::Fungible(_) => {
+
+					// get correct limit
+					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+						collection_limits.sponsor_transfer_timeout
+					} else {
+						limits.fungible_sponsor_transfer_timeout
+					};
+
+					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+					let mut sponsored = true;
+					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {
+						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);
+						let limit_time = last_tx_block + limit.into();
+						if block_number <= limit_time {
+							sponsored = false;
+						}
+					}
+					if sponsored {
+						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);
+					}
+
+					sponsored
+				}
+				CollectionMode::ReFungible => {
+
+					// get correct limit
+					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+						collection_limits.sponsor_transfer_timeout
+					} else {
+						limits.refungible_sponsor_transfer_timeout
+					};
+
+					let mut sponsored = true;
+					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {
+						let last_tx_block = ReFungibleTransferBasket::<T>::get(collection_id, item_id);
+						let limit_time = last_tx_block + limit.into();
+						if block_number <= limit_time {
+							sponsored = false;
+						}
+					}
+					if sponsored {
+						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);
+					}
+
+					sponsored
+				}
+				_ => {
+					false
+				},
+			};
+		}
+
+		if !sponsor_transfer {
+			None
+		} else {
+			collection.sponsorship.sponsor()
+				.cloned()
+		}
+	}
+	
+	pub fn withdraw_set_variable_meta_data(
+		collection_id: &CollectionId,
+		item_id: &TokenId,
+		data: &Vec<u8>,
+	) -> Option<T::AccountId> {
+
+		let mut sponsor_metadata_changes = false;
+
+		let collection = CollectionById::<T>::get(collection_id)?;
+
+		if
+			collection.sponsorship.confirmed() &&
+			// Can't sponsor fungible collection, this tx will be rejected
+			// as invalid
+			!matches!(collection.mode, CollectionMode::Fungible(_)) &&
+			data.len() <= collection.limits.sponsored_data_size as usize
+		{
+			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {
+				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+
+				if VariableMetaDataBasket::<T>::get(collection_id, item_id)
+					.map(|last_block| block_number - last_block > rate_limit)
+					.unwrap_or(true) 
+				{
+					sponsor_metadata_changes = true;
+					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);
+				}
+			}
+		}
+
+		if !sponsor_metadata_changes {
+			None
+		} else {
+			collection.sponsorship.sponsor().cloned()
+		}
+
+	}
+}
+
+impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>
+where 
+    T: Config,
+    C: IsSubType<Call<T>>
+{
+    fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {
+        match IsSubType::<Call<T>>::is_sub_type(call)? {
+            Call::create_item(collection_id, _owner, _properties) => {
+                Self::withdraw_create_item(who, collection_id, &_properties)
+            },
+            Call::transfer(_new_owner, collection_id, item_id, _value) => {
+                Self::withdraw_transfer(who, collection_id, item_id)
+            },
+            Call::set_variable_meta_data(collection_id, item_id, data) => {
+                Self::withdraw_set_variable_meta_data(collection_id, item_id, &data)
+			},
+			_ => None,
+        }
+    }
+}
\ No newline at end of file
modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -14,15 +14,12 @@
 codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
 frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-benchmarking = { default-features = false, version = '3.0.0', optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 
-pallet-nft-transaction-payment = { default-features = false, path = "../nft-transaction-payment" }
-pallet-nft = { default-features = false, path = "../nft" }
-nft-data-structs = { path = '../../primitives', default-features = false }
+up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
 log = { version = "0.4.14", default-features = false }
 
 [dev-dependencies]
@@ -37,10 +34,7 @@
 	"frame-benchmarking/std",
 	"frame-support/std",
 	"frame-system/std",
-	"pallet-nft-transaction-payment/std",
-	"pallet-nft/std",
-	"pallet-contracts/std",
-	"nft-data-structs/std",
+	"up-sponsorship/std",
 	"sp-io/std",
 	"sp-std/std",
 	"log/std",
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -64,10 +64,8 @@
 	weights::{GetDispatchInfo, Weight},
 };
 use frame_system::{self as system, ensure_signed};
-use pallet_nft::*;
-// use pallet_nft_transaction_payment::{self as nft_transaction_payment};
-use nft_data_structs::*;
 pub use weights::WeightInfo;
+use up_sponsorship::SponsorshipHandler;
 
 /// Our pallet's configuration trait. All our types and constants go in here. If the
 /// pallet is dependent on specific other pallets, then their configuration traits
@@ -103,7 +101,7 @@
 	type MaxScheduledPerBlock: Get<u32>;
 
 	/// Sponsoring function
-	type Sponsoring: SponsoringResolve<Self::AccountId, <Self as Config>::Call>;
+	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
 
 	/// Weight information for extrinsics in this pallet.
 	type WeightInfo: WeightInfo;
@@ -405,8 +403,7 @@
 							s.origin.clone()
 						).into();
 						let sender = ensure_signed(origin).unwrap_or(T::AccountId::default());
-						let who_will_pay = T::Sponsoring::resolve(&sender, &s.call.clone()).unwrap_or(
-							sender);
+						let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);
 						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
 						let r = s.call.clone().dispatch(sponsor.into());
 						let maybe_id = s.maybe_id.clone();
deletedprimitives/Cargo.tomldiffbeforeafterboth
--- a/primitives/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[package]
-name = "nft-data-structs"
-authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
-description = "Nft data structs definitions"
-edition = "2018"
-license = 'GPL-3.0'
-homepage = "https://substrate.dev"
-repository = 'https://github.com/clover-network/clover'
-version = '0.9.0'
-
-[dependencies]
-codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ['derive'] }
-serde = { version = "1.0.119", features = ['derive'], default-features = false }
-frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-sp-core = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-sp-runtime = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-
-[features]
-default = ["std"]
-std = [
-  "serde/std",
-  "codec/std",
-  "frame-system/std",
-  "frame-support/std",
-  "sp-runtime/std",
-  "sp-core/std",
-  "pallet-contracts/std",
-]
\ No newline at end of file
addedprimitives/nft/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/nft/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "nft-data-structs"
+authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
+description = "Nft data structs definitions"
+edition = "2018"
+license = 'GPL-3.0'
+homepage = "https://substrate.dev"
+repository = 'https://github.com/clover-network/clover'
+version = '0.9.0'
+
+[dependencies]
+codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ['derive'] }
+serde = { version = "1.0.119", features = ['derive'], default-features = false }
+frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+sp-core = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+sp-runtime = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
+
+[features]
+default = ["std"]
+std = [
+  "serde/std",
+  "codec/std",
+  "frame-system/std",
+  "frame-support/std",
+  "sp-runtime/std",
+  "sp-core/std",
+  "pallet-contracts/std",
+]
\ No newline at end of file
addedprimitives/nft/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/nft/src/lib.rs
@@ -0,0 +1,285 @@
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+pub use serde::{Serialize, Deserialize};
+
+use frame_system;
+use sp_runtime::sp_std::prelude::Vec;
+use codec::{Decode, Encode};
+pub use frame_support::{
+    construct_runtime, decl_event, decl_module, decl_storage, decl_error,
+    dispatch::DispatchResult,
+    ensure, fail, parameter_types,
+    traits::{
+        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
+        Randomness, IsSubType, WithdrawReasons,
+    },
+    weights::{
+        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
+        WeightToFeePolynomial, DispatchClass,
+    },
+    StorageValue,
+    transactional,
+};
+
+pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
+pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
+pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
+pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;
+
+pub type CollectionId = u32;
+pub type TokenId = u32;
+pub type DecimalPoints = u8;
+
+#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum CollectionMode {
+    Invalid,
+    NFT,
+    // decimal points
+    Fungible(DecimalPoints),
+    ReFungible,
+}
+
+impl Default for CollectionMode {
+    fn default() -> Self {
+        Self::Invalid
+    }
+}
+
+impl Into<u8> for CollectionMode {
+    fn into(self) -> u8 {
+        match self {
+            CollectionMode::Invalid => 0,
+            CollectionMode::NFT => 1,
+            CollectionMode::Fungible(_) => 2,
+            CollectionMode::ReFungible => 3,
+        }
+    }
+}
+
+pub trait SponsoringResolve<AccountId, Call> {
+    fn resolve(
+        who: &AccountId,
+		call: &Call) -> Option<AccountId>;
+}
+
+#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum AccessMode {
+    Normal,
+    WhiteList,
+}
+impl Default for AccessMode {
+    fn default() -> Self {
+        Self::Normal
+    }
+}
+
+#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SchemaVersion {
+    ImageURL,
+    Unique,
+}
+impl Default for SchemaVersion {
+    fn default() -> Self {
+        Self::ImageURL
+    }
+}
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct Ownership<AccountId> {
+    pub owner: AccountId,
+    pub fraction: u128,
+}
+
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SponsorshipState<AccountId> {
+    /// The fees are applied to the transaction sender
+    Disabled,
+    Unconfirmed(AccountId),
+    /// Transactions are sponsored by specified account
+    Confirmed(AccountId),
+}
+
+impl<AccountId> SponsorshipState<AccountId> {
+    pub fn sponsor(&self) -> Option<&AccountId> {
+        match self {
+            Self::Confirmed(sponsor) => Some(sponsor),
+            _ => None,
+        }
+    }
+
+    pub fn pending_sponsor(&self) -> Option<&AccountId> {
+        match self {
+            Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
+            _ => None,
+        }
+    }
+
+    pub fn confirmed(&self) -> bool {
+        matches!(self, Self::Confirmed(_))
+    }
+}
+
+impl<T> Default for SponsorshipState<T> {
+    fn default() -> Self {
+        Self::Disabled
+    }
+}
+
+#[derive(Encode, Decode, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct Collection<T: frame_system::Config> {
+    pub owner: T::AccountId,
+    pub mode: CollectionMode,
+    pub access: AccessMode,
+    pub decimal_points: DecimalPoints,
+    pub name: Vec<u16>,        // 64 include null escape char
+    pub description: Vec<u16>, // 256 include null escape char
+    pub token_prefix: Vec<u8>, // 16 include null escape char
+    pub mint_mode: bool,
+    pub offchain_schema: Vec<u8>,
+    pub schema_version: SchemaVersion,
+    pub sponsorship: SponsorshipState<T::AccountId>,
+    pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 
+    pub variable_on_chain_schema: Vec<u8>, //
+    pub const_on_chain_schema: Vec<u8>, //
+}
+
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct NftItemType<AccountId> {
+    pub owner: AccountId,
+    pub const_data: Vec<u8>,
+    pub variable_data: Vec<u8>,
+}
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct FungibleItemType {
+    pub value: u128,
+}
+
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct ReFungibleItemType<AccountId> {
+    pub owner: Vec<Ownership<AccountId>>,
+    pub const_data: Vec<u8>,
+    pub variable_data: Vec<u8>,
+}
+
+
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct CollectionLimits<BlockNumber: Encode + Decode> {
+    pub account_token_ownership_limit: u32,
+    pub sponsored_data_size: u32,
+    /// None - setVariableMetadata is not sponsored
+    /// Some(v) - setVariableMetadata is sponsored 
+    ///           if there is v block between txs
+    pub sponsored_data_rate_limit: Option<BlockNumber>,
+    pub token_limit: u32,
+
+    // Timeouts for item types in passed blocks
+    pub sponsor_transfer_timeout: u32,
+    pub owner_can_transfer: bool,
+    pub owner_can_destroy: bool,
+}
+
+impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
+    fn default() -> Self {
+        Self { 
+            account_token_ownership_limit: 10_000_000, 
+            token_limit: u32::max_value(),
+            sponsored_data_size: u32::MAX, 
+            sponsored_data_rate_limit: None,
+            sponsor_transfer_timeout: 14400,
+            owner_can_transfer: true,
+            owner_can_destroy: true
+        }
+    }
+}
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct ChainLimits {
+    pub collection_numbers_limit: u32,
+    pub account_token_ownership_limit: u32,
+    pub collections_admins_limit: u64,
+    pub custom_data_limit: u32,
+
+    // Timeouts for item types in passed blocks
+    pub nft_sponsor_transfer_timeout: u32,
+    pub fungible_sponsor_transfer_timeout: u32,
+    pub refungible_sponsor_transfer_timeout: u32,
+
+    // Schema limits
+    pub offchain_schema_limit: u32,
+    pub variable_on_chain_schema_limit: u32,
+    pub const_on_chain_schema_limit: u32,
+}
+
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct CreateNftData {
+    pub const_data: Vec<u8>,
+    pub variable_data: Vec<u8>,
+}
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct CreateFungibleData {
+    pub value: u128,
+}
+
+#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct CreateReFungibleData {
+    pub const_data: Vec<u8>,
+    pub variable_data: Vec<u8>,
+    pub pieces: u128,
+}
+
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum CreateItemData {
+    NFT(CreateNftData),
+    Fungible(CreateFungibleData),
+    ReFungible(CreateReFungibleData),
+}
+
+impl CreateItemData {
+    pub fn len(&self) -> usize {
+        let len = match self {
+            CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),
+            CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),
+            _ => 0
+        };
+        
+        return len;
+    }
+}
+
+impl From<CreateNftData> for CreateItemData {
+    fn from(item: CreateNftData) -> Self {
+        CreateItemData::NFT(item)
+    }
+}
+
+impl From<CreateReFungibleData> for CreateItemData {
+    fn from(item: CreateReFungibleData) -> Self {
+        CreateItemData::ReFungible(item)
+    }
+}
+
+impl From<CreateFungibleData> for CreateItemData {
+    fn from(item: CreateFungibleData) -> Self {
+        CreateItemData::Fungible(item)
+    }
+}
addedprimitives/sponsorship/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/sponsorship/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "up-sponsorship"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+impl-trait-for-tuples = "0.2.1"
+
+[features]
+default = ["std"]
+std = []
\ No newline at end of file
addedprimitives/sponsorship/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/sponsorship/src/lib.rs
@@ -0,0 +1,42 @@
+#![no_std]
+
+pub trait SponsorshipHandler<AccountId, Call> {
+	fn get_sponsor(who: &AccountId, call: &Call) -> Option<AccountId>;
+}
+
+impl<A, C> SponsorshipHandler<A, C> for () {
+	fn get_sponsor(_who: &A, _call: &C) -> Option<A> {
+		None
+	}
+}
+
+macro_rules! impl_tuples {
+	($($ident:ident)+) => {
+		impl<AccountId, Call, $($ident),+> SponsorshipHandler<AccountId, Call> for ($($ident,)+)
+		where
+			$(
+				$ident: SponsorshipHandler<AccountId, Call>
+			),+
+		{
+			fn get_sponsor(who: &AccountId, call: &Call) -> Option<AccountId> {
+				$(
+					if let Some(account) = $ident::get_sponsor(who, call) {
+						return Some(account);
+					}
+				)+
+				None
+			}
+		}
+	}
+}
+
+impl_tuples! {A}
+impl_tuples! {A B}
+impl_tuples! {A B C}
+impl_tuples! {A B C D}
+impl_tuples! {A B C D E}
+impl_tuples! {A B C D E F}
+impl_tuples! {A B C D E F G}
+impl_tuples! {A B C D E F G H}
+impl_tuples! {A B C D E F G H I}
+impl_tuples! {A B C D E F G H I J}
deletedprimitives/src/lib.rsdiffbeforeafterboth
--- a/primitives/src/lib.rs
+++ /dev/null
@@ -1,285 +0,0 @@
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-pub use serde::{Serialize, Deserialize};
-
-use frame_system;
-use sp_runtime::sp_std::prelude::Vec;
-use codec::{Decode, Encode};
-pub use frame_support::{
-    construct_runtime, decl_event, decl_module, decl_storage, decl_error,
-    dispatch::DispatchResult,
-    ensure, fail, parameter_types,
-    traits::{
-        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
-        Randomness, IsSubType, WithdrawReasons,
-    },
-    weights::{
-        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
-        WeightToFeePolynomial, DispatchClass,
-    },
-    StorageValue,
-    transactional,
-};
-
-pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
-pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
-pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
-pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;
-
-pub type CollectionId = u32;
-pub type TokenId = u32;
-pub type DecimalPoints = u8;
-
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum CollectionMode {
-    Invalid,
-    NFT,
-    // decimal points
-    Fungible(DecimalPoints),
-    ReFungible,
-}
-
-impl Default for CollectionMode {
-    fn default() -> Self {
-        Self::Invalid
-    }
-}
-
-impl Into<u8> for CollectionMode {
-    fn into(self) -> u8 {
-        match self {
-            CollectionMode::Invalid => 0,
-            CollectionMode::NFT => 1,
-            CollectionMode::Fungible(_) => 2,
-            CollectionMode::ReFungible => 3,
-        }
-    }
-}
-
-pub trait SponsoringResolve<AccountId, Call> {
-    fn resolve(
-        who: &AccountId,
-		call: &Call) -> Option<AccountId>;
-}
-
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum AccessMode {
-    Normal,
-    WhiteList,
-}
-impl Default for AccessMode {
-    fn default() -> Self {
-        Self::Normal
-    }
-}
-
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum SchemaVersion {
-    ImageURL,
-    Unique,
-}
-impl Default for SchemaVersion {
-    fn default() -> Self {
-        Self::ImageURL
-    }
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct Ownership<AccountId> {
-    pub owner: AccountId,
-    pub fraction: u128,
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum SponsorshipState<AccountId> {
-    /// The fees are applied to the transaction sender
-    Disabled,
-    Unconfirmed(AccountId),
-    /// Transactions are sponsored by specified account
-    Confirmed(AccountId),
-}
-
-impl<AccountId> SponsorshipState<AccountId> {
-    pub fn sponsor(&self) -> Option<&AccountId> {
-        match self {
-            Self::Confirmed(sponsor) => Some(sponsor),
-            _ => None,
-        }
-    }
-
-    pub fn pending_sponsor(&self) -> Option<&AccountId> {
-        match self {
-            Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
-            _ => None,
-        }
-    }
-
-    pub fn confirmed(&self) -> bool {
-        matches!(self, Self::Confirmed(_))
-    }
-}
-
-impl<T> Default for SponsorshipState<T> {
-    fn default() -> Self {
-        Self::Disabled
-    }
-}
-
-#[derive(Encode, Decode, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct Collection<T: frame_system::Config> {
-    pub owner: T::AccountId,
-    pub mode: CollectionMode,
-    pub access: AccessMode,
-    pub decimal_points: DecimalPoints,
-    pub name: Vec<u16>,        // 64 include null escape char
-    pub description: Vec<u16>, // 256 include null escape char
-    pub token_prefix: Vec<u8>, // 16 include null escape char
-    pub mint_mode: bool,
-    pub offchain_schema: Vec<u8>,
-    pub schema_version: SchemaVersion,
-    pub sponsorship: SponsorshipState<T::AccountId>,
-    pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 
-    pub variable_on_chain_schema: Vec<u8>, //
-    pub const_on_chain_schema: Vec<u8>, //
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct NftItemType<AccountId> {
-    pub owner: AccountId,
-    pub const_data: Vec<u8>,
-    pub variable_data: Vec<u8>,
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct FungibleItemType {
-    pub value: u128,
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct ReFungibleItemType<AccountId> {
-    pub owner: Vec<Ownership<AccountId>>,
-    pub const_data: Vec<u8>,
-    pub variable_data: Vec<u8>,
-}
-
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CollectionLimits<BlockNumber: Encode + Decode> {
-    pub account_token_ownership_limit: u32,
-    pub sponsored_data_size: u32,
-    /// None - setVariableMetadata is not sponsored
-    /// Some(v) - setVariableMetadata is sponsored 
-    ///           if there is v block between txs
-    pub sponsored_data_rate_limit: Option<BlockNumber>,
-    pub token_limit: u32,
-
-    // Timeouts for item types in passed blocks
-    pub sponsor_transfer_timeout: u32,
-    pub owner_can_transfer: bool,
-    pub owner_can_destroy: bool,
-}
-
-impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
-    fn default() -> Self {
-        Self { 
-            account_token_ownership_limit: 10_000_000, 
-            token_limit: u32::max_value(),
-            sponsored_data_size: u32::MAX, 
-            sponsored_data_rate_limit: None,
-            sponsor_transfer_timeout: 14400,
-            owner_can_transfer: true,
-            owner_can_destroy: true
-        }
-    }
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct ChainLimits {
-    pub collection_numbers_limit: u32,
-    pub account_token_ownership_limit: u32,
-    pub collections_admins_limit: u64,
-    pub custom_data_limit: u32,
-
-    // Timeouts for item types in passed blocks
-    pub nft_sponsor_transfer_timeout: u32,
-    pub fungible_sponsor_transfer_timeout: u32,
-    pub refungible_sponsor_transfer_timeout: u32,
-
-    // Schema limits
-    pub offchain_schema_limit: u32,
-    pub variable_on_chain_schema_limit: u32,
-    pub const_on_chain_schema_limit: u32,
-}
-
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CreateNftData {
-    pub const_data: Vec<u8>,
-    pub variable_data: Vec<u8>,
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CreateFungibleData {
-    pub value: u128,
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CreateReFungibleData {
-    pub const_data: Vec<u8>,
-    pub variable_data: Vec<u8>,
-    pub pieces: u128,
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum CreateItemData {
-    NFT(CreateNftData),
-    Fungible(CreateFungibleData),
-    ReFungible(CreateReFungibleData),
-}
-
-impl CreateItemData {
-    pub fn len(&self) -> usize {
-        let len = match self {
-            CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),
-            CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),
-            _ => 0
-        };
-        
-        return len;
-    }
-}
-
-impl From<CreateNftData> for CreateItemData {
-    fn from(item: CreateNftData) -> Self {
-        CreateItemData::NFT(item)
-    }
-}
-
-impl From<CreateReFungibleData> for CreateItemData {
-    fn from(item: CreateReFungibleData) -> Self {
-        CreateItemData::ReFungible(item)
-    }
-}
-
-impl From<CreateFungibleData> for CreateItemData {
-    fn from(item: CreateFungibleData) -> Self {
-        CreateItemData::Fungible(item)
-    }
-}
\ No newline at end of file
modifiedruntime/Cargo.tomldiffbeforeafterboth
--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -46,6 +46,7 @@
     'pallet-contracts/std',
     'pallet-contracts-primitives/std',
     'pallet-contracts-rpc-runtime-api/std',
+    'pallet-contract-helpers/std',
     'pallet-randomness-collective-flip/std',
     'pallet-sudo/std',
     'pallet-timestamp/std',
@@ -372,8 +373,9 @@
 [dependencies]
 pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }
 pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }
-nft-data-structs = { path = '../primitives', default-features = false,  version = '0.9.0' }
+nft-data-structs = { path = '../primitives/nft', default-features = false,  version = '0.9.0' }
 pallet-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }
+pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }
 pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }
 
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use sp_api::impl_runtime_apis;17use sp_core::{ crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160 };18// #[cfg(any(feature = "std", test))]19// pub use sp_runtime::BuildStorage;2021use sp_runtime::{22    Permill, Perbill, Percent,23    create_runtime_str, generic, impl_opaque_keys,24    traits::{25        AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26		Verify, AccountIdConversion,27    },28    transaction_validity::{TransactionSource, TransactionValidity},29    ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo};38// A few exports that help ease life for downstream crates.39pub use pallet_balances::Call as BalancesCall;40pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};41pub use frame_support::{42    construct_runtime,43	match_type,44    dispatch::DispatchResult,45	PalletId,46    parameter_types,47    StorageValue,48	ConsensusEngineId,49    traits::{50        All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, Randomness, FindAuthor51    },52    weights::{53        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},54        DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,55        WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients56    },57};58use nft_data_structs::*;59use pallet_contracts::weights::WeightInfo;60// #[cfg(any(feature = "std", test))]61use frame_system::{62    self as system,63    EnsureRoot, EnsureSigned,64	limits::{BlockWeights, BlockLength},65};66use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73	traits::{ 74		Dispatchable,75	},76};77use pallet_contracts::chain_extension::UncheckedFrom;787980pub use pallet_timestamp::Call as TimestampCall;81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8283// Polkadot imports84use pallet_xcm::XcmPassthrough;85use polkadot_parachain::primitives::Sibling;86use xcm::v0::Xcm;87use xcm::v0::{BodyId, Junction::*, MultiAsset, MultiLocation, MultiLocation::*, NetworkId};88use xcm_builder::{89	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,90	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,91	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,92	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,93	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,94};95use xcm_executor::{Config, XcmExecutor};969798mod chain_extension;99use crate::chain_extension::{ NFTExtension, Imbalance };100101/// Re-export a nft pallet102/// TODO: Check this re-export. Is this safe and good style?103// extern crate pallet_nft;104// pub use pallet_nft::*;105106/// Reimport pallet inflation107// extern crate pallet_inflation;108// pub use pallet_inflation::*;109110/// An index to a block.111pub type BlockNumber = u32;112113/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.114pub type Signature = MultiSignature;115116/// Some way of identifying an account on the chain. We intentionally make it equivalent117/// to the public key of our transaction signing scheme.118pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;119120/// The type for looking up accounts. We don't expect more than 4 billion of them, but you121/// never know...122pub type AccountIndex = u32;123124/// Balance of an account.125pub type Balance = u128;126127/// Index of a transaction in the chain.128pub type Index = u32;129130/// A hash of some data used by the chain.131pub type Hash = sp_core::H256;132133/// Digest item type.134pub type DigestItem = generic::DigestItem<Hash>;135136mod nft_weights;137138/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know139/// the specifics of the runtime. They can then be made to be agnostic over specific formats140/// of data like extrinsics, allowing for them to continue syncing the network through upgrades141/// to even the core data structures.142pub mod opaque {143	use super::*;144145	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;146147    /// Opaque block type.148    pub type Block = generic::Block<Header, UncheckedExtrinsic>;149150    pub type SessionHandlers = ();151152	impl_opaque_keys! {153        pub struct SessionKeys {154			pub aura: Aura,155		}156    }157}158159/// This runtime version.160pub const VERSION: RuntimeVersion = RuntimeVersion {161	spec_name: create_runtime_str!("nft"),162	impl_name: create_runtime_str!("nft"),163	authoring_version: 1,164	spec_version: 3,165	impl_version: 1,166	apis: RUNTIME_API_VERSIONS,167	transaction_version: 1,168};169170pub const MILLISECS_PER_BLOCK: u64 = 12000;171172pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;173174// These time units are defined in number of blocks.175pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);176pub const HOURS: BlockNumber = MINUTES * 60;177pub const DAYS: BlockNumber = HOURS * 24;178179#[derive(codec::Encode, codec::Decode)]180pub enum XCMPMessage<XAccountId, XBalance> {181    /// Transfer tokens to the given account from the Parachain account.182    TransferToken(XAccountId, XBalance),183}184185/// The version information used to identify this runtime when compiled natively.186#[cfg(feature = "std")]187pub fn native_version() -> NativeVersion {188	NativeVersion {189		runtime_version: VERSION,190		can_author_with: Default::default(),191	}192}193194type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;195196pub struct DealWithFees;197impl OnUnbalanced<NegativeImbalance> for DealWithFees {198	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {199		if let Some(fees) = fees_then_tips.next() {200			// for fees, 100% to treasury201			let mut split = fees.ration(100, 0);202			if let Some(tips) = fees_then_tips.next() {203				// for tips, if any, 100% to treasury204				tips.ration_merge_into(100, 0, &mut split);205			}206			Treasury::on_unbalanced(split.0);207			// Author::on_unbalanced(split.1);208		}209	}210}211212/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.213/// This is used to limit the maximal weight of a single extrinsic.214const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);215/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used216/// by  Operational  extrinsics.217const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);218/// We allow for 2 seconds of compute with a 6 second average block time.219const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;220221parameter_types! {222	pub const BlockHashCount: BlockNumber = 2400;223	pub RuntimeBlockLength: BlockLength =224		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228		.base_block(BlockExecutionWeight::get())229		.for_class(DispatchClass::all(), |weights| {230			weights.base_extrinsic = ExtrinsicBaseWeight::get();231		})232		.for_class(DispatchClass::Normal, |weights| {233			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234		})235		.for_class(DispatchClass::Operational, |weights| {236			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237			// Operational transactions have some extra reserved space, so that they238			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239			weights.reserved = Some(240				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241			);242		})243		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244		.build_or_panic();245	pub const Version: RuntimeVersion = VERSION;246	pub const SS58Prefix: u8 = 42;247}248249250parameter_types! {251	pub const ChainId: u64 = 8888;252}253254impl pallet_evm::Config for Runtime {255	type BlockGasLimit = BlockGasLimit;256	type FeeCalculator = ();257	type GasWeightMapping = ();258	type CallOrigin = EnsureAddressTruncated;259	type WithdrawOrigin = EnsureAddressTruncated;260	type AddressMapping = HashedAddressMapping<Self::Hashing>;261	type Precompiles = ();262	type Currency = Balances;263	type Event = Event;264	type OnMethodCall = pallet_nft::NftErcSupport<Self>;265	type ChainId = ChainId;266	type Runner = pallet_evm::runner::stack::Runner<Self>;267	type OnChargeTransaction = ();268}269270pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);271impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>272{273	fn find_author<'a, I>(digests: I) -> Option<H160> where274		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>275	{276		if let Some(author_index) = F::find_author(digests) {277			let authority_id = Aura::authorities()[author_index as usize].clone();278			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));279		}280		None281	}282}283284parameter_types! {285	pub BlockGasLimit: U256 = U256::from(u32::max_value());286}287288impl pallet_ethereum::Config for Runtime {289	type Event = Event;290	type FindAuthor = EthereumFindAuthor<Aura>;291	type StateRoot = pallet_ethereum::IntermediateStateRoot;292	type EvmSubmitLog = pallet_evm::Pallet<Runtime>;293}294295impl system::Config for Runtime {296    /// The data to be stored in an account.297    type AccountData = pallet_balances::AccountData<Balance>;298    /// The identifier used to distinguish between accounts.299    type AccountId = AccountId;300    /// The basic call filter to use in dispatchable.301    type BaseCallFilter = ();302    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).303    type BlockHashCount = BlockHashCount;304    /// The maximum length of a block (in bytes).305	type BlockLength = RuntimeBlockLength;306    /// The index type for blocks.307    type BlockNumber = BlockNumber;308    /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.309	type BlockWeights = RuntimeBlockWeights;310    /// The aggregated dispatch type that is available for extrinsics.311    type Call = Call;312    /// The weight of database operations that the runtime can invoke.313    type DbWeight = RocksDbWeight;314    /// The ubiquitous event type.315    type Event = Event;316    /// The type for hashing blocks and tries.317    type Hash = Hash;318	/// The hashing algorithm used.319    type Hashing = BlakeTwo256;320    /// The header type.321    type Header = generic::Header<BlockNumber, BlakeTwo256>;322    /// The index type for storing how many extrinsics an account has signed.323    type Index = Index;324    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.325    type Lookup = AccountIdLookup<AccountId, ()>;326    /// What to do if an account is fully reaped from the system.327    type OnKilledAccount = ();328    /// What to do if a new account is created.329    type OnNewAccount = ();330    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;331    /// The ubiquitous origin type.332    type Origin = Origin;333 	/// This type is being generated by `construct_runtime!`.334    type PalletInfo = PalletInfo;335    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.336	type SS58Prefix = SS58Prefix;337	/// Weight information for the extrinsics of this pallet.338    type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;339    /// Version of the runtime.340    type Version = Version;341}342343parameter_types! {344	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;345}346347impl pallet_timestamp::Config for Runtime {348	/// A timestamp: milliseconds since the unix epoch.349	type Moment = u64;350	type OnTimestampSet = ();351	type MinimumPeriod = MinimumPeriod;352	type WeightInfo = ();353}354355parameter_types! {356	// pub const ExistentialDeposit: u128 = 500;357	pub const ExistentialDeposit: u128 = 0;358	pub const MaxLocks: u32 = 50;359}360361impl pallet_balances::Config for Runtime {362	type MaxLocks = MaxLocks;363	/// The type for recording an account's balance.364	type Balance = Balance;365	/// The ubiquitous event type.366	type Event = Event;367	type DustRemoval = Treasury;368	type ExistentialDeposit = ExistentialDeposit;369	type AccountStore = System;370	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;371}372373pub const MICROUNIQUE: Balance = 1_000_000_000;374pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;375pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;376pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;377378pub const fn deposit(items: u32, bytes: u32) -> Balance {379	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE380}381382parameter_types! {383	pub TombstoneDeposit: Balance = deposit(384		1,385		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,386	);387	pub DepositPerContract: Balance = TombstoneDeposit::get();388	pub const DepositPerStorageByte: Balance = deposit(0, 1);389	pub const DepositPerStorageItem: Balance = deposit(1, 0);390	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);391	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;392	pub const SignedClaimHandicap: u32 = 2;393	pub const MaxDepth: u32 = 32;394	pub const MaxValueSize: u32 = 16 * 1024;395	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb396	// The lazy deletion runs inside on_initialize.397	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *398		RuntimeBlockWeights::get().max_block;399	// The weight needed for decoding the queue should be less or equal than a fifth400	// of the overall weight dedicated to the lazy deletion.401	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (402			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -403			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)404		)) / 5) as u32;405	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();406}407408impl pallet_contracts::Config for Runtime {409	type Time = Timestamp;410	type Randomness = RandomnessCollectiveFlip;411	type Currency = Balances;412	type Event = Event;413	type RentPayment = ();414	type SignedClaimHandicap = SignedClaimHandicap;415	type TombstoneDeposit = TombstoneDeposit;416	type DepositPerContract = DepositPerContract;417	type DepositPerStorageByte = DepositPerStorageByte;418	type DepositPerStorageItem = DepositPerStorageItem;419	type RentFraction = RentFraction;420	type SurchargeReward = SurchargeReward;421	// type MaxDepth = MaxDepth;422	// type MaxValueSize = MaxValueSize;423	type WeightPrice = pallet_transaction_payment::Module<Self>;424	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;425	type ChainExtension = NFTExtension;426	type DeletionQueueDepth = DeletionQueueDepth;427	type DeletionWeightLimit = DeletionWeightLimit;428	// type MaxCodeSize = MaxCodeSize;429	type Schedule = Schedule;430	type CallStack = [pallet_contracts::Frame<Self>; 31];431}432433parameter_types! {434	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer435}436437/// Linear implementor of `WeightToFeePolynomial`438pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);439440impl<T> WeightToFeePolynomial for LinearFee<T> where441	T: BaseArithmetic + From<u32> + Copy + Unsigned442{443	type Balance = T;444445	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {446		smallvec!(WeightToFeeCoefficient {447			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer448			coeff_frac: Perbill::zero(),449			negative: false,450			degree: 1,451		})452	}453}454455impl pallet_transaction_payment::Config for Runtime {456	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;457	type TransactionByteFee = TransactionByteFee;458	type WeightToFee = LinearFee<Balance>;459	type FeeMultiplierUpdate = ();460}461462parameter_types! {463	pub const ProposalBond: Permill = Permill::from_percent(5);464	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;465	pub const SpendPeriod: BlockNumber = 5 * MINUTES;466	pub const Burn: Permill = Permill::from_percent(0);467	pub const TipCountdown: BlockNumber = 1 * DAYS;468	pub const TipFindersFee: Percent = Percent::from_percent(20);469	pub const TipReportDepositBase: Balance = 1 * UNIQUE;470	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;471	pub const BountyDepositBase: Balance = 1 * UNIQUE;472	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;473	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");474	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;475	pub const MaximumReasonLength: u32 = 16384;476	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);477	pub const BountyValueMinimum: Balance = 5 * UNIQUE;478	pub const MaxApprovals: u32 = 100;479}480481impl pallet_treasury::Config for Runtime {482	type PalletId = TreasuryModuleId;483	type Currency = Balances;484	type ApproveOrigin = EnsureRoot<AccountId>;485	type RejectOrigin = EnsureRoot<AccountId>;486	type Event = Event;487	type OnSlash = ();488	type ProposalBond = ProposalBond;489	type ProposalBondMinimum = ProposalBondMinimum;490	type SpendPeriod = SpendPeriod;491	type Burn = Burn;492	type BurnDestination = ();493	type SpendFunds = ();494	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;495	type MaxApprovals = MaxApprovals;496}497498impl pallet_sudo::Config for Runtime {499	type Event = Event;500	type Call = Call;501}502503parameter_types! {504	pub const MinVestedTransfer: Balance = 10 * UNIQUE;505}506507impl pallet_vesting::Config for Runtime {508	type Event = Event;509	type Currency = Balances;510	type BlockNumberToBalance = ConvertInto;511	type MinVestedTransfer = MinVestedTransfer;512	type WeightInfo = ();513}514515parameter_types! {516	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;517	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;518}519520impl cumulus_pallet_parachain_system::Config for Runtime {521	type Event = Event;522	type OnValidationData = ();523	type SelfParaId = parachain_info::Pallet<Runtime>;524	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<525	// 	MaxDownwardMessageWeight,526	// 	XcmExecutor<XcmConfig>,527	// 	Call,528	// >;529	type OutboundXcmpMessageSource = XcmpQueue;530	type DmpMessageHandler = DmpQueue;531	type ReservedDmpWeight = ReservedDmpWeight;532	type ReservedXcmpWeight = ReservedXcmpWeight;533	type XcmpMessageHandler = XcmpQueue;534}535536impl parachain_info::Config for Runtime {}537538impl cumulus_pallet_aura_ext::Config for Runtime {}539540parameter_types! {541	pub const RelayLocation: MultiLocation = X1(Parent);542	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;543	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();544	pub Ancestry: MultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));545}546547/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used548/// when determining ownership of accounts for asset transacting and when attempting to use XCM549/// `Transact` in order to determine the dispatch Origin.550pub type LocationToAccountId = (551	// The parent (Relay-chain) origin converts to the default `AccountId`.552	ParentIsDefault<AccountId>,553	// Sibling parachain origins convert to AccountId via the `ParaId::into`.554	SiblingParachainConvertsVia<Sibling, AccountId>,555	// Straight up local `AccountId32` origins just alias directly to `AccountId`.556	AccountId32Aliases<RelayNetwork, AccountId>,557);558559/// Means for transacting assets on this chain.560pub type LocalAssetTransactor = CurrencyAdapter<561	// Use this currency:562	Balances,563	// Use this currency when it is a fungible asset matching the given location or name:564	IsConcrete<RelayLocation>,565	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:566	LocationToAccountId,567	// Our chain's account ID type (we can't get away without mentioning it explicitly):568	AccountId,569	// We don't track any teleports.570	(),571>;572573/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,574/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can575/// biases the kind of local `Origin` it will become.576pub type XcmOriginToTransactDispatchOrigin = (577	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location578	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for579	// foreign chains who want to have a local sovereign account on this chain which they control.580	SovereignSignedViaLocation<LocationToAccountId, Origin>,581	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when582	// recognised.583	RelayChainAsNative<RelayOrigin, Origin>,584	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when585	// recognised.586	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,587	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a588	// transaction from the Root origin.589	ParentAsSuperuser<Origin>,590	// Native signed account converter; this just converts an `AccountId32` origin into a normal591	// `Origin::Signed` origin of the same 32-byte value.592	SignedAccountId32AsNative<RelayNetwork, Origin>,593	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.594	XcmPassthrough<Origin>,595);596597parameter_types! {598	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.599	pub UnitWeightCost: Weight = 1_000_000;600	// 1200 UNIQUEs buy 1 second of weight.601	pub const WeightPrice: (MultiLocation, u128) = (X1(Parent), 1_200 * UNIQUE);602}603604match_type! {605	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {606		X1(Parent) | X2(Parent, Plurality { id: BodyId::Unit, .. })607	};608}609610pub type Barrier = (611	TakeWeightCredit,612	AllowTopLevelPaidExecutionFrom<All<MultiLocation>>,613	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,614	// ^^^ Parent & its unit plurality gets free execution615);616617pub struct XcmConfig;618impl Config for XcmConfig {619	type Call = Call;620	type XcmSender = XcmRouter;621	// How to withdraw and deposit an asset.622	type AssetTransactor = LocalAssetTransactor;623	type OriginConverter = XcmOriginToTransactDispatchOrigin;624	type IsReserve = NativeAsset;625	type IsTeleporter = NativeAsset;	// <- should be enough to allow teleportation of ROC626	type LocationInverter = LocationInverter<Ancestry>;627	type Barrier = Barrier;628	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;629	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;630	type ResponseHandler = ();	// Don't handle responses for now.631}632633// parameter_types! {634// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;635// }636637/// No local origins on this chain are allowed to dispatch XCM sends/executions.638pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);639640/// The means for routing XCM messages which are not for local execution into the right message641/// queues.642pub type XcmRouter = (643	// Two routers - use UMP to communicate with the relay chain:644	cumulus_primitives_utility::ParentAsUmp<ParachainSystem>,645	// ..and XCMP to communicate with the sibling chains.646	XcmpQueue,647);648649impl pallet_xcm::Config for Runtime {650	type Event = Event;651	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;652	type XcmRouter = XcmRouter;653	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;654	type XcmExecuteFilter = All<(MultiLocation, Xcm<Call>)>;655	type XcmExecutor = XcmExecutor<XcmConfig>;656	type XcmTeleportFilter = All<(MultiLocation, Vec<MultiAsset>)>;657	type XcmReserveTransferFilter = ();658	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;659}660661impl cumulus_pallet_xcm::Config for Runtime {662	type Event = Event;663	type XcmExecutor = XcmExecutor<XcmConfig>;664}665666impl cumulus_pallet_xcmp_queue::Config for Runtime {667	type Event = Event;668	type XcmExecutor = XcmExecutor<XcmConfig>;669	type ChannelInfo = ParachainSystem;670}671672impl cumulus_pallet_dmp_queue::Config for Runtime {673	type Event = Event;674	type XcmExecutor = XcmExecutor<XcmConfig>;675	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;676}677678impl pallet_aura::Config for Runtime {679	type AuthorityId = AuraId;680}681682parameter_types! {683	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();684	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;685}686687/// Used for the pallet nft in `./nft.rs`688impl pallet_nft::Config for Runtime {689	type Event = Event;690	type WeightInfo = nft_weights::WeightInfo;691692	type EvmWithdrawOrigin = EnsureAddressTruncated;693	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;694	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;695	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;696697	type Currency = Balances;698	type CollectionCreationPrice = CollectionCreationPrice;699	type TreasuryAccountId = TreasuryAccountId;700701	type EthereumChainId = ChainId;702	type EthereumTransactionSender = pallet_ethereum::Module<Runtime>;703}704705parameter_types! {706	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied707}708709/// Used for the pallet inflation710impl pallet_inflation::Config for Runtime {711	type Currency = Balances;712	type TreasuryAccountId = TreasuryAccountId;713	type InflationBlockInterval = InflationBlockInterval;714}715716parameter_types! {717	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *718		RuntimeBlockWeights::get().max_block;719	pub const MaxScheduledPerBlock: u32 = 50;720}721722pub struct Sponsoring;723impl SponsoringResolve<AccountId, Call> for Sponsoring {724725	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId> 726	where 727		Call: Dispatchable<Info=DispatchInfo>,728		Call: IsSubType<pallet_nft::Call<Runtime>>, 729		Call: IsSubType<pallet_contracts::Call<Runtime>>,730		AccountId: AsRef<[u8]>,731		AccountId: UncheckedFrom<Hash>732	{733		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)734	}735}736737impl pallet_scheduler::Config for Runtime {738	type Event = Event;739	type Origin = Origin;740	type PalletsOrigin = OriginCaller;741	type Call = Call;742	type MaximumWeight = MaximumSchedulerWeight;743	type ScheduleOrigin = EnsureSigned<AccountId>;744	type MaxScheduledPerBlock = MaxScheduledPerBlock;745	type Sponsoring = Sponsoring;746	type WeightInfo = ();747}748749impl pallet_nft_transaction_payment::Config for Runtime {750}751752impl pallet_nft_charge_transaction::Config for Runtime {753}754755construct_runtime!(756    pub enum Runtime where757        Block = Block,758        NodeBlock = opaque::Block,759        UncheckedExtrinsic = UncheckedExtrinsic760    {761		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,762		Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},763		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},764		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},765		TransactionPayment: pallet_transaction_payment::{Pallet, Storage},766        Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>},767		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>},768		System: system::{Pallet, Call, Storage, Config, Event<T>},769        Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>},770771		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,772		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,773774		Aura: pallet_aura::{Pallet, Config<T>},775		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config},776777		// Frontier778		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},779		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, ValidateUnsigned},780781		// XCM helpers.782		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,783		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,784		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,785		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,786787788		// Unique Pallets789        Inflation: pallet_inflation::{Pallet, Call, Storage},790		Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},791		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},792		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage},793		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage },794    }795);796797pub struct TransactionConverter;798799impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {800	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {801		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())802	}803}804805impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {806	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {807		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());808		let encoded = extrinsic.encode();809		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")810	}811}812813/// The address format for describing accounts.814pub type Address = sp_runtime::MultiAddress<AccountId, ()>;815/// Block header type as expected by this runtime.816pub type Header = generic::Header<BlockNumber, BlakeTwo256>;817/// Block type as expected by this runtime.818pub type Block = generic::Block<Header, UncheckedExtrinsic>;819/// A Block signed with a Justification820pub type SignedBlock = generic::SignedBlock<Block>;821/// BlockId type as expected by this runtime.822pub type BlockId = generic::BlockId<Block>;823/// The SignedExtension to the basic transaction logic.824pub type SignedExtra = (825    system::CheckSpecVersion<Runtime>,826    // system::CheckTxVersion<Runtime>,827    system::CheckGenesis<Runtime>,828    system::CheckEra<Runtime>,829    system::CheckNonce<Runtime>,830    system::CheckWeight<Runtime>,831    pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,832);833/// Unchecked extrinsic type as expected by this runtime.834pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;835/// Extrinsic type that has already been checked.836pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;837/// Executive: handles dispatch to the various modules.838pub type Executive = frame_executive::Executive<839    Runtime,840    Block,841    frame_system::ChainContext<Runtime>,842    Runtime,843    AllPallets,844>;845846impl_opaque_keys! {847	pub struct SessionKeys {848		pub aura: Aura,849	}850}851852impl_runtime_apis! {853	impl pallet_nft::NftApi<Block>854		for Runtime855	{856		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {857			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)858		}859	}860861    impl sp_api::Core<Block> for Runtime {862        fn version() -> RuntimeVersion {863            VERSION864        }865866        fn execute_block(block: Block) {867            Executive::execute_block(block)868        }869870        fn initialize_block(header: &<Block as BlockT>::Header) {871            Executive::initialize_block(header)872        }873    }874875    impl sp_api::Metadata<Block> for Runtime {876        fn metadata() -> OpaqueMetadata {877            Runtime::metadata().into()878        }879    }880881    impl sp_block_builder::BlockBuilder<Block> for Runtime {882        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {883            Executive::apply_extrinsic(extrinsic)884        }885886        fn finalize_block() -> <Block as BlockT>::Header {887            Executive::finalize_block()888        }889890        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {891            data.create_extrinsics()892        }893894        fn check_inherents(895            block: Block,896            data: sp_inherents::InherentData,897        ) -> sp_inherents::CheckInherentsResult {898            data.check_extrinsics(&block)899        }900901        // fn random_seed() -> <Block as BlockT>::Hash {902        //     RandomnessCollectiveFlip::random_seed().0903        // }904    }905906    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {907        fn validate_transaction(908            source: TransactionSource,909            tx: <Block as BlockT>::Extrinsic,910        ) -> TransactionValidity {911            Executive::validate_transaction(source, tx)912        }913    }914915	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {916		fn offchain_worker(header: &<Block as BlockT>::Header) {917			Executive::offchain_worker(header)918		}919	}920921	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {922		fn chain_id() -> u64 {923			<Runtime as pallet_evm::Config>::ChainId::get()924		}925926		fn account_basic(address: H160) -> EVMAccount {927			EVM::account_basic(&address)928		}929930		fn gas_price() -> U256 {931			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()932		}933934		fn account_code_at(address: H160) -> Vec<u8> {935			EVM::account_codes(address)936		}937938		fn author() -> H160 {939			<pallet_ethereum::Module<Runtime>>::find_author()940		}941942		fn storage_at(address: H160, index: U256) -> H256 {943			let mut tmp = [0u8; 32];944			index.to_big_endian(&mut tmp);945			EVM::account_storages(address, H256::from_slice(&tmp[..]))946		}947948		fn call(949			from: H160,950			to: H160,951			data: Vec<u8>,952			value: U256,953			gas_limit: U256,954			gas_price: Option<U256>,955			nonce: Option<U256>,956			estimate: bool,957		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {958			let config = if estimate {959				let mut config = <Runtime as pallet_evm::Config>::config().clone();960				config.estimate = true;961				Some(config)962			} else {963				None964			};965966			<Runtime as pallet_evm::Config>::Runner::call(967				from,968				to,969				data,970				value,971				gas_limit.low_u64(),972				gas_price,973				nonce,974				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),975			).map_err(|err| err.into())976		}977978		fn create(979			from: H160,980			data: Vec<u8>,981			value: U256,982			gas_limit: U256,983			gas_price: Option<U256>,984			nonce: Option<U256>,985			estimate: bool,986		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {987			let config = if estimate {988				let mut config = <Runtime as pallet_evm::Config>::config().clone();989				config.estimate = true;990				Some(config)991			} else {992				None993			};994995			<Runtime as pallet_evm::Config>::Runner::create(996				from,997				data,998				value,999				gas_limit.low_u64(),1000				gas_price,1001				nonce,1002				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),1003			).map_err(|err| err.into())1004		}10051006		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1007			Ethereum::current_transaction_statuses()1008		}10091010		fn current_block() -> Option<pallet_ethereum::Block> {1011			Ethereum::current_block()1012		}10131014		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1015			Ethereum::current_receipts()1016		}10171018		fn current_all() -> (1019			Option<pallet_ethereum::Block>,1020			Option<Vec<pallet_ethereum::Receipt>>,1021			Option<Vec<TransactionStatus>>1022		) {1023			(1024				Ethereum::current_block(),1025				Ethereum::current_receipts(),1026				Ethereum::current_transaction_statuses()1027			)1028		}1029	}10301031	impl sp_session::SessionKeys<Block> for Runtime {1032		fn decode_session_keys(1033			encoded: Vec<u8>,1034		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1035			SessionKeys::decode_into_raw_public_keys(&encoded)1036		}10371038		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1039			SessionKeys::generate(seed)1040		}1041	}10421043	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1044		fn slot_duration() -> sp_consensus_aura::SlotDuration {1045			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1046		}10471048		fn authorities() -> Vec<AuraId> {1049			Aura::authorities()1050		}1051	}10521053	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1054		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1055			ParachainSystem::collect_collation_info()1056		}1057	}10581059	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1060		fn account_nonce(account: AccountId) -> Index {1061			System::account_nonce(account)1062		}1063	}10641065	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1066		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1067			TransactionPayment::query_info(uxt, len)1068		}1069		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1070			TransactionPayment::query_fee_details(uxt, len)1071		}1072	}10731074	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1075		for Runtime1076	{1077		fn call(1078			origin: AccountId,1079			dest: AccountId,1080			value: Balance,1081			gas_limit: u64,1082			input_data: Vec<u8>,1083		) -> pallet_contracts_primitives::ContractExecResult {1084			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1085		}10861087		fn instantiate(1088			origin: AccountId,1089			endowment: Balance,1090			gas_limit: u64,1091			code: pallet_contracts_primitives::Code<Hash>,1092			data: Vec<u8>,1093			salt: Vec<u8>,1094		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1095		{1096			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1097		}10981099		fn get_storage(1100			address: AccountId,1101			key: [u8; 32],1102		) -> pallet_contracts_primitives::GetStorageResult {1103			Contracts::get_storage(address, key)1104		}11051106		fn rent_projection(1107			address: AccountId,1108		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1109			Contracts::rent_projection(address)1110		}1111	}11121113    #[cfg(feature = "runtime-benchmarks")]1114	impl frame_benchmarking::Benchmark<Block> for Runtime {1115		fn dispatch_benchmark(1116			config: frame_benchmarking::BenchmarkConfig1117		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1118			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};11191120			let whitelist: Vec<TrackedStorageKey> = vec![1121				// Alice account1122				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1123				// // Total Issuance1124				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1125				// // Execution Phase1126				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1127				// // Event Count1128				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1129				// // System Events1130				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1131			];11321133			let mut batches = Vec::<BenchmarkBatch>::new();1134			let params = (&config, &whitelist);11351136			add_benchmark!(params, batches, pallet_nft, Nft);1137			add_benchmark!(params, batches, pallet_inflation, Inflation);11381139			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1140			Ok(batches)1141		}1142	}1143}11441145cumulus_pallet_parachain_system::register_validate_block!(1146	Runtime,1147	cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1148);
after · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use sp_api::impl_runtime_apis;17use sp_core::{ crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160 };18// #[cfg(any(feature = "std", test))]19// pub use sp_runtime::BuildStorage;2021use sp_runtime::{22    Permill, Perbill, Percent,23    create_runtime_str, generic, impl_opaque_keys,24    traits::{25        AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26		Verify, AccountIdConversion,27    },28    transaction_validity::{TransactionSource, TransactionValidity},29    ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo};38// A few exports that help ease life for downstream crates.39pub use pallet_balances::Call as BalancesCall;40pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};41pub use frame_support::{42    construct_runtime,43	match_type,44    dispatch::DispatchResult,45	PalletId,46    parameter_types,47    StorageValue,48	ConsensusEngineId,49    traits::{50        All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, Randomness, FindAuthor51    },52    weights::{53        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},54        DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,55        WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients56    },57};58use nft_data_structs::*;59use pallet_contracts::weights::WeightInfo;60// #[cfg(any(feature = "std", test))]61use frame_system::{62    self as system,63    EnsureRoot, EnsureSigned,64	limits::{BlockWeights, BlockLength},65};66use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73	traits::{ 74		Dispatchable,75	},76};77use pallet_contracts::chain_extension::UncheckedFrom;787980pub use pallet_timestamp::Call as TimestampCall;81pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8283// Polkadot imports84use pallet_xcm::XcmPassthrough;85use polkadot_parachain::primitives::Sibling;86use xcm::v0::Xcm;87use xcm::v0::{BodyId, Junction::*, MultiAsset, MultiLocation, MultiLocation::*, NetworkId};88use xcm_builder::{89	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,90	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,91	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,92	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,93	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,94};95use xcm_executor::{Config, XcmExecutor};969798mod chain_extension;99use crate::chain_extension::{ NFTExtension, Imbalance };100101/// Re-export a nft pallet102/// TODO: Check this re-export. Is this safe and good style?103// extern crate pallet_nft;104// pub use pallet_nft::*;105106/// Reimport pallet inflation107// extern crate pallet_inflation;108// pub use pallet_inflation::*;109110/// An index to a block.111pub type BlockNumber = u32;112113/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.114pub type Signature = MultiSignature;115116/// Some way of identifying an account on the chain. We intentionally make it equivalent117/// to the public key of our transaction signing scheme.118pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;119120/// The type for looking up accounts. We don't expect more than 4 billion of them, but you121/// never know...122pub type AccountIndex = u32;123124/// Balance of an account.125pub type Balance = u128;126127/// Index of a transaction in the chain.128pub type Index = u32;129130/// A hash of some data used by the chain.131pub type Hash = sp_core::H256;132133/// Digest item type.134pub type DigestItem = generic::DigestItem<Hash>;135136mod nft_weights;137138/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know139/// the specifics of the runtime. They can then be made to be agnostic over specific formats140/// of data like extrinsics, allowing for them to continue syncing the network through upgrades141/// to even the core data structures.142pub mod opaque {143	use super::*;144145	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;146147    /// Opaque block type.148    pub type Block = generic::Block<Header, UncheckedExtrinsic>;149150    pub type SessionHandlers = ();151152	impl_opaque_keys! {153        pub struct SessionKeys {154			pub aura: Aura,155		}156    }157}158159/// This runtime version.160pub const VERSION: RuntimeVersion = RuntimeVersion {161	spec_name: create_runtime_str!("nft"),162	impl_name: create_runtime_str!("nft"),163	authoring_version: 1,164	spec_version: 3,165	impl_version: 1,166	apis: RUNTIME_API_VERSIONS,167	transaction_version: 1,168};169170pub const MILLISECS_PER_BLOCK: u64 = 12000;171172pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;173174// These time units are defined in number of blocks.175pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);176pub const HOURS: BlockNumber = MINUTES * 60;177pub const DAYS: BlockNumber = HOURS * 24;178179#[derive(codec::Encode, codec::Decode)]180pub enum XCMPMessage<XAccountId, XBalance> {181    /// Transfer tokens to the given account from the Parachain account.182    TransferToken(XAccountId, XBalance),183}184185/// The version information used to identify this runtime when compiled natively.186#[cfg(feature = "std")]187pub fn native_version() -> NativeVersion {188	NativeVersion {189		runtime_version: VERSION,190		can_author_with: Default::default(),191	}192}193194type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;195196pub struct DealWithFees;197impl OnUnbalanced<NegativeImbalance> for DealWithFees {198	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {199		if let Some(fees) = fees_then_tips.next() {200			// for fees, 100% to treasury201			let mut split = fees.ration(100, 0);202			if let Some(tips) = fees_then_tips.next() {203				// for tips, if any, 100% to treasury204				tips.ration_merge_into(100, 0, &mut split);205			}206			Treasury::on_unbalanced(split.0);207			// Author::on_unbalanced(split.1);208		}209	}210}211212/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.213/// This is used to limit the maximal weight of a single extrinsic.214const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);215/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used216/// by  Operational  extrinsics.217const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);218/// We allow for 2 seconds of compute with a 6 second average block time.219const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;220221parameter_types! {222	pub const BlockHashCount: BlockNumber = 2400;223	pub RuntimeBlockLength: BlockLength =224		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228		.base_block(BlockExecutionWeight::get())229		.for_class(DispatchClass::all(), |weights| {230			weights.base_extrinsic = ExtrinsicBaseWeight::get();231		})232		.for_class(DispatchClass::Normal, |weights| {233			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234		})235		.for_class(DispatchClass::Operational, |weights| {236			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237			// Operational transactions have some extra reserved space, so that they238			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239			weights.reserved = Some(240				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241			);242		})243		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244		.build_or_panic();245	pub const Version: RuntimeVersion = VERSION;246	pub const SS58Prefix: u8 = 42;247}248249250parameter_types! {251	pub const ChainId: u64 = 8888;252}253254impl pallet_evm::Config for Runtime {255	type BlockGasLimit = BlockGasLimit;256	type FeeCalculator = ();257	type GasWeightMapping = ();258	type CallOrigin = EnsureAddressTruncated;259	type WithdrawOrigin = EnsureAddressTruncated;260	type AddressMapping = HashedAddressMapping<Self::Hashing>;261	type Precompiles = ();262	type Currency = Balances;263	type Event = Event;264	type OnMethodCall = pallet_nft::NftErcSupport<Self>;265	type ChainId = ChainId;266	type Runner = pallet_evm::runner::stack::Runner<Self>;267	type OnChargeTransaction = ();268}269270pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);271impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>272{273	fn find_author<'a, I>(digests: I) -> Option<H160> where274		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>275	{276		if let Some(author_index) = F::find_author(digests) {277			let authority_id = Aura::authorities()[author_index as usize].clone();278			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));279		}280		None281	}282}283284parameter_types! {285	pub BlockGasLimit: U256 = U256::from(u32::max_value());286}287288impl pallet_ethereum::Config for Runtime {289	type Event = Event;290	type FindAuthor = EthereumFindAuthor<Aura>;291	type StateRoot = pallet_ethereum::IntermediateStateRoot;292	type EvmSubmitLog = pallet_evm::Pallet<Runtime>;293}294295impl system::Config for Runtime {296    /// The data to be stored in an account.297    type AccountData = pallet_balances::AccountData<Balance>;298    /// The identifier used to distinguish between accounts.299    type AccountId = AccountId;300    /// The basic call filter to use in dispatchable.301    type BaseCallFilter = ();302    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).303    type BlockHashCount = BlockHashCount;304    /// The maximum length of a block (in bytes).305	type BlockLength = RuntimeBlockLength;306    /// The index type for blocks.307    type BlockNumber = BlockNumber;308    /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.309	type BlockWeights = RuntimeBlockWeights;310    /// The aggregated dispatch type that is available for extrinsics.311    type Call = Call;312    /// The weight of database operations that the runtime can invoke.313    type DbWeight = RocksDbWeight;314    /// The ubiquitous event type.315    type Event = Event;316    /// The type for hashing blocks and tries.317    type Hash = Hash;318	/// The hashing algorithm used.319    type Hashing = BlakeTwo256;320    /// The header type.321    type Header = generic::Header<BlockNumber, BlakeTwo256>;322    /// The index type for storing how many extrinsics an account has signed.323    type Index = Index;324    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.325    type Lookup = AccountIdLookup<AccountId, ()>;326    /// What to do if an account is fully reaped from the system.327    type OnKilledAccount = ();328    /// What to do if a new account is created.329    type OnNewAccount = ();330    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;331    /// The ubiquitous origin type.332    type Origin = Origin;333 	/// This type is being generated by `construct_runtime!`.334    type PalletInfo = PalletInfo;335    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.336	type SS58Prefix = SS58Prefix;337	/// Weight information for the extrinsics of this pallet.338    type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;339    /// Version of the runtime.340    type Version = Version;341}342343parameter_types! {344	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;345}346347impl pallet_timestamp::Config for Runtime {348	/// A timestamp: milliseconds since the unix epoch.349	type Moment = u64;350	type OnTimestampSet = ();351	type MinimumPeriod = MinimumPeriod;352	type WeightInfo = ();353}354355parameter_types! {356	// pub const ExistentialDeposit: u128 = 500;357	pub const ExistentialDeposit: u128 = 0;358	pub const MaxLocks: u32 = 50;359}360361impl pallet_balances::Config for Runtime {362	type MaxLocks = MaxLocks;363	/// The type for recording an account's balance.364	type Balance = Balance;365	/// The ubiquitous event type.366	type Event = Event;367	type DustRemoval = Treasury;368	type ExistentialDeposit = ExistentialDeposit;369	type AccountStore = System;370	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;371}372373pub const MICROUNIQUE: Balance = 1_000_000_000;374pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;375pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;376pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;377378pub const fn deposit(items: u32, bytes: u32) -> Balance {379	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE380}381382parameter_types! {383	pub TombstoneDeposit: Balance = deposit(384		1,385		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,386	);387	pub DepositPerContract: Balance = TombstoneDeposit::get();388	pub const DepositPerStorageByte: Balance = deposit(0, 1);389	pub const DepositPerStorageItem: Balance = deposit(1, 0);390	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);391	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;392	pub const SignedClaimHandicap: u32 = 2;393	pub const MaxDepth: u32 = 32;394	pub const MaxValueSize: u32 = 16 * 1024;395	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb396	// The lazy deletion runs inside on_initialize.397	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *398		RuntimeBlockWeights::get().max_block;399	// The weight needed for decoding the queue should be less or equal than a fifth400	// of the overall weight dedicated to the lazy deletion.401	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (402			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -403			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)404		)) / 5) as u32;405	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();406}407408impl pallet_contracts::Config for Runtime {409	type Time = Timestamp;410	type Randomness = RandomnessCollectiveFlip;411	type Currency = Balances;412	type Event = Event;413	type RentPayment = ();414	type SignedClaimHandicap = SignedClaimHandicap;415	type TombstoneDeposit = TombstoneDeposit;416	type DepositPerContract = DepositPerContract;417	type DepositPerStorageByte = DepositPerStorageByte;418	type DepositPerStorageItem = DepositPerStorageItem;419	type RentFraction = RentFraction;420	type SurchargeReward = SurchargeReward;421	// type MaxDepth = MaxDepth;422	// type MaxValueSize = MaxValueSize;423	type WeightPrice = pallet_transaction_payment::Module<Self>;424	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;425	type ChainExtension = NFTExtension;426	type DeletionQueueDepth = DeletionQueueDepth;427	type DeletionWeightLimit = DeletionWeightLimit;428	// type MaxCodeSize = MaxCodeSize;429	type Schedule = Schedule;430	type CallStack = [pallet_contracts::Frame<Self>; 31];431}432433parameter_types! {434	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer435}436437/// Linear implementor of `WeightToFeePolynomial`438pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);439440impl<T> WeightToFeePolynomial for LinearFee<T> where441	T: BaseArithmetic + From<u32> + Copy + Unsigned442{443	type Balance = T;444445	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {446		smallvec!(WeightToFeeCoefficient {447			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer448			coeff_frac: Perbill::zero(),449			negative: false,450			degree: 1,451		})452	}453}454455impl pallet_transaction_payment::Config for Runtime {456	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;457	type TransactionByteFee = TransactionByteFee;458	type WeightToFee = LinearFee<Balance>;459	type FeeMultiplierUpdate = ();460}461462parameter_types! {463	pub const ProposalBond: Permill = Permill::from_percent(5);464	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;465	pub const SpendPeriod: BlockNumber = 5 * MINUTES;466	pub const Burn: Permill = Permill::from_percent(0);467	pub const TipCountdown: BlockNumber = 1 * DAYS;468	pub const TipFindersFee: Percent = Percent::from_percent(20);469	pub const TipReportDepositBase: Balance = 1 * UNIQUE;470	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;471	pub const BountyDepositBase: Balance = 1 * UNIQUE;472	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;473	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");474	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;475	pub const MaximumReasonLength: u32 = 16384;476	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);477	pub const BountyValueMinimum: Balance = 5 * UNIQUE;478	pub const MaxApprovals: u32 = 100;479}480481impl pallet_treasury::Config for Runtime {482	type PalletId = TreasuryModuleId;483	type Currency = Balances;484	type ApproveOrigin = EnsureRoot<AccountId>;485	type RejectOrigin = EnsureRoot<AccountId>;486	type Event = Event;487	type OnSlash = ();488	type ProposalBond = ProposalBond;489	type ProposalBondMinimum = ProposalBondMinimum;490	type SpendPeriod = SpendPeriod;491	type Burn = Burn;492	type BurnDestination = ();493	type SpendFunds = ();494	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;495	type MaxApprovals = MaxApprovals;496}497498impl pallet_sudo::Config for Runtime {499	type Event = Event;500	type Call = Call;501}502503parameter_types! {504	pub const MinVestedTransfer: Balance = 10 * UNIQUE;505}506507impl pallet_vesting::Config for Runtime {508	type Event = Event;509	type Currency = Balances;510	type BlockNumberToBalance = ConvertInto;511	type MinVestedTransfer = MinVestedTransfer;512	type WeightInfo = ();513}514515parameter_types! {516	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;517	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;518}519520impl cumulus_pallet_parachain_system::Config for Runtime {521	type Event = Event;522	type OnValidationData = ();523	type SelfParaId = parachain_info::Pallet<Runtime>;524	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<525	// 	MaxDownwardMessageWeight,526	// 	XcmExecutor<XcmConfig>,527	// 	Call,528	// >;529	type OutboundXcmpMessageSource = XcmpQueue;530	type DmpMessageHandler = DmpQueue;531	type ReservedDmpWeight = ReservedDmpWeight;532	type ReservedXcmpWeight = ReservedXcmpWeight;533	type XcmpMessageHandler = XcmpQueue;534}535536impl parachain_info::Config for Runtime {}537538impl cumulus_pallet_aura_ext::Config for Runtime {}539540parameter_types! {541	pub const RelayLocation: MultiLocation = X1(Parent);542	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;543	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();544	pub Ancestry: MultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));545}546547/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used548/// when determining ownership of accounts for asset transacting and when attempting to use XCM549/// `Transact` in order to determine the dispatch Origin.550pub type LocationToAccountId = (551	// The parent (Relay-chain) origin converts to the default `AccountId`.552	ParentIsDefault<AccountId>,553	// Sibling parachain origins convert to AccountId via the `ParaId::into`.554	SiblingParachainConvertsVia<Sibling, AccountId>,555	// Straight up local `AccountId32` origins just alias directly to `AccountId`.556	AccountId32Aliases<RelayNetwork, AccountId>,557);558559/// Means for transacting assets on this chain.560pub type LocalAssetTransactor = CurrencyAdapter<561	// Use this currency:562	Balances,563	// Use this currency when it is a fungible asset matching the given location or name:564	IsConcrete<RelayLocation>,565	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:566	LocationToAccountId,567	// Our chain's account ID type (we can't get away without mentioning it explicitly):568	AccountId,569	// We don't track any teleports.570	(),571>;572573/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,574/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can575/// biases the kind of local `Origin` it will become.576pub type XcmOriginToTransactDispatchOrigin = (577	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location578	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for579	// foreign chains who want to have a local sovereign account on this chain which they control.580	SovereignSignedViaLocation<LocationToAccountId, Origin>,581	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when582	// recognised.583	RelayChainAsNative<RelayOrigin, Origin>,584	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when585	// recognised.586	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,587	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a588	// transaction from the Root origin.589	ParentAsSuperuser<Origin>,590	// Native signed account converter; this just converts an `AccountId32` origin into a normal591	// `Origin::Signed` origin of the same 32-byte value.592	SignedAccountId32AsNative<RelayNetwork, Origin>,593	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.594	XcmPassthrough<Origin>,595);596597parameter_types! {598	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.599	pub UnitWeightCost: Weight = 1_000_000;600	// 1200 UNIQUEs buy 1 second of weight.601	pub const WeightPrice: (MultiLocation, u128) = (X1(Parent), 1_200 * UNIQUE);602}603604match_type! {605	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {606		X1(Parent) | X2(Parent, Plurality { id: BodyId::Unit, .. })607	};608}609610pub type Barrier = (611	TakeWeightCredit,612	AllowTopLevelPaidExecutionFrom<All<MultiLocation>>,613	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,614	// ^^^ Parent & its unit plurality gets free execution615);616617pub struct XcmConfig;618impl Config for XcmConfig {619	type Call = Call;620	type XcmSender = XcmRouter;621	// How to withdraw and deposit an asset.622	type AssetTransactor = LocalAssetTransactor;623	type OriginConverter = XcmOriginToTransactDispatchOrigin;624	type IsReserve = NativeAsset;625	type IsTeleporter = NativeAsset;	// <- should be enough to allow teleportation of ROC626	type LocationInverter = LocationInverter<Ancestry>;627	type Barrier = Barrier;628	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;629	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;630	type ResponseHandler = ();	// Don't handle responses for now.631}632633// parameter_types! {634// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;635// }636637/// No local origins on this chain are allowed to dispatch XCM sends/executions.638pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);639640/// The means for routing XCM messages which are not for local execution into the right message641/// queues.642pub type XcmRouter = (643	// Two routers - use UMP to communicate with the relay chain:644	cumulus_primitives_utility::ParentAsUmp<ParachainSystem>,645	// ..and XCMP to communicate with the sibling chains.646	XcmpQueue,647);648649impl pallet_xcm::Config for Runtime {650	type Event = Event;651	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;652	type XcmRouter = XcmRouter;653	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;654	type XcmExecuteFilter = All<(MultiLocation, Xcm<Call>)>;655	type XcmExecutor = XcmExecutor<XcmConfig>;656	type XcmTeleportFilter = All<(MultiLocation, Vec<MultiAsset>)>;657	type XcmReserveTransferFilter = ();658	type Weigher = FixedWeightBounds<UnitWeightCost, Call>;659}660661impl cumulus_pallet_xcm::Config for Runtime {662	type Event = Event;663	type XcmExecutor = XcmExecutor<XcmConfig>;664}665666impl cumulus_pallet_xcmp_queue::Config for Runtime {667	type Event = Event;668	type XcmExecutor = XcmExecutor<XcmConfig>;669	type ChannelInfo = ParachainSystem;670}671672impl cumulus_pallet_dmp_queue::Config for Runtime {673	type Event = Event;674	type XcmExecutor = XcmExecutor<XcmConfig>;675	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;676}677678impl pallet_aura::Config for Runtime {679	type AuthorityId = AuraId;680}681682parameter_types! {683	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();684	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;685}686687/// Used for the pallet nft in `./nft.rs`688impl pallet_nft::Config for Runtime {689	type Event = Event;690	type WeightInfo = nft_weights::WeightInfo;691692	type EvmWithdrawOrigin = EnsureAddressTruncated;693	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;694	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;695	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;696697	type Currency = Balances;698	type CollectionCreationPrice = CollectionCreationPrice;699	type TreasuryAccountId = TreasuryAccountId;700701	type EthereumChainId = ChainId;702	type EthereumTransactionSender = pallet_ethereum::Module<Runtime>;703}704705parameter_types! {706	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied707}708709/// Used for the pallet inflation710impl pallet_inflation::Config for Runtime {711	type Currency = Balances;712	type TreasuryAccountId = TreasuryAccountId;713	type InflationBlockInterval = InflationBlockInterval;714}715716parameter_types! {717	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *718		RuntimeBlockWeights::get().max_block;719	pub const MaxScheduledPerBlock: u32 = 50;720}721722pub struct Sponsoring;723impl SponsoringResolve<AccountId, Call> for Sponsoring {724725	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId> 726	where 727		Call: Dispatchable<Info=DispatchInfo>,728		Call: IsSubType<pallet_nft::Call<Runtime>>, 729		Call: IsSubType<pallet_contracts::Call<Runtime>>,730		AccountId: AsRef<[u8]>,731		AccountId: UncheckedFrom<Hash>732	{733		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)734	}735}736737type SponsorshipHandler = (738	pallet_nft::NftSponsorshipHandler<Runtime>,739    pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,740);741742impl pallet_scheduler::Config for Runtime {743	type Event = Event;744	type Origin = Origin;745	type PalletsOrigin = OriginCaller;746	type Call = Call;747	type MaximumWeight = MaximumSchedulerWeight;748	type ScheduleOrigin = EnsureSigned<AccountId>;749	type MaxScheduledPerBlock = MaxScheduledPerBlock;750	type SponsorshipHandler = SponsorshipHandler;751	type WeightInfo = ();752}753754impl pallet_nft_transaction_payment::Config for Runtime {755	type SponsorshipHandler = SponsorshipHandler;756}757758impl pallet_nft_charge_transaction::Config for Runtime {}759760impl pallet_contract_helpers::Config for Runtime {}761762construct_runtime!(763    pub enum Runtime where764        Block = Block,765        NodeBlock = opaque::Block,766        UncheckedExtrinsic = UncheckedExtrinsic767    {768		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,769		Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},770		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},771		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},772		TransactionPayment: pallet_transaction_payment::{Pallet, Storage},773        Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>},774		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>},775		System: system::{Pallet, Call, Storage, Config, Event<T>},776        Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>},777778		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,779		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,780781		Aura: pallet_aura::{Pallet, Config<T>},782		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config},783784		// Frontier785		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},786		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, ValidateUnsigned},787788		// XCM helpers.789		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,790		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,791		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,792		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,793794795		// Unique Pallets796        Inflation: pallet_inflation::{Pallet, Call, Storage},797		Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},798		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},799		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage},800		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage },801		ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage},802    }803);804805pub struct TransactionConverter;806807impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {808	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {809		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())810	}811}812813impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {814	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {815		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());816		let encoded = extrinsic.encode();817		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")818	}819}820821/// The address format for describing accounts.822pub type Address = sp_runtime::MultiAddress<AccountId, ()>;823/// Block header type as expected by this runtime.824pub type Header = generic::Header<BlockNumber, BlakeTwo256>;825/// Block type as expected by this runtime.826pub type Block = generic::Block<Header, UncheckedExtrinsic>;827/// A Block signed with a Justification828pub type SignedBlock = generic::SignedBlock<Block>;829/// BlockId type as expected by this runtime.830pub type BlockId = generic::BlockId<Block>;831/// The SignedExtension to the basic transaction logic.832pub type SignedExtra = (833    system::CheckSpecVersion<Runtime>,834    // system::CheckTxVersion<Runtime>,835    system::CheckGenesis<Runtime>,836    system::CheckEra<Runtime>,837    system::CheckNonce<Runtime>,838    system::CheckWeight<Runtime>,839    pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,840	pallet_contract_helpers::ContractHelpersExtension<Runtime>,841);842/// Unchecked extrinsic type as expected by this runtime.843pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;844/// Extrinsic type that has already been checked.845pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;846/// Executive: handles dispatch to the various modules.847pub type Executive = frame_executive::Executive<848    Runtime,849    Block,850    frame_system::ChainContext<Runtime>,851    Runtime,852    AllPallets,853>;854855impl_opaque_keys! {856	pub struct SessionKeys {857		pub aura: Aura,858	}859}860861impl_runtime_apis! {862	impl pallet_nft::NftApi<Block>863		for Runtime864	{865		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {866			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)867		}868	}869870    impl sp_api::Core<Block> for Runtime {871        fn version() -> RuntimeVersion {872            VERSION873        }874875        fn execute_block(block: Block) {876            Executive::execute_block(block)877        }878879        fn initialize_block(header: &<Block as BlockT>::Header) {880            Executive::initialize_block(header)881        }882    }883884    impl sp_api::Metadata<Block> for Runtime {885        fn metadata() -> OpaqueMetadata {886            Runtime::metadata().into()887        }888    }889890    impl sp_block_builder::BlockBuilder<Block> for Runtime {891        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {892            Executive::apply_extrinsic(extrinsic)893        }894895        fn finalize_block() -> <Block as BlockT>::Header {896            Executive::finalize_block()897        }898899        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {900            data.create_extrinsics()901        }902903        fn check_inherents(904            block: Block,905            data: sp_inherents::InherentData,906        ) -> sp_inherents::CheckInherentsResult {907            data.check_extrinsics(&block)908        }909910        // fn random_seed() -> <Block as BlockT>::Hash {911        //     RandomnessCollectiveFlip::random_seed().0912        // }913    }914915    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {916        fn validate_transaction(917            source: TransactionSource,918            tx: <Block as BlockT>::Extrinsic,919        ) -> TransactionValidity {920            Executive::validate_transaction(source, tx)921        }922    }923924	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {925		fn offchain_worker(header: &<Block as BlockT>::Header) {926			Executive::offchain_worker(header)927		}928	}929930	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {931		fn chain_id() -> u64 {932			<Runtime as pallet_evm::Config>::ChainId::get()933		}934935		fn account_basic(address: H160) -> EVMAccount {936			EVM::account_basic(&address)937		}938939		fn gas_price() -> U256 {940			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()941		}942943		fn account_code_at(address: H160) -> Vec<u8> {944			EVM::account_codes(address)945		}946947		fn author() -> H160 {948			<pallet_ethereum::Module<Runtime>>::find_author()949		}950951		fn storage_at(address: H160, index: U256) -> H256 {952			let mut tmp = [0u8; 32];953			index.to_big_endian(&mut tmp);954			EVM::account_storages(address, H256::from_slice(&tmp[..]))955		}956957		fn call(958			from: H160,959			to: H160,960			data: Vec<u8>,961			value: U256,962			gas_limit: U256,963			gas_price: Option<U256>,964			nonce: Option<U256>,965			estimate: bool,966		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {967			let config = if estimate {968				let mut config = <Runtime as pallet_evm::Config>::config().clone();969				config.estimate = true;970				Some(config)971			} else {972				None973			};974975			<Runtime as pallet_evm::Config>::Runner::call(976				from,977				to,978				data,979				value,980				gas_limit.low_u64(),981				gas_price,982				nonce,983				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),984			).map_err(|err| err.into())985		}986987		fn create(988			from: H160,989			data: Vec<u8>,990			value: U256,991			gas_limit: U256,992			gas_price: Option<U256>,993			nonce: Option<U256>,994			estimate: bool,995		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {996			let config = if estimate {997				let mut config = <Runtime as pallet_evm::Config>::config().clone();998				config.estimate = true;999				Some(config)1000			} else {1001				None1002			};10031004			<Runtime as pallet_evm::Config>::Runner::create(1005				from,1006				data,1007				value,1008				gas_limit.low_u64(),1009				gas_price,1010				nonce,1011				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),1012			).map_err(|err| err.into())1013		}10141015		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1016			Ethereum::current_transaction_statuses()1017		}10181019		fn current_block() -> Option<pallet_ethereum::Block> {1020			Ethereum::current_block()1021		}10221023		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1024			Ethereum::current_receipts()1025		}10261027		fn current_all() -> (1028			Option<pallet_ethereum::Block>,1029			Option<Vec<pallet_ethereum::Receipt>>,1030			Option<Vec<TransactionStatus>>1031		) {1032			(1033				Ethereum::current_block(),1034				Ethereum::current_receipts(),1035				Ethereum::current_transaction_statuses()1036			)1037		}1038	}10391040	impl sp_session::SessionKeys<Block> for Runtime {1041		fn decode_session_keys(1042			encoded: Vec<u8>,1043		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1044			SessionKeys::decode_into_raw_public_keys(&encoded)1045		}10461047		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1048			SessionKeys::generate(seed)1049		}1050	}10511052	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1053		fn slot_duration() -> sp_consensus_aura::SlotDuration {1054			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1055		}10561057		fn authorities() -> Vec<AuraId> {1058			Aura::authorities()1059		}1060	}10611062	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1063		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1064			ParachainSystem::collect_collation_info()1065		}1066	}10671068	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1069		fn account_nonce(account: AccountId) -> Index {1070			System::account_nonce(account)1071		}1072	}10731074	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1075		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1076			TransactionPayment::query_info(uxt, len)1077		}1078		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1079			TransactionPayment::query_fee_details(uxt, len)1080		}1081	}10821083	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1084		for Runtime1085	{1086		fn call(1087			origin: AccountId,1088			dest: AccountId,1089			value: Balance,1090			gas_limit: u64,1091			input_data: Vec<u8>,1092		) -> pallet_contracts_primitives::ContractExecResult {1093			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1094		}10951096		fn instantiate(1097			origin: AccountId,1098			endowment: Balance,1099			gas_limit: u64,1100			code: pallet_contracts_primitives::Code<Hash>,1101			data: Vec<u8>,1102			salt: Vec<u8>,1103		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1104		{1105			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1106		}11071108		fn get_storage(1109			address: AccountId,1110			key: [u8; 32],1111		) -> pallet_contracts_primitives::GetStorageResult {1112			Contracts::get_storage(address, key)1113		}11141115		fn rent_projection(1116			address: AccountId,1117		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1118			Contracts::rent_projection(address)1119		}1120	}11211122    #[cfg(feature = "runtime-benchmarks")]1123	impl frame_benchmarking::Benchmark<Block> for Runtime {1124		fn dispatch_benchmark(1125			config: frame_benchmarking::BenchmarkConfig1126		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1127			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};11281129			let whitelist: Vec<TrackedStorageKey> = vec![1130				// Alice account1131				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1132				// // Total Issuance1133				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1134				// // Execution Phase1135				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1136				// // Event Count1137				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1138				// // System Events1139				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1140			];11411142			let mut batches = Vec::<BenchmarkBatch>::new();1143			let params = (&config, &whitelist);11441145			add_benchmark!(params, batches, pallet_nft, Nft);1146			add_benchmark!(params, batches, pallet_inflation, Inflation);11471148			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1149			Ok(batches)1150		}1151	}1152}11531154cumulus_pallet_parachain_system::register_validate_block!(1155	Runtime,1156	cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1157);