git.delta.rocks / unique-network / refs/commits / 2072cd7e5aa3

difftreelog

merge to recent changes

Greg Zaitsev2021-06-30parents: #4afa738 #fbd66f5.patch.diff
in: master

14 files changed

modified.github/workflows/codestyle.ymldiffbeforeafterboth
--- a/.github/workflows/codestyle.yml
+++ b/.github/workflows/codestyle.yml
@@ -8,9 +8,15 @@
 
     steps:
       - uses: actions/checkout@v1
-      - uses: icepuma/rust-action@master
+      - name: Install latest nightly
+        uses: actions-rs/toolchain@v1
         with:
-          args: cargo fmt -- --check
+            toolchain: nightly
+            default: true
+            target: wasm32-unknown-unknown
+            components: rustfmt, clippy
+      - name: Run cargo fmt
+        run: cargo fmt -- --check
 
   clippy:
     runs-on: ubuntu-20.04
@@ -19,6 +25,12 @@
       - uses: actions/checkout@v1
       - name: Install substrate dependencies
         run: sudo apt-get install libssl-dev pkg-config libclang-dev clang
-      - uses: icepuma/rust-action@master
+      - name: Install latest nightly
+        uses: actions-rs/toolchain@v1
         with:
-          args: cargo clippy -- -Dwarnings
\ No newline at end of file
+            toolchain: nightly
+            default: true
+            target: wasm32-unknown-unknown
+            components: rustfmt, clippy
+      - name: Run cargo check
+        run: cargo clippy -- -Dwarnings
modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5996,34 +5996,34 @@
 [[package]]
 name = "pallet-scheduler"
 version = "3.0.0"
-source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
  "frame-system",
  "log",
  "parity-scale-codec 2.1.3",
+ "serde",
+ "sp-core",
  "sp-io",
  "sp-runtime",
  "sp-std",
+ "substrate-test-utils",
+ "up-sponsorship",
 ]
 
 [[package]]
 name = "pallet-scheduler"
 version = "3.0.0"
+source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
  "frame-system",
  "log",
  "parity-scale-codec 2.1.3",
- "serde",
- "sp-core",
  "sp-io",
  "sp-runtime",
  "sp-std",
- "substrate-test-utils",
- "up-sponsorship",
 ]
 
 [[package]]
modifiedcrates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -264,7 +264,7 @@
 			ReturnType::Type(_, ty) => ty,
 			_ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),
 		};
-		let result = parse_result_ok(&result)?;
+		let result = parse_result_ok(result)?;
 
 		let camel_name = info
 			.rename_selector
@@ -285,8 +285,8 @@
 		Ok(Self {
 			name: ident.clone(),
 			camel_name,
-			pascal_name: snake_ident_to_pascal(&ident),
-			screaming_name: snake_ident_to_screaming(&ident),
+			pascal_name: snake_ident_to_pascal(ident),
+			screaming_name: snake_ident_to_screaming(ident),
 			selector_str,
 			selector,
 			args,
@@ -433,7 +433,7 @@
 						found_error = true;
 					}
 				}
-				TraitItem::Method(method) => methods.push(Method::try_from(&method)?),
+				TraitItem::Method(method) => methods.push(Method::try_from(method)?),
 				_ => {}
 			}
 		}
modifiedcrates/evm-coder-macros/src/to_log.rsdiffbeforeafterboth
--- a/crates/evm-coder-macros/src/to_log.rs
+++ b/crates/evm-coder-macros/src/to_log.rs
@@ -41,7 +41,7 @@
 impl Event {
 	fn try_from(variant: &Variant) -> syn::Result<Self> {
 		let name = &variant.ident;
-		let name_screaming = snake_ident_to_screaming(&name);
+		let name_screaming = snake_ident_to_screaming(name);
 
 		let named = match &variant.fields {
 			Fields::Named(named) => named,
@@ -54,7 +54,7 @@
 		};
 		let mut fields = Vec::new();
 		for field in &named.named {
-			fields.push(EventField::try_from(&field)?);
+			fields.push(EventField::try_from(field)?);
 		}
 		let mut selector_str = format!("{}(", name);
 		for (i, arg) in fields.iter().enumerate() {
modifiedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -104,7 +104,7 @@
 	fn subresult(&mut self) -> Result<AbiReader<'i>> {
 		let offset = self.read_usize()?;
 		Ok(AbiReader {
-			buf: &self.buf,
+			buf: self.buf,
 			offset: offset + self.offset,
 		})
 	}
@@ -252,7 +252,7 @@
 impl_abi_writeable!(&str, string);
 impl AbiWrite for &string {
 	fn abi_write(&self, writer: &mut AbiWriter) {
-		writer.string(&self)
+		writer.string(self)
 	}
 }
 
modifiednode/cli/src/cli.rsdiffbeforeafterboth
--- a/node/cli/src/cli.rs
+++ b/node/cli/src/cli.rs
@@ -1,6 +1,4 @@
 use crate::chain_spec;
-use cumulus_client_cli;
-use sc_cli;
 use std::path::PathBuf;
 use structopt::StructOpt;
 
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -120,8 +120,7 @@
 	}
 
 	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
-		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter())
-			.load_spec(id)
+		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
 	}
 
 	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
@@ -129,6 +128,7 @@
 	}
 }
 
+#[allow(clippy::borrowed_box)]
 fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {
 	let mut storage = chain_spec.build_storage()?;
 
@@ -189,7 +189,7 @@
 			runner.sync_run(|config| {
 				let polkadot_cli = RelayChainCli::new(
 					&config,
-					[RelayChainCli::executable_name().to_string()]
+					[RelayChainCli::executable_name()]
 						.iter()
 						.chain(cli.relaychain_args.iter()),
 				);
@@ -275,7 +275,7 @@
 
 				let polkadot_cli = RelayChainCli::new(
 					&config,
-					[RelayChainCli::executable_name().to_string()]
+					[RelayChainCli::executable_name()]
 						.iter()
 						.chain(cli.relaychain_args.iter()),
 				);
modifiednode/cli/src/service.rsdiffbeforeafterboth
--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -141,7 +141,7 @@
 
 	let (client, backend, keystore_container, task_manager) =
 		sc_service::new_full_parts::<Block, RuntimeApi, Executor>(
-			&config,
+			config,
 			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
 		)?;
 	let client = Arc::new(client);
modifiedpallets/contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/contract-helpers/src/lib.rs
+++ b/pallets/contract-helpers/src/lib.rs
@@ -213,7 +213,7 @@
 					Ok(Some((who.clone(), *code_hash, salt.clone())))
 				}
 				Some(pallet_contracts::Call::instantiate_with_code(_, _, code, _, salt)) => {
-					let code_hash = &T::Hashing::hash(&code);
+					let code_hash = &T::Hashing::hash(code);
 					Ok(Some((who.clone(), *code_hash, salt.clone())))
 				}
 				_ => Ok(None),
modifiedpallets/nft/src/eth/erc_impl.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/erc_impl.rs
+++ b/pallets/nft/src/eth/erc_impl.rs
@@ -114,7 +114,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;
 
-		<Module<T>>::transfer_from_internal(&caller, &from, &to, &self, token_id, 1)
+		<Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)
 			.map_err(|_| "transferFrom error")?;
 		Ok(())
 	}
@@ -130,7 +130,7 @@
 		let approved = T::CrossAccountId::from_eth(approved);
 		let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;
 
-		<Module<T>>::approve_internal(&caller, &approved, &self, token_id, 1)
+		<Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)
 			.map_err(|_| "approve internal")?;
 		Ok(())
 	}
@@ -176,7 +176,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id = token_id.try_into().map_err(|_| "amount overflow")?;
 
-		<Module<T>>::transfer_internal(&caller, &to, &self, token_id, 1)
+		<Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)
 			.map_err(|_| "transfer error")?;
 		Ok(())
 	}
@@ -226,7 +226,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		<Module<T>>::transfer_internal(&caller, &to, &self, 1, amount)
+		<Module<T>>::transfer_internal(&caller, &to, self, 1, amount)
 			.map_err(|_| "transfer error")?;
 		Ok(true)
 	}
@@ -242,7 +242,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		<Module<T>>::transfer_from_internal(&caller, &from, &to, &self, 1, amount)
+		<Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)
 			.map_err(|_| "transferFrom error")?;
 		Ok(true)
 	}
@@ -251,7 +251,7 @@
 		let spender = T::CrossAccountId::from_eth(spender);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		<Module<T>>::approve_internal(&caller, &spender, &self, 1, amount)
+		<Module<T>>::approve_internal(&caller, &spender, self, 1, amount)
 			.map_err(|_| "approve internal")?;
 		Ok(true)
 	}
modifiedpallets/nft/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/mod.rs
+++ b/pallets/nft/src/eth/mod.rs
@@ -108,7 +108,7 @@
 			.unwrap_or(false)
 	}
 	fn get_code(target: &H160) -> Option<Vec<u8>> {
-		map_eth_to_id(&target)
+		map_eth_to_id(target)
 			.and_then(<CollectionById<T>>::get)
 			.map(|collection| {
 				match collection.mode {
@@ -127,7 +127,7 @@
 		input: &[u8],
 		value: U256,
 	) -> Option<PrecompileOutput> {
-		let mut collection = map_eth_to_id(&target)
+		let mut collection = map_eth_to_id(target)
 			.and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;
 		let (method_id, input) = AbiReader::new_call(input).unwrap();
 		let result = call_internal(&mut collection, *source, method_id, input, value);
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -132,10 +132,10 @@
 	) -> Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
 		let mut who_pays_fee = *who;
 		if let WithdrawReason::Call { target, input } = &reason {
-			if let Some(collection_id) = crate::eth::map_eth_to_id(&target) {
+			if let Some(collection_id) = crate::eth::map_eth_to_id(target) {
 				if let Some(collection) = <CollectionById<T>>::get(collection_id) {
 					if let Some(sponsor) = collection.sponsorship.sponsor() {
-						if try_sponsor(who, collection_id, &collection, &input).is_ok() {
+						if try_sponsor(who, collection_id, &collection, input).is_ok() {
 							who_pays_fee =
 								T::EvmBackwardsAddressMapping::from_account_id(sponsor.clone());
 						}
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -1232,7 +1232,7 @@
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = Self::get_collection(collection_id)?;
-			Self::check_owner_permissions(&target_collection, &sender.as_sub())?;
+			Self::check_owner_permissions(&target_collection, sender.as_sub())?;
 			let old_limits = &target_collection.limits;
 			let chain_limits = ChainLimit::get();
 
@@ -1267,9 +1267,9 @@
 		owner: &T::CrossAccountId,
 		data: CreateItemData,
 	) -> DispatchResult {
-		Self::can_create_items_in_collection(&collection, &sender, &owner, 1)?;
-		Self::validate_create_item_args(&collection, &data)?;
-		Self::create_item_no_validation(&collection, owner, data)?;
+		Self::can_create_items_in_collection(collection, sender, owner, 1)?;
+		Self::validate_create_item_args(collection, &data)?;
+		Self::create_item_no_validation(collection, owner, data)?;
 
 		Ok(())
 	}
@@ -1283,18 +1283,18 @@
 	) -> DispatchResult {
 		target_collection.consume_gas(2000000)?;
 		// Limits check
-		Self::is_correct_transfer(target_collection, &recipient)?;
+		Self::is_correct_transfer(target_collection, recipient)?;
 
 		// Transfer permissions check
 		ensure!(
-			Self::is_item_owner(&sender, target_collection, item_id)
-				|| Self::is_owner_or_admin_permissions(target_collection, &sender),
+			Self::is_item_owner(sender, target_collection, item_id)
+				|| Self::is_owner_or_admin_permissions(target_collection, sender),
 			Error::<T>::NoPermission
 		);
 
 		if target_collection.access == AccessMode::WhiteList {
-			Self::check_white_list(target_collection, &sender)?;
-			Self::check_white_list(target_collection, &recipient)?;
+			Self::check_white_list(target_collection, sender)?;
+			Self::check_white_list(target_collection, recipient)?;
 		}
 
 		match target_collection.mode {
@@ -1305,7 +1305,7 @@
 				recipient.clone(),
 			)?,
 			CollectionMode::Fungible(_) => {
-				Self::transfer_fungible(target_collection, value, &sender, &recipient)?
+				Self::transfer_fungible(target_collection, value, sender, recipient)?
 			}
 			CollectionMode::ReFungible => Self::transfer_refungible(
 				target_collection,
@@ -1336,23 +1336,23 @@
 		amount: u128,
 	) -> DispatchResult {
 		collection.consume_gas(2000000)?;
-		Self::token_exists(&collection, item_id)?;
+		Self::token_exists(collection, item_id)?;
 
 		// Transfer permissions check
 		let bypasses_limits = collection.limits.owner_can_transfer
-			&& Self::is_owner_or_admin_permissions(&collection, &sender);
+			&& Self::is_owner_or_admin_permissions(collection, sender);
 
 		let allowance_limit = if bypasses_limits {
 			None
-		} else if let Some(amount) = Self::owned_amount(&sender, &collection, item_id) {
+		} else if let Some(amount) = Self::owned_amount(sender, collection, item_id) {
 			Some(amount)
 		} else {
 			fail!(Error::<T>::NoPermission);
 		};
 
 		if collection.access == AccessMode::WhiteList {
-			Self::check_white_list(&collection, &sender)?;
-			Self::check_white_list(&collection, &spender)?;
+			Self::check_white_list(collection, sender)?;
+			Self::check_white_list(collection, spender)?;
 		}
 
 		let allowance: u128 = amount
@@ -1412,19 +1412,19 @@
 			<Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
 
 		// Limits check
-		Self::is_correct_transfer(&collection, &recipient)?;
+		Self::is_correct_transfer(collection, recipient)?;
 
 		// Transfer permissions check
 		ensure!(
 			approval >= amount
 				|| (collection.limits.owner_can_transfer
-					&& Self::is_owner_or_admin_permissions(&collection, &sender)),
+					&& Self::is_owner_or_admin_permissions(collection, sender)),
 			Error::<T>::NoPermission
 		);
 
 		if collection.access == AccessMode::WhiteList {
-			Self::check_white_list(&collection, &sender)?;
-			Self::check_white_list(&collection, &recipient)?;
+			Self::check_white_list(collection, sender)?;
+			Self::check_white_list(collection, recipient)?;
 		}
 
 		// Reduce approval by transferred amount or remove if remaining approval drops to 0
@@ -1441,13 +1441,13 @@
 
 		match collection.mode {
 			CollectionMode::NFT => {
-				Self::transfer_nft(&collection, item_id, from.clone(), recipient.clone())?
+				Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?
 			}
 			CollectionMode::Fungible(_) => {
-				Self::transfer_fungible(&collection, amount, &from, &recipient)?
+				Self::transfer_fungible(collection, amount, from, recipient)?
 			}
 			CollectionMode::ReFungible => Self::transfer_refungible(
-				&collection,
+				collection,
 				item_id,
 				amount,
 				from.clone(),
@@ -1473,7 +1473,7 @@
 		item_id: TokenId,
 		data: Vec<u8>,
 	) -> DispatchResult {
-		Self::token_exists(&collection, item_id)?;
+		Self::token_exists(collection, item_id)?;
 
 		ensure!(
 			ChainLimit::get().custom_data_limit >= data.len() as u32,
@@ -1482,15 +1482,15 @@
 
 		// Modify permissions check
 		ensure!(
-			Self::is_item_owner(&sender, &collection, item_id)
-				|| Self::is_owner_or_admin_permissions(&collection, &sender),
+			Self::is_item_owner(sender, collection, item_id)
+				|| Self::is_owner_or_admin_permissions(collection, sender),
 			Error::<T>::NoPermission
 		);
 
 		match collection.mode {
-			CollectionMode::NFT => Self::set_nft_variable_data(&collection, item_id, data)?,
+			CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,
 			CollectionMode::ReFungible => {
-				Self::set_re_fungible_variable_data(&collection, item_id, data)?
+				Self::set_re_fungible_variable_data(collection, item_id, data)?
 			}
 			CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
 			_ => fail!(Error::<T>::UnexpectedCollectionType),
@@ -1505,18 +1505,13 @@
 		owner: &T::CrossAccountId,
 		items_data: Vec<CreateItemData>,
 	) -> DispatchResult {
-		Self::can_create_items_in_collection(
-			&collection,
-			&sender,
-			&owner,
-			items_data.len() as u32,
-		)?;
+		Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;
 
 		for data in &items_data {
-			Self::validate_create_item_args(&collection, data)?;
+			Self::validate_create_item_args(collection, data)?;
 		}
 		for data in &items_data {
-			Self::create_item_no_validation(&collection, owner, data.clone())?;
+			Self::create_item_no_validation(collection, owner, data.clone())?;
 		}
 
 		Ok(())
@@ -1529,22 +1524,20 @@
 		value: u128,
 	) -> DispatchResult {
 		ensure!(
-			Self::is_item_owner(&sender, &collection, item_id)
+			Self::is_item_owner(sender, collection, item_id)
 				|| (collection.limits.owner_can_transfer
-					&& Self::is_owner_or_admin_permissions(&collection, &sender)),
+					&& Self::is_owner_or_admin_permissions(collection, sender)),
 			Error::<T>::NoPermission
 		);
 
 		if collection.access == AccessMode::WhiteList {
-			Self::check_white_list(&collection, &sender)?;
+			Self::check_white_list(collection, sender)?;
 		}
 
 		match collection.mode {
-			CollectionMode::NFT => Self::burn_nft_item(&collection, item_id)?,
-			CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, &collection, value)?,
-			CollectionMode::ReFungible => {
-				Self::burn_refungible_item(&collection, item_id, &sender)?
-			}
+			CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,
+			CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,
+			CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,
 			_ => (),
 		};
 
@@ -1557,7 +1550,7 @@
 		address: &T::CrossAccountId,
 		whitelisted: bool,
 	) -> DispatchResult {
-		Self::check_owner_or_admin_permissions(&collection, &sender)?;
+		Self::check_owner_or_admin_permissions(collection, sender)?;
 
 		if whitelisted {
 			<WhiteList<T>>::insert(collection.id, address.as_sub(), true);
@@ -1610,7 +1603,7 @@
 			Error::<T>::AccountTokenLimitExceeded
 		);
 
-		if !Self::is_owner_or_admin_permissions(collection, &sender) {
+		if !Self::is_owner_or_admin_permissions(collection, sender) {
 			ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);
 			Self::check_white_list(collection, owner)?;
 			Self::check_white_list(collection, sender)?;
@@ -1691,7 +1684,7 @@
 				Self::add_nft_item(collection, item)?;
 			}
 			CreateItemData::Fungible(data) => {
-				Self::add_fungible_item(collection, &owner, data.value)?;
+				Self::add_fungible_item(collection, owner, data.value)?;
 			}
 			CreateItemData::ReFungible(data) => {
 				let owner_list = vec![Ownership {
@@ -1934,7 +1927,7 @@
 		subject: &T::CrossAccountId,
 	) -> bool {
 		*subject.as_sub() == collection.owner
-			|| <AdminList<T>>::get(collection.id).contains(&subject)
+			|| <AdminList<T>>::get(collection.id).contains(subject)
 	}
 
 	fn check_owner_or_admin_permissions(
@@ -1979,7 +1972,7 @@
 	) -> bool {
 		match target_collection.mode {
 			CollectionMode::Fungible(_) => true,
-			_ => Self::owned_amount(&subject, target_collection, item_id).is_some(),
+			_ => Self::owned_amount(subject, target_collection, item_id).is_some(),
 		}
 	}
 
modifiedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
before · pallets/nft/src/sponsorship.rs
1use crate::{2	Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,3	ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit,4	CreateItemData, CollectionMode,5};6use core::marker::PhantomData;7use up_sponsorship::SponsorshipHandler;8use frame_support::{9	traits::IsSubType,10	storage::{StorageMap, StorageDoubleMap, StorageValue},11};12use nft_data_structs::{TokenId, CollectionId};1314pub struct NftSponsorshipHandler<T>(PhantomData<T>);15impl<T: Config> NftSponsorshipHandler<T> {16	pub fn withdraw_create_item(17		who: &T::AccountId,18		collection_id: &CollectionId,19		_properties: &CreateItemData,20	) -> Option<T::AccountId> {21		let collection = CollectionById::<T>::get(collection_id)?;2223		// sponsor timeout24		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;2526		let limit = collection.limits.sponsor_transfer_timeout;27		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {28			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));29			let limit_time = last_tx_block + limit.into();30			if block_number <= limit_time {31				return None;32			}33		}34		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);3536		// check free create limit37		if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {38			collection.sponsorship.sponsor().cloned()39		} else {40			None41		}42	}4344	pub fn withdraw_transfer(45		who: &T::AccountId,46		collection_id: &CollectionId,47		item_id: &TokenId,48	) -> Option<T::AccountId> {49		let collection = CollectionById::<T>::get(collection_id)?;50		let limits = ChainLimit::get();5152		let mut sponsor_transfer = false;53		if collection.sponsorship.confirmed() {54			let collection_limits = collection.limits.clone();55			let collection_mode = collection.mode.clone();5657			// sponsor timeout58			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;59			sponsor_transfer = match collection_mode {60				CollectionMode::NFT => {61					// get correct limit62					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {63						collection_limits.sponsor_transfer_timeout64					} else {65						limits.nft_sponsor_transfer_timeout66					};6768					let mut sponsored = true;69					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {70						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);71						let limit_time = last_tx_block + limit.into();72						if block_number <= limit_time {73							sponsored = false;74						}75					}76					if sponsored {77						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);78					}7980					sponsored81				}82				CollectionMode::Fungible(_) => {83					// get correct limit84					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {85						collection_limits.sponsor_transfer_timeout86					} else {87						limits.fungible_sponsor_transfer_timeout88					};8990					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;91					let mut sponsored = true;92					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {93						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);94						let limit_time = last_tx_block + limit.into();95						if block_number <= limit_time {96							sponsored = false;97						}98					}99					if sponsored {100						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);101					}102103					sponsored104				}105				CollectionMode::ReFungible => {106					// get correct limit107					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {108						collection_limits.sponsor_transfer_timeout109					} else {110						limits.refungible_sponsor_transfer_timeout111					};112113					let mut sponsored = true;114					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {115						let last_tx_block =116							ReFungibleTransferBasket::<T>::get(collection_id, item_id);117						let limit_time = last_tx_block + limit.into();118						if block_number <= limit_time {119							sponsored = false;120						}121					}122					if sponsored {123						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);124					}125126					sponsored127				}128				_ => false,129			};130		}131132		if !sponsor_transfer {133			None134		} else {135			collection.sponsorship.sponsor().cloned()136		}137	}138139	pub fn withdraw_set_variable_meta_data(140		collection_id: &CollectionId,141		item_id: &TokenId,142		data: &[u8],143	) -> Option<T::AccountId> {144		let mut sponsor_metadata_changes = false;145146		let collection = CollectionById::<T>::get(collection_id)?;147148		if collection.sponsorship.confirmed() &&149			// Can't sponsor fungible collection, this tx will be rejected150			// as invalid151			!matches!(collection.mode, CollectionMode::Fungible(_)) &&152			data.len() <= collection.limits.sponsored_data_size as usize153		{154			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {155				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;156157				if VariableMetaDataBasket::<T>::get(collection_id, item_id)158					.map(|last_block| block_number - last_block > rate_limit)159					.unwrap_or(true)160				{161					sponsor_metadata_changes = true;162					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);163				}164			}165		}166167		if !sponsor_metadata_changes {168			None169		} else {170			collection.sponsorship.sponsor().cloned()171		}172	}173}174175impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>176where177	T: Config,178	C: IsSubType<Call<T>>,179{180	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {181		match IsSubType::<Call<T>>::is_sub_type(call)? {182			Call::create_item(collection_id, _owner, _properties) => {183				Self::withdraw_create_item(who, collection_id, &_properties)184			}185			Call::transfer(_new_owner, collection_id, item_id, _value) => {186				Self::withdraw_transfer(who, collection_id, item_id)187			}188			Call::set_variable_meta_data(collection_id, item_id, data) => {189				Self::withdraw_set_variable_meta_data(collection_id, item_id, &data)190			}191			_ => None,192		}193	}194}
after · pallets/nft/src/sponsorship.rs
1use crate::{2	Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,3	ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit,4	CreateItemData, CollectionMode,5};6use core::marker::PhantomData;7use up_sponsorship::SponsorshipHandler;8use frame_support::{9	traits::IsSubType,10	storage::{StorageMap, StorageDoubleMap, StorageValue},11};12use nft_data_structs::{TokenId, CollectionId};1314pub struct NftSponsorshipHandler<T>(PhantomData<T>);15impl<T: Config> NftSponsorshipHandler<T> {16	pub fn withdraw_create_item(17		who: &T::AccountId,18		collection_id: &CollectionId,19		_properties: &CreateItemData,20	) -> Option<T::AccountId> {21		let collection = CollectionById::<T>::get(collection_id)?;2223		// sponsor timeout24		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;2526		let limit = collection.limits.sponsor_transfer_timeout;27		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {28			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));29			let limit_time = last_tx_block + limit.into();30			if block_number <= limit_time {31				return None;32			}33		}34		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);3536		// check free create limit37		if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {38			collection.sponsorship.sponsor().cloned()39		} else {40			None41		}42	}4344	pub fn withdraw_transfer(45		who: &T::AccountId,46		collection_id: &CollectionId,47		item_id: &TokenId,48	) -> Option<T::AccountId> {49		let collection = CollectionById::<T>::get(collection_id)?;50		let limits = ChainLimit::get();5152		let mut sponsor_transfer = false;53		if collection.sponsorship.confirmed() {54			let collection_limits = collection.limits.clone();55			let collection_mode = collection.mode.clone();5657			// sponsor timeout58			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;59			sponsor_transfer = match collection_mode {60				CollectionMode::NFT => {61					// get correct limit62					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {63						collection_limits.sponsor_transfer_timeout64					} else {65						limits.nft_sponsor_transfer_timeout66					};6768					let mut sponsored = true;69					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {70						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);71						let limit_time = last_tx_block + limit.into();72						if block_number <= limit_time {73							sponsored = false;74						}75					}76					if sponsored {77						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);78					}7980					sponsored81				}82				CollectionMode::Fungible(_) => {83					// get correct limit84					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {85						collection_limits.sponsor_transfer_timeout86					} else {87						limits.fungible_sponsor_transfer_timeout88					};8990					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;91					let mut sponsored = true;92					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {93						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);94						let limit_time = last_tx_block + limit.into();95						if block_number <= limit_time {96							sponsored = false;97						}98					}99					if sponsored {100						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);101					}102103					sponsored104				}105				CollectionMode::ReFungible => {106					// get correct limit107					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {108						collection_limits.sponsor_transfer_timeout109					} else {110						limits.refungible_sponsor_transfer_timeout111					};112113					let mut sponsored = true;114					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {115						let last_tx_block =116							ReFungibleTransferBasket::<T>::get(collection_id, item_id);117						let limit_time = last_tx_block + limit.into();118						if block_number <= limit_time {119							sponsored = false;120						}121					}122					if sponsored {123						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);124					}125126					sponsored127				}128				_ => false,129			};130		}131132		if !sponsor_transfer {133			None134		} else {135			collection.sponsorship.sponsor().cloned()136		}137	}138139	pub fn withdraw_set_variable_meta_data(140		collection_id: &CollectionId,141		item_id: &TokenId,142		data: &[u8],143	) -> Option<T::AccountId> {144		let mut sponsor_metadata_changes = false;145146		let collection = CollectionById::<T>::get(collection_id)?;147148		if collection.sponsorship.confirmed() &&149			// Can't sponsor fungible collection, this tx will be rejected150			// as invalid151			!matches!(collection.mode, CollectionMode::Fungible(_)) &&152			data.len() <= collection.limits.sponsored_data_size as usize153		{154			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {155				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;156157				if VariableMetaDataBasket::<T>::get(collection_id, item_id)158					.map(|last_block| block_number - last_block > rate_limit)159					.unwrap_or(true)160				{161					sponsor_metadata_changes = true;162					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);163				}164			}165		}166167		if !sponsor_metadata_changes {168			None169		} else {170			collection.sponsorship.sponsor().cloned()171		}172	}173}174175impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>176where177	T: Config,178	C: IsSubType<Call<T>>,179{180	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {181		match IsSubType::<Call<T>>::is_sub_type(call)? {182			Call::create_item(collection_id, _owner, properties) => {183				Self::withdraw_create_item(who, collection_id, properties)184			}185			Call::transfer(_new_owner, collection_id, item_id, _value) => {186				Self::withdraw_transfer(who, collection_id, item_id)187			}188			Call::set_variable_meta_data(collection_id, item_id, data) => {189				Self::withdraw_set_variable_meta_data(collection_id, item_id, data)190			}191			_ => None,192		}193	}194}