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

difftreelog

refactor switch charging logic to sponsoring primitive

Yaroslav Bolyukin2021-06-24parent: #c12e121.patch.diff
in: master

6 files changed

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
before · pallets/nft-charge-transaction/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#![cfg_attr(not(feature = "std"), no_std)]78#[cfg(feature = "std")]9pub use std::*;1011#[cfg(feature = "std")]12pub use serde::*;1314#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;1617#[cfg(test)]18mod tests;1920use codec::{Decode, Encode};21use frame_support::traits::{ Get};22use frame_support::{23	decl_module, decl_storage,24	traits::{25		IsSubType, 26	},27	weights::{28		DispatchInfo, PostDispatchInfo, DispatchClass29	}30};31use sp_runtime::{32	traits::{ 33		DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,34	},35	transaction_validity::{ 36		TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,37	},38	FixedPointOperand, DispatchResult39};40use pallet_contracts::chain_extension::UncheckedFrom;41use pallet_transaction_payment::OnChargeTransaction;42use sp_std::prelude::*;434445pub trait Config: frame_system::Config + 46    pallet_nft_transaction_payment::Config47{4849}5051decl_storage! {52    trait Store for Module<T: Config> as NftTransactionPayment53    {}54}5556decl_module! {5758	pub struct Module<T: Config> for enum Call 59    where 60		origin: T::Origin,61    {}62}6364type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;6566/// Require the transactor pay for themselves and maybe include a tip to gain additional priority67/// in the queue.68#[derive(Encode, Decode, Clone, Eq, PartialEq)]69pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);7071impl<T: Config + Send + Sync> sp_std::fmt::Debug 72    for ChargeTransactionPayment<T>73{74	#[cfg(feature = "std")]75	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {76		write!(f, "ChargeTransactionPayment<{:?}>", self.0)77	}78	#[cfg(not(feature = "std"))]79	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {80		Ok(())81	}82}8384impl<T: Config> ChargeTransactionPayment<T>85where86	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,87    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,88    T::AccountId: AsRef<[u8]>,89    T::AccountId: UncheckedFrom<T::Hash>,90{91    fn traditional_fee(92        len: usize,93        info: &DispatchInfoOf<T::Call>,94        tip: BalanceOf<T>,95    ) -> BalanceOf<T>96    where97        T::Call: Dispatchable<Info = DispatchInfo>,98    {99        <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)100    }101102	fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {103        let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);104        let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);105        let len_saturation = max_block_length as u64 / (len as u64).max(1);106        let coefficient: BalanceOf<T> = weight_saturation107            .min(len_saturation)108            .saturated_into::<BalanceOf<T>>();109        final_fee110            .saturating_mul(coefficient)111            .saturated_into::<TransactionPriority>()112    }113114    fn withdraw_fee(115        &self,116        who: &T::AccountId,117        call: &T::Call,118        info: &DispatchInfoOf<T::Call>,119        len: usize,120	) -> Result<121		(122			BalanceOf<T>,123			<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,124		),125		TransactionValidityError,126	> {127        let tip = self.0;128129        let fee = Self::traditional_fee(len, info, tip);130131        // Only mess with balances if fee is not zero.132        if fee.is_zero() {133            return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)134			.map(|i| (fee, i));135        }136137        // check errors138        let _error = <pallet_nft_transaction_payment::Module<T>>::check_error(who, call);139        match _error {140            Err(_error) => return Err(_error),141            Ok(_error) => {}142        };143144        // Determine who is paying transaction fee based on ecnomic model145		// Parse call to extract collection ID and access collection sponsor	146		let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);147148        let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());149150		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)151			.map(|i| (fee, i))152    }153}154155impl<T: Config + Send + Sync> SignedExtension156    for ChargeTransactionPayment<T>157where158    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,159	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,160    T::AccountId: AsRef<[u8]>,161    T::AccountId: UncheckedFrom<T::Hash>,162{163    const IDENTIFIER: &'static str = "ChargeTransactionPayment";164    type AccountId = T::AccountId;165    type Call = T::Call;166    type AdditionalSigned = ();167    type Pre = (168        // tip169        BalanceOf<T>,170        // who pays fee171        Self::AccountId,172		// imbalance resulting from withdrawing the fee173		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,174    );175    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {176        Ok(())177    }178179    fn validate(180        &self,181        who: &Self::AccountId,182        call: &Self::Call,183        info: &DispatchInfoOf<Self::Call>,184        len: usize,185    ) -> TransactionValidity {186		let (fee, _) = self.withdraw_fee(who, call, info, len)?;187		Ok(ValidTransaction {188			priority: Self::get_priority(len, info, fee),189			..Default::default()190		})191    }192193    fn pre_dispatch(194        self,195        who: &Self::AccountId,196        call: &Self::Call,197        info: &DispatchInfoOf<Self::Call>,198        len: usize,199    ) -> Result<Self::Pre, TransactionValidityError> {200        let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;201        Ok((self.0, who.clone(), imbalance))202    }203204    fn post_dispatch(205        pre: Self::Pre,206        info: &DispatchInfoOf<Self::Call>,207        post_info: &PostDispatchInfoOf<Self::Call>,208        len: usize,209        _result: &DispatchResult,210    ) -> Result<(), TransactionValidityError> {211		let (tip, who, imbalance) = pre;212		let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(213			len as u32,214			info,215			post_info,216			tip,217		);218		<T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;219		Ok(())220    }221}
after · pallets/nft-charge-transaction/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#![cfg_attr(not(feature = "std"), no_std)]78#[cfg(feature = "std")]9pub use std::*;1011#[cfg(feature = "std")]12pub use serde::*;1314#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;1617use codec::{Decode, Encode};18use frame_support::traits::Get;19use frame_support::{20	decl_module, decl_storage,21	weights::{22		DispatchInfo, PostDispatchInfo, DispatchClass23	}24};25use sp_runtime::{26	traits::{ 27		DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,28	},29	transaction_validity::{ 30		TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,31	},32	FixedPointOperand, DispatchResult33};34use pallet_transaction_payment::OnChargeTransaction;35use sp_std::prelude::*;363738pub trait Config: frame_system::Config + 39    pallet_nft_transaction_payment::Config40{4142}4344decl_storage! {45    trait Store for Module<T: Config> as NftTransactionPayment46    {}47}4849decl_module! {5051	pub struct Module<T: Config> for enum Call 52    where 53		origin: T::Origin,54    {}55}5657type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;5859/// Require the transactor pay for themselves and maybe include a tip to gain additional priority60/// in the queue.61#[derive(Encode, Decode, Clone, Eq, PartialEq)]62pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);6364impl<T: Config + Send + Sync> sp_std::fmt::Debug 65    for ChargeTransactionPayment<T>66{67	#[cfg(feature = "std")]68	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {69		write!(f, "ChargeTransactionPayment<{:?}>", self.0)70	}71	#[cfg(not(feature = "std"))]72	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {73		Ok(())74	}75}7677impl<T: Config> ChargeTransactionPayment<T>78where79	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo>,80    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,81{82    fn traditional_fee(83        len: usize,84        info: &DispatchInfoOf<T::Call>,85        tip: BalanceOf<T>,86    ) -> BalanceOf<T>87    where88        T::Call: Dispatchable<Info = DispatchInfo>,89    {90        <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)91    }9293	fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {94        let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);95        let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);96        let len_saturation = max_block_length as u64 / (len as u64).max(1);97        let coefficient: BalanceOf<T> = weight_saturation98            .min(len_saturation)99            .saturated_into::<BalanceOf<T>>();100        final_fee101            .saturating_mul(coefficient)102            .saturated_into::<TransactionPriority>()103    }104105    fn withdraw_fee(106        &self,107        who: &T::AccountId,108        call: &T::Call,109        info: &DispatchInfoOf<T::Call>,110        len: usize,111	) -> Result<112		(113			BalanceOf<T>,114			<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,115		),116		TransactionValidityError,117	> {118        let tip = self.0;119120        let fee = Self::traditional_fee(len, info, tip);121122        // Only mess with balances if fee is not zero.123        if fee.is_zero() {124            return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)125			.map(|i| (fee, i));126        }127128        // Determine who is paying transaction fee based on ecnomic model129		// Parse call to extract collection ID and access collection sponsor	130		let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);131132        let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());133134		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)135			.map(|i| (fee, i))136    }137}138139impl<T: Config + Send + Sync> SignedExtension140    for ChargeTransactionPayment<T>141where142    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,143	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo>,144{145    const IDENTIFIER: &'static str = "ChargeTransactionPayment";146    type AccountId = T::AccountId;147    type Call = T::Call;148    type AdditionalSigned = ();149    type Pre = (150        // tip151        BalanceOf<T>,152        // who pays fee153        Self::AccountId,154		// imbalance resulting from withdrawing the fee155		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,156    );157    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {158        Ok(())159    }160161    fn validate(162        &self,163        who: &Self::AccountId,164        call: &Self::Call,165        info: &DispatchInfoOf<Self::Call>,166        len: usize,167    ) -> TransactionValidity {168		let (fee, _) = self.withdraw_fee(who, call, info, len)?;169		Ok(ValidTransaction {170			priority: Self::get_priority(len, info, fee),171			..Default::default()172		})173    }174175    fn pre_dispatch(176        self,177        who: &Self::AccountId,178        call: &Self::Call,179        info: &DispatchInfoOf<Self::Call>,180        len: usize,181    ) -> Result<Self::Pre, TransactionValidityError> {182        let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;183        Ok((self.0, who.clone(), imbalance))184    }185186    fn post_dispatch(187        pre: Self::Pre,188        info: &DispatchInfoOf<Self::Call>,189        post_info: &PostDispatchInfoOf<Self::Call>,190        len: usize,191        _result: &DispatchResult,192    ) -> Result<(), TransactionValidityError> {193		let (tip, who, imbalance) = pre;194		let actual_fee = pallet_transaction_payment::Pallet::<T>::compute_actual_fee(195			len as u32,196			info,197			post_info,198			tip,199		);200		<T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;201		Ok(())202    }203}
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]);
-			}
-		});
-	}
-}