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

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2021-11-26parent: #d1696cc.patch.diff
in: master

26 files changed

modified.maintain/frame-weight-template.hbsdiffbeforeafterboth
--- a/.maintain/frame-weight-template.hbs
+++ b/.maintain/frame-weight-template.hbs
@@ -14,6 +14,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -57,9 +57,5 @@
 bench-nonfungible:
 	make _bench PALLET=nonfungible
 
-.PHONY: bench-evm-coder-substrate
-bench-evm-coder-substrate:
-	make _bench PALLET=evm-coder-substrate
-
 .PHONY: bench
-bench: bench-evm-migration bench-nft bench-fungible bench-refungible bench-nonfungible bench-evm-coder-substrate
+bench: bench-evm-migration bench-nft bench-fungible bench-refungible bench-nonfungible
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
@@ -226,16 +226,10 @@
 		}
 	}
 	fn is_value(&self) -> bool {
-		match self {
-			Self::Plain(v) if v == "value" => true,
-			_ => false,
-		}
+		matches!(self, Self::Plain(v) if v == "value")
 	}
 	fn is_caller(&self) -> bool {
-		match self {
-			Self::Plain(v) if v == "caller" => true,
-			_ => false,
-		}
+		matches!(self, Self::Plain(v) if v == "caller")
 	}
 	fn is_special(&self) -> bool {
 		self.is_caller() || self.is_value()
@@ -599,7 +593,7 @@
 						#args,
 					)*
 				)?;
-				(&result).into_result()
+				(&result).to_result()
 			}
 		}
 	}
modifiedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -310,7 +310,7 @@
 
 pub trait AbiWrite {
 	fn abi_write(&self, writer: &mut AbiWriter);
-	fn into_result(&self) -> ResultWithPostInfo<AbiWriter> {
+	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
 		let mut writer = AbiWriter::new();
 		self.abi_write(&mut writer);
 		Ok(writer.into())
@@ -319,7 +319,7 @@
 
 impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
 	// this particular AbiWrite implementation should be split to another trait,
-	// which only implements [`into_result`]
+	// which only implements [`to_result`]
 	//
 	// But due to lack of specialization feature in stable Rust, we can't have
 	// blanket impl of this trait `for T where T: AbiWrite`, so here we abusing
@@ -327,7 +327,7 @@
 	fn abi_write(&self, _writer: &mut AbiWriter) {
 		debug_assert!(false, "shouldn't be called, see comment")
 	}
-	fn into_result(&self) -> ResultWithPostInfo<AbiWriter> {
+	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
 		match self {
 			Ok(v) => Ok(WithPostDispatchInfo {
 				post_info: v.post_info.clone(),
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -214,7 +214,7 @@
 			500_usize, // max stored filters
 			overrides.clone(),
 			max_past_logs,
-			block_data_cache.clone(),
+			block_data_cache,
 		)));
 	}
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -51,7 +51,7 @@
 		Self::new_with_gas_limit(id, u64::MAX)
 	}
 	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {
-		Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)
+		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)
 	}
 	pub fn log(&self, log: impl evm_coder::ToLog) {
 		self.recorder.log(log)
@@ -453,7 +453,7 @@
 			collection.limits.owner_can_destroy(),
 			<Error<T>>::NoPermission,
 		);
-		collection.check_is_owner(&sender)?;
+		collection.check_is_owner(sender)?;
 
 		let destroyed_collections = <DestroyedCollectionCount<T>>::get()
 			.0
@@ -476,7 +476,7 @@
 		user: &T::CrossAccountId,
 		allowed: bool,
 	) -> DispatchResult {
-		collection.check_is_owner_or_admin(&sender)?;
+		collection.check_is_owner_or_admin(sender)?;
 
 		// =========
 
@@ -495,7 +495,7 @@
 		user: &T::CrossAccountId,
 		admin: bool,
 	) -> DispatchResult {
-		collection.check_is_owner_or_admin(&sender)?;
+		collection.check_is_owner_or_admin(sender)?;
 
 		let was_admin = <IsAdmin<T>>::get((collection.id, user));
 		if was_admin == admin {
modifiedpallets/evm-contract-helpers/exp.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/exp.rs
+++ b/pallets/evm-contract-helpers/exp.rs
@@ -532,11 +532,11 @@
             match c.call {
                 InternalCall::ContractOwner { contract_address } => {
                     let result = self.contract_owner(contract_address)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::SponsoringEnabled { contract_address } => {
                     let result = self.sponsoring_enabled(contract_address)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::ToggleSponsoring {
                     contract_address,
@@ -544,7 +544,7 @@
                 } => {
                     let result =
                         self.toggle_sponsoring(c.caller.clone(), contract_address, enabled)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::SetSponsoringRateLimit {
                     contract_address,
@@ -555,22 +555,22 @@
                         contract_address,
                         rate_limit,
                     )?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::GetSponsoringRateLimit { contract_address } => {
                     let result = self.get_sponsoring_rate_limit(contract_address)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::Allowed {
                     contract_address,
                     user,
                 } => {
                     let result = self.allowed(contract_address, user)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::AllowlistEnabled { contract_address } => {
                     let result = self.allowlist_enabled(contract_address)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::ToggleAllowlist {
                     contract_address,
@@ -578,7 +578,7 @@
                 } => {
                     let result =
                         self.toggle_allowlist(c.caller.clone(), contract_address, enabled)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 InternalCall::ToggleAllowed {
                     contract_address,
@@ -587,7 +587,7 @@
                 } => {
                     let result =
                         self.toggle_allowed(c.caller.clone(), contract_address, user, allowed)?;
-                    (&result).into_result()
+                    (&result).to_result()
                 }
                 _ => ::core::panicking::panic("internal error: entered unreachable code"),
             }
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -1,10 +1,7 @@
 use core::marker::PhantomData;
 use evm_coder::{abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use pallet_evm::{
-	ExitReason, ExitRevert, OnCreate, OnMethodCall, PrecompileOutput, PrecompileResult,
-	PrecompileFailure,
-};
+use pallet_evm::{ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure};
 use sp_core::H160;
 use crate::{
 	AllowlistEnabled, Config, Owner, Pallet, SelfSponsoring, SponsorBasket, SponsoringRateLimit,
@@ -161,7 +158,7 @@
 		if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {
 			let limit = <SponsoringRateLimit<T>>::get(&call.0);
 
-			let timeout = last_tx_block + limit.into();
+			let timeout = last_tx_block + limit;
 			if block_number < timeout {
 				return None;
 			}
modifiedpallets/evm-migration/src/weights.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/weights.rs
+++ b/pallets/evm-migration/src/weights.rs
@@ -25,6 +25,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
modifiedpallets/evm-transaction-payment/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-transaction-payment/src/lib.rs
+++ b/pallets/evm-transaction-payment/src/lib.rs
@@ -128,7 +128,7 @@
 				let sponsor = frame_support::storage::with_transaction(|| {
 					TransactionOutcome::Rollback(T::EvmSponsorshipHandler::get_sponsor(
 						&who,
-						&(target.clone(), input.clone()),
+						&(*target, input.clone()),
 					))
 				})?;
 				let sponsor = T::EvmAddressMapping::into_account_id(sponsor);
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -116,7 +116,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::transfer(&self, &from, &to, amount),
+			<Pallet<T>>::transfer(self, &from, &to, amount),
 			<CommonWeights<T>>::transfer(),
 		)
 	}
@@ -134,7 +134,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::set_allowance(&self, &sender, &spender, amount),
+			<Pallet<T>>::set_allowance(self, &sender, &spender, amount),
 			<CommonWeights<T>>::approve(),
 		)
 	}
@@ -153,7 +153,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::transfer_from(&self, &sender, &from, &to, amount),
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount),
 			<CommonWeights<T>>::transfer_from(),
 		)
 	}
@@ -171,7 +171,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::burn_from(&self, &sender, &from, amount),
+			<Pallet<T>>::burn_from(self, &sender, &from, amount),
 			<CommonWeights<T>>::burn_from(),
 		)
 	}
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -6,7 +6,6 @@
 use sp_core::{H160, U256};
 use sp_std::vec::Vec;
 use pallet_common::account::CrossAccountId;
-use pallet_common::erc::PrecompileOutput;
 use pallet_evm_coder_substrate::{call, dispatch_to_evm};
 
 use crate::{
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -303,8 +303,8 @@
 		amount: u128,
 	) -> DispatchResult {
 		if collection.access == AccessMode::AllowList {
-			collection.check_allowlist(&owner)?;
-			collection.check_allowlist(&spender)?;
+			collection.check_allowlist(owner)?;
+			collection.check_allowlist(spender)?;
 		}
 
 		if <Balance<T>>::get((collection.id, owner)) < amount {
modifiedpallets/fungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -25,6 +25,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
@@ -32,11 +33,11 @@
 /// Weight functions needed for pallet_fungible.
 pub trait WeightInfo {
 	fn create_item() -> Weight;
-	fn burn_from() -> Weight;
 	fn burn_item() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
+	fn burn_from() -> Weight;
 }
 
 /// Weights for pallet_fungible using the Substrate node and recommended hardware.
modifiedpallets/nft/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nft/src/benchmarking.rs
+++ b/pallets/nft/src/benchmarking.rs
@@ -158,6 +158,7 @@
 			sponsored_data_size: Some(0),
 			token_limit: Some(1),
 			sponsor_transfer_timeout: Some(0),
+			sponsor_approve_timeout: None,
 			owner_can_destroy: Some(true),
 			owner_can_transfer: Some(true),
 			sponsored_data_rate_limit: None,
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -195,7 +195,7 @@
 
 			// Create new collection
 			let new_collection = Collection {
-				owner: who.clone(),
+				owner: who,
 				name: collection_name,
 				mode: mode.clone(),
 				mint_mode: false,
modifiedpallets/nft/src/weights.rsdiffbeforeafterboth
--- a/pallets/nft/src/weights.rs
+++ b/pallets/nft/src/weights.rs
@@ -25,6 +25,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -100,7 +100,7 @@
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::burn(&self, &sender, token),
+				<Pallet<T>>::burn(self, &sender, token),
 				<CommonWeights<T>>::burn_item(),
 			)
 		} else {
@@ -118,7 +118,7 @@
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::transfer(&self, &from, &to, token),
+				<Pallet<T>>::transfer(self, &from, &to, token),
 				<CommonWeights<T>>::transfer(),
 			)
 		} else {
@@ -137,9 +137,9 @@
 
 		with_weight(
 			if amount == 1 {
-				<Pallet<T>>::set_allowance(&self, &sender, token, Some(&spender))
+				<Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))
 			} else {
-				<Pallet<T>>::set_allowance(&self, &sender, token, None)
+				<Pallet<T>>::set_allowance(self, &sender, token, None)
 			},
 			<CommonWeights<T>>::approve(),
 		)
@@ -157,7 +157,7 @@
 
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::transfer_from(&self, &sender, &from, &to, token),
+				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token),
 				<CommonWeights<T>>::transfer_from(),
 			)
 		} else {
@@ -176,7 +176,7 @@
 
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::burn_from(&self, &sender, &from, token),
+				<Pallet<T>>::burn_from(self, &sender, &from, token),
 				<CommonWeights<T>>::burn_from(),
 			)
 		} else {
@@ -192,7 +192,7 @@
 	) -> DispatchResultWithPostInfo {
 		let len = data.len();
 		with_weight(
-			<Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
+			<Pallet<T>>::set_variable_metadata(self, &sender, token, data),
 			<CommonWeights<T>>::set_variable_metadata(len as u32),
 		)
 	}
@@ -218,12 +218,12 @@
 	}
 	fn const_metadata(&self, token: TokenId) -> Vec<u8> {
 		<TokenData<T>>::get((self.id, token))
-			.map(|t| t.const_data.clone())
+			.map(|t| t.const_data)
 			.unwrap_or_default()
 	}
 	fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
 		<TokenData<T>>::get((self.id, token))
-			.map(|t| t.variable_data.clone())
+			.map(|t| t.variable_data)
 			.unwrap_or_default()
 	}
 
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -13,7 +13,6 @@
 	erc::{CommonEvmHandler, PrecompileResult},
 };
 use pallet_evm_coder_substrate::call;
-use pallet_common::erc::PrecompileOutput;
 
 use crate::{
 	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -169,8 +169,8 @@
 		sender: &T::CrossAccountId,
 		token: TokenId,
 	) -> DispatchResult {
-		let token_data = <TokenData<T>>::get((collection.id, token))
-			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
+		let token_data =
+			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
 		ensure!(
 			&token_data.owner == sender
 				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),
@@ -197,7 +197,7 @@
 				collection.id,
 				token,
 				sender.clone(),
-				old_spender.clone(),
+				old_spender,
 				0,
 			));
 		}
@@ -213,7 +213,7 @@
 			token_data.owner,
 			1,
 		));
-		return Ok(());
+		Ok(())
 	}
 
 	pub fn transfer(
@@ -227,8 +227,8 @@
 			<CommonError<T>>::TransferNotAllowed
 		);
 
-		let token_data = <TokenData<T>>::get((collection.id, token))
-			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
+		let token_data =
+			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
 		ensure!(
 			&token_data.owner == from
 				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),
@@ -399,7 +399,7 @@
 						collection.id,
 						token,
 						sender.clone(),
-						old_owner.clone(),
+						old_owner,
 						0,
 					));
 				}
@@ -429,7 +429,7 @@
 					collection.id,
 					token,
 					sender.clone(),
-					old_spender.clone(),
+					old_spender,
 					0,
 				));
 			}
@@ -443,9 +443,9 @@
 		spender: Option<&T::CrossAccountId>,
 	) -> DispatchResult {
 		if collection.access == AccessMode::AllowList {
-			collection.check_allowlist(&sender)?;
+			collection.check_allowlist(sender)?;
 			if let Some(spender) = spender {
-				collection.check_allowlist(&spender)?;
+				collection.check_allowlist(spender)?;
 			}
 		}
 
@@ -491,7 +491,7 @@
 
 		// =========
 
-		Self::transfer(collection, &from, to, token)?;
+		Self::transfer(collection, from, to, token)?;
 		// Allowance is reset in [`transfer`]
 		Ok(())
 	}
@@ -519,7 +519,7 @@
 
 		// =========
 
-		Self::burn(collection, &from, token)
+		Self::burn(collection, from, token)
 	}
 
 	pub fn set_variable_metadata(
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -25,6 +25,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
@@ -33,11 +34,11 @@
 pub trait WeightInfo {
 	fn create_item() -> Weight;
 	fn create_multiple_items(b: u32, ) -> Weight;
-	fn burn_from() -> Weight;
 	fn burn_item() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
+	fn burn_from() -> Weight;
 	fn set_variable_metadata(b: u32, ) -> Weight;
 }
 
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -135,7 +135,7 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::transfer(&self, &from, &to, token, amount),
+			<Pallet<T>>::transfer(self, &from, &to, token, amount),
 			<CommonWeights<T>>::transfer(),
 		)
 	}
@@ -148,7 +148,7 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::set_allowance(&self, &sender, &spender, token, amount),
+			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),
 			<CommonWeights<T>>::approve(),
 		)
 	}
@@ -162,7 +162,7 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::transfer_from(&self, &sender, &from, &to, token, amount),
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount),
 			<CommonWeights<T>>::transfer_from(),
 		)
 	}
@@ -175,7 +175,7 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::burn_from(&self, &sender, &from, token, amount),
+			<Pallet<T>>::burn_from(self, &sender, &from, token, amount),
 			<CommonWeights<T>>::burn_from(),
 		)
 	}
@@ -188,7 +188,7 @@
 	) -> DispatchResultWithPostInfo {
 		let len = data.len();
 		with_weight(
-			<Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
+			<Pallet<T>>::set_variable_metadata(self, &sender, token, data),
 			<CommonWeights<T>>::set_variable_metadata(len as u32),
 		)
 	}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_data_structs::{5	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6	MAX_REFUNGIBLE_PIECES, TokenId,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24	pub const_data: BoundedVec<u8, CustomDataLimit>,25	pub variable_data: BoundedVec<u8, CustomDataLimit>,26	pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo)]31pub struct ItemData {32	pub const_data: Vec<u8>,33	pub variable_data: Vec<u8>,34}3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40	use nft_data_structs::{CollectionId, TokenId};41	use super::weights::WeightInfo;4243	#[pallet::error]44	pub enum Error<T> {45		/// Not Refungible item data used to mint in Refungible collection.46		NotRefungibleDataUsedToMintFungibleCollectionToken,47		/// Maximum refungibility exceeded48		WrongRefungiblePieces,49	}5051	#[pallet::config]52	pub trait Config: frame_system::Config + pallet_common::Config {53		type WeightInfo: WeightInfo;54	}5556	#[pallet::pallet]57	#[pallet::generate_store(pub trait Store)]58	pub struct Pallet<T>(_);5960	#[pallet::storage]61	pub type TokensMinted<T: Config> =62		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63	#[pallet::storage]64	pub type TokensBurnt<T: Config> =65		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667	#[pallet::storage]68	pub type TokenData<T: Config> = StorageNMap<69		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70		Value = ItemData,71		QueryKind = ValueQuery,72	>;7374	#[pallet::storage]75	pub type TotalSupply<T: Config> = StorageNMap<76		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77		Value = u128,78		QueryKind = ValueQuery,79	>;8081	/// Used to enumerate tokens owned by account82	#[pallet::storage]83	pub type Owned<T: Config> = StorageNMap<84		Key = (85			Key<Twox64Concat, CollectionId>,86			Key<Blake2_128Concat, T::CrossAccountId>,87			Key<Twox64Concat, TokenId>,88		),89		Value = bool,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub type AccountBalance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			// Owner98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u32,101		QueryKind = ValueQuery,102	>;103104	#[pallet::storage]105	pub type Balance<T: Config> = StorageNMap<106		Key = (107			Key<Twox64Concat, CollectionId>,108			Key<Twox64Concat, TokenId>,109			// Owner110			Key<Blake2_128Concat, T::CrossAccountId>,111		),112		Value = u128,113		QueryKind = ValueQuery,114	>;115116	#[pallet::storage]117	pub type Allowance<T: Config> = StorageNMap<118		Key = (119			Key<Twox64Concat, CollectionId>,120			Key<Twox64Concat, TokenId>,121			// Owner122			Key<Blake2_128, T::CrossAccountId>,123			// Spender124			Key<Blake2_128Concat, T::CrossAccountId>,125		),126		Value = u128,127		QueryKind = ValueQuery,128	>;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134		Self(inner)135	}136	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137		self.0138	}139}140impl<T: Config> Deref for RefungibleHandle<T> {141	type Target = pallet_common::CollectionHandle<T>;142143	fn deref(&self) -> &Self::Target {144		&self.0145	}146}147148impl<T: Config> Pallet<T> {149	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151	}152	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153		<TotalSupply<T>>::contains_key((collection.id, token))154	}155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160		<PalletCommon<T>>::init_collection(data)161	}162	pub fn destroy_collection(163		collection: RefungibleHandle<T>,164		sender: &T::CrossAccountId,165	) -> DispatchResult {166		let id = collection.id;167168		// =========169170		PalletCommon::destroy_collection(collection.0, sender)?;171172		<TokensMinted<T>>::remove(id);173		<TokensBurnt<T>>::remove(id);174		<TokenData<T>>::remove_prefix((id,), None);175		<TotalSupply<T>>::remove_prefix((id,), None);176		<Balance<T>>::remove_prefix((id,), None);177		<Allowance<T>>::remove_prefix((id,), None);178		Ok(())179	}180181	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182		let burnt = <TokensBurnt<T>>::get(collection.id)183			.checked_add(1)184			.ok_or(ArithmeticError::Overflow)?;185186		<TokensBurnt<T>>::insert(collection.id, burnt);187		<TokenData<T>>::remove((collection.id, token_id));188		<TotalSupply<T>>::remove((collection.id, token_id));189		<Balance<T>>::remove_prefix((collection.id, token_id), None);190		<Allowance<T>>::remove_prefix((collection.id, token_id), None);191		// TODO: ERC721 transfer event192		return Ok(());193	}194195	pub fn burn(196		collection: &RefungibleHandle<T>,197		owner: &T::CrossAccountId,198		token: TokenId,199		amount: u128,200	) -> DispatchResult {201		let total_supply = <TotalSupply<T>>::get((collection.id, token))202			.checked_sub(amount)203			.ok_or(<CommonError<T>>::TokenValueTooLow)?;204205		// This was probally last owner of this token?206		if total_supply == 0 {207			// Ensure user actually owns this amount208			ensure!(209				<Balance<T>>::get((collection.id, token, owner)) == amount,210				<CommonError<T>>::TokenValueTooLow211			);212			let account_balance = <AccountBalance<T>>::get((collection.id, owner))213				.checked_sub(1)214				// Should not occur215				.ok_or(ArithmeticError::Underflow)?;216217			// =========218219			<Owned<T>>::remove((collection.id, owner, token));220			<AccountBalance<T>>::insert((collection.id, owner), account_balance);221			Self::burn_token(collection, token)?;222			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223				collection.id,224				token,225				owner.clone(),226				amount,227			));228			return Ok(());229		}230231		let balance = <Balance<T>>::get((collection.id, token, owner))232			.checked_sub(amount)233			.ok_or(<CommonError<T>>::TokenValueTooLow)?;234		let account_balance = if balance == 0 {235			<AccountBalance<T>>::get((collection.id, owner))236				.checked_sub(1)237				// Should not occur238				.ok_or(ArithmeticError::Underflow)?239		} else {240			0241		};242243		// =========244245		if balance == 0 {246			<Owned<T>>::remove((collection.id, owner, token));247			<Balance<T>>::remove((collection.id, token, owner));248			<AccountBalance<T>>::insert((collection.id, owner), account_balance);249		} else {250			<Balance<T>>::insert((collection.id, token, owner), balance);251		}252		<TotalSupply<T>>::insert((collection.id, token), total_supply);253		// TODO: ERC20 transfer event254		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255			collection.id,256			token,257			owner.clone(),258			amount,259		));260		Ok(())261	}262263	pub fn transfer(264		collection: &RefungibleHandle<T>,265		from: &T::CrossAccountId,266		to: &T::CrossAccountId,267		token: TokenId,268		amount: u128,269	) -> DispatchResult {270		ensure!(271			collection.limits.transfers_enabled(),272			<CommonError<T>>::TransferNotAllowed273		);274275		if collection.access == AccessMode::AllowList {276			collection.check_allowlist(from)?;277			collection.check_allowlist(to)?;278		}279		<PalletCommon<T>>::ensure_correct_receiver(to)?;280281		let balance_from = <Balance<T>>::get((collection.id, token, from))282			.checked_sub(amount)283			.ok_or(<CommonError<T>>::TokenValueTooLow)?;284		let mut create_target = false;285		let from_to_differ = from != to;286		let balance_to = if from != to {287			let old_balance = <Balance<T>>::get((collection.id, token, to));288			if old_balance == 0 {289				create_target = true;290			}291			Some(292				old_balance293					.checked_add(amount)294					.ok_or(ArithmeticError::Overflow)?,295			)296		} else {297			None298		};299300		let account_balance_from = if balance_from == 0 {301			Some(302				<AccountBalance<T>>::get((collection.id, from))303					.checked_sub(1)304					// Should not occur305					.ok_or(ArithmeticError::Underflow)?,306			)307		} else {308			None309		};310		// Account data is created in token, AccountBalance should be increased311		// But only if from != to as we shouldn't check overflow in this case312		let account_balance_to = if create_target && from_to_differ {313			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314				.checked_add(1)315				.ok_or(ArithmeticError::Overflow)?;316			ensure!(317				account_balance_to < collection.limits.account_token_ownership_limit(),318				<CommonError<T>>::AccountTokenLimitExceeded,319			);320321			Some(account_balance_to)322		} else {323			None324		};325326		// =========327328		if let Some(balance_to) = balance_to {329			// from != to330			if balance_from == 0 {331				<Balance<T>>::remove((collection.id, token, from));332			} else {333				<Balance<T>>::insert((collection.id, token, from), balance_from);334			}335			<Balance<T>>::insert((collection.id, token, to), balance_to);336			if let Some(account_balance_from) = account_balance_from {337				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);338				<Owned<T>>::remove((collection.id, from, token));339			}340			if let Some(account_balance_to) = account_balance_to {341				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);342				<Owned<T>>::insert((collection.id, to, token), true);343			}344		}345346		// TODO: ERC20 transfer event347		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348			collection.id,349			token,350			from.clone(),351			to.clone(),352			amount,353		));354		Ok(())355	}356357	pub fn create_multiple_items(358		collection: &RefungibleHandle<T>,359		sender: &T::CrossAccountId,360		data: Vec<CreateItemData<T>>,361	) -> DispatchResult {362		if !collection.is_owner_or_admin(sender) {363			ensure!(364				collection.mint_mode,365				<CommonError<T>>::PublicMintingNotAllowed366			);367			collection.check_allowlist(sender)?;368369			for item in data.iter() {370				for (user, _) in &item.users {371					collection.check_allowlist(&user)?;372				}373			}374		}375376		for item in data.iter() {377			for (owner, _) in item.users.iter() {378				<PalletCommon<T>>::ensure_correct_receiver(owner)?;379			}380		}381382		// Total pieces per tokens383		let totals = data384			.iter()385			.map(|data| {386				Ok(data387					.users388					.iter()389					.map(|u| u.1)390					.try_fold(0u128, |acc, v| acc.checked_add(*v))391					.ok_or(ArithmeticError::Overflow)?)392			})393			.collect::<Result<Vec<_>, DispatchError>>()?;394		for total in &totals {395			ensure!(396				*total <= MAX_REFUNGIBLE_PIECES,397				<Error<T>>::WrongRefungiblePieces398			);399		}400401		let first_token_id = <TokensMinted<T>>::get(collection.id);402		let tokens_minted = first_token_id403			.checked_add(data.len() as u32)404			.ok_or(ArithmeticError::Overflow)?;405		ensure!(406			tokens_minted < collection.limits.token_limit(),407			<CommonError<T>>::CollectionTokenLimitExceeded408		);409410		let mut balances = BTreeMap::new();411		for data in &data {412			for (owner, _) in &data.users {413				let balance = balances414					.entry(owner)415					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));416				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;417418				ensure!(419					*balance <= collection.limits.account_token_ownership_limit(),420					<CommonError<T>>::AccountTokenLimitExceeded,421				);422			}423		}424425		// =========426427		<TokensMinted<T>>::insert(collection.id, tokens_minted);428		for (account, balance) in balances {429			<AccountBalance<T>>::insert((collection.id, account), balance);430		}431		for (i, token) in data.into_iter().enumerate() {432			let token_id = first_token_id + i as u32 + 1;433			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);434435			<TokenData<T>>::insert(436				(collection.id, token_id),437				ItemData {438					const_data: token.const_data.into(),439					variable_data: token.variable_data.into(),440				},441			);442			for (user, amount) in token.users.into_iter() {443				if amount == 0 {444					continue;445				}446				<Balance<T>>::insert((collection.id, token_id, &user), amount);447				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);448				// TODO: ERC20 transfer event449				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(450					collection.id,451					TokenId(token_id),452					user,453					amount,454				));455			}456		}457		Ok(())458	}459460	pub fn set_allowance_unchecked(461		collection: &RefungibleHandle<T>,462		sender: &T::CrossAccountId,463		spender: &T::CrossAccountId,464		token: TokenId,465		amount: u128,466	) {467		<Allowance<T>>::insert((collection.id, token, sender, spender), amount);468		// TODO: ERC20 approval event469		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(470			collection.id,471			token,472			sender.clone(),473			spender.clone(),474			amount,475		))476	}477478	pub fn set_allowance(479		collection: &RefungibleHandle<T>,480		sender: &T::CrossAccountId,481		spender: &T::CrossAccountId,482		token: TokenId,483		amount: u128,484	) -> DispatchResult {485		if collection.access == AccessMode::AllowList {486			collection.check_allowlist(&sender)?;487			collection.check_allowlist(&spender)?;488		}489490		<PalletCommon<T>>::ensure_correct_receiver(spender)?;491492		if <Balance<T>>::get((collection.id, token, sender)) < amount {493			ensure!(494				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),495				<CommonError<T>>::CantApproveMoreThanOwned496			);497		}498499		// =========500501		Self::set_allowance_unchecked(collection, sender, spender, token, amount);502		Ok(())503	}504505	pub fn transfer_from(506		collection: &RefungibleHandle<T>,507		spender: &T::CrossAccountId,508		from: &T::CrossAccountId,509		to: &T::CrossAccountId,510		token: TokenId,511		amount: u128,512	) -> DispatchResult {513		if spender.conv_eq(from) {514			return Self::transfer(collection, from, to, token, amount);515		}516		if collection.access == AccessMode::AllowList {517			// `from`, `to` checked in [`transfer`]518			collection.check_allowlist(spender)?;519		}520521		let allowance =522			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);523		if allowance.is_none() {524			ensure!(525				collection.ignores_allowance(spender),526				<CommonError<T>>::TokenValueNotEnough527			);528		}529530		// =========531532		Self::transfer(collection, from, to, token, amount)?;533		if let Some(allowance) = allowance {534			Self::set_allowance_unchecked(collection, from, spender, token, allowance);535		}536		Ok(())537	}538539	pub fn burn_from(540		collection: &RefungibleHandle<T>,541		spender: &T::CrossAccountId,542		from: &T::CrossAccountId,543		token: TokenId,544		amount: u128,545	) -> DispatchResult {546		if spender.conv_eq(from) {547			return Self::burn(collection, from, token, amount);548		}549		if collection.access == AccessMode::AllowList {550			// `from` checked in [`burn`]551			collection.check_allowlist(spender)?;552		}553554		let allowance =555			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);556		if allowance.is_none() {557			ensure!(558				collection.ignores_allowance(spender),559				<CommonError<T>>::TokenValueNotEnough560			);561		}562563		// =========564565		Self::burn(collection, from, token, amount)?;566		if let Some(allowance) = allowance {567			Self::set_allowance_unchecked(collection, from, spender, token, allowance);568		}569		Ok(())570	}571572	pub fn set_variable_metadata(573		collection: &RefungibleHandle<T>,574		sender: &T::CrossAccountId,575		token: TokenId,576		data: Vec<u8>,577	) -> DispatchResult {578		ensure!(579			data.len() as u32 <= CUSTOM_DATA_LIMIT,580			<CommonError<T>>::TokenVariableDataLimitExceeded581		);582		collection.check_can_update_meta(583			sender,584			&T::CrossAccountId::from_sub(collection.owner.clone()),585		)?;586587		let token_data = <TokenData<T>>::get((collection.id, token));588589		// =========590591		<TokenData<T>>::insert(592			(collection.id, token),593			ItemData {594				variable_data: data,595				..token_data596			},597		);598		Ok(())599	}600601	/// Delegated to `create_multiple_items`602	pub fn create_item(603		collection: &RefungibleHandle<T>,604		sender: &T::CrossAccountId,605		data: CreateItemData<T>,606	) -> DispatchResult {607		Self::create_multiple_items(collection, sender, vec![data])608	}609}
after · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_data_structs::{5	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6	MAX_REFUNGIBLE_PIECES, TokenId,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24	pub const_data: BoundedVec<u8, CustomDataLimit>,25	pub variable_data: BoundedVec<u8, CustomDataLimit>,26	pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo)]31pub struct ItemData {32	pub const_data: Vec<u8>,33	pub variable_data: Vec<u8>,34}3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40	use nft_data_structs::{CollectionId, TokenId};41	use super::weights::WeightInfo;4243	#[pallet::error]44	pub enum Error<T> {45		/// Not Refungible item data used to mint in Refungible collection.46		NotRefungibleDataUsedToMintFungibleCollectionToken,47		/// Maximum refungibility exceeded48		WrongRefungiblePieces,49	}5051	#[pallet::config]52	pub trait Config: frame_system::Config + pallet_common::Config {53		type WeightInfo: WeightInfo;54	}5556	#[pallet::pallet]57	#[pallet::generate_store(pub trait Store)]58	pub struct Pallet<T>(_);5960	#[pallet::storage]61	pub type TokensMinted<T: Config> =62		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63	#[pallet::storage]64	pub type TokensBurnt<T: Config> =65		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667	#[pallet::storage]68	pub type TokenData<T: Config> = StorageNMap<69		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70		Value = ItemData,71		QueryKind = ValueQuery,72	>;7374	#[pallet::storage]75	pub type TotalSupply<T: Config> = StorageNMap<76		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77		Value = u128,78		QueryKind = ValueQuery,79	>;8081	/// Used to enumerate tokens owned by account82	#[pallet::storage]83	pub type Owned<T: Config> = StorageNMap<84		Key = (85			Key<Twox64Concat, CollectionId>,86			Key<Blake2_128Concat, T::CrossAccountId>,87			Key<Twox64Concat, TokenId>,88		),89		Value = bool,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub type AccountBalance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			// Owner98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u32,101		QueryKind = ValueQuery,102	>;103104	#[pallet::storage]105	pub type Balance<T: Config> = StorageNMap<106		Key = (107			Key<Twox64Concat, CollectionId>,108			Key<Twox64Concat, TokenId>,109			// Owner110			Key<Blake2_128Concat, T::CrossAccountId>,111		),112		Value = u128,113		QueryKind = ValueQuery,114	>;115116	#[pallet::storage]117	pub type Allowance<T: Config> = StorageNMap<118		Key = (119			Key<Twox64Concat, CollectionId>,120			Key<Twox64Concat, TokenId>,121			// Owner122			Key<Blake2_128, T::CrossAccountId>,123			// Spender124			Key<Blake2_128Concat, T::CrossAccountId>,125		),126		Value = u128,127		QueryKind = ValueQuery,128	>;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134		Self(inner)135	}136	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137		self.0138	}139}140impl<T: Config> Deref for RefungibleHandle<T> {141	type Target = pallet_common::CollectionHandle<T>;142143	fn deref(&self) -> &Self::Target {144		&self.0145	}146}147148impl<T: Config> Pallet<T> {149	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151	}152	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153		<TotalSupply<T>>::contains_key((collection.id, token))154	}155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160		<PalletCommon<T>>::init_collection(data)161	}162	pub fn destroy_collection(163		collection: RefungibleHandle<T>,164		sender: &T::CrossAccountId,165	) -> DispatchResult {166		let id = collection.id;167168		// =========169170		PalletCommon::destroy_collection(collection.0, sender)?;171172		<TokensMinted<T>>::remove(id);173		<TokensBurnt<T>>::remove(id);174		<TokenData<T>>::remove_prefix((id,), None);175		<TotalSupply<T>>::remove_prefix((id,), None);176		<Balance<T>>::remove_prefix((id,), None);177		<Allowance<T>>::remove_prefix((id,), None);178		Ok(())179	}180181	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182		let burnt = <TokensBurnt<T>>::get(collection.id)183			.checked_add(1)184			.ok_or(ArithmeticError::Overflow)?;185186		<TokensBurnt<T>>::insert(collection.id, burnt);187		<TokenData<T>>::remove((collection.id, token_id));188		<TotalSupply<T>>::remove((collection.id, token_id));189		<Balance<T>>::remove_prefix((collection.id, token_id), None);190		<Allowance<T>>::remove_prefix((collection.id, token_id), None);191		// TODO: ERC721 transfer event192		Ok(())193	}194195	pub fn burn(196		collection: &RefungibleHandle<T>,197		owner: &T::CrossAccountId,198		token: TokenId,199		amount: u128,200	) -> DispatchResult {201		let total_supply = <TotalSupply<T>>::get((collection.id, token))202			.checked_sub(amount)203			.ok_or(<CommonError<T>>::TokenValueTooLow)?;204205		// This was probally last owner of this token?206		if total_supply == 0 {207			// Ensure user actually owns this amount208			ensure!(209				<Balance<T>>::get((collection.id, token, owner)) == amount,210				<CommonError<T>>::TokenValueTooLow211			);212			let account_balance = <AccountBalance<T>>::get((collection.id, owner))213				.checked_sub(1)214				// Should not occur215				.ok_or(ArithmeticError::Underflow)?;216217			// =========218219			<Owned<T>>::remove((collection.id, owner, token));220			<AccountBalance<T>>::insert((collection.id, owner), account_balance);221			Self::burn_token(collection, token)?;222			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223				collection.id,224				token,225				owner.clone(),226				amount,227			));228			return Ok(());229		}230231		let balance = <Balance<T>>::get((collection.id, token, owner))232			.checked_sub(amount)233			.ok_or(<CommonError<T>>::TokenValueTooLow)?;234		let account_balance = if balance == 0 {235			<AccountBalance<T>>::get((collection.id, owner))236				.checked_sub(1)237				// Should not occur238				.ok_or(ArithmeticError::Underflow)?239		} else {240			0241		};242243		// =========244245		if balance == 0 {246			<Owned<T>>::remove((collection.id, owner, token));247			<Balance<T>>::remove((collection.id, token, owner));248			<AccountBalance<T>>::insert((collection.id, owner), account_balance);249		} else {250			<Balance<T>>::insert((collection.id, token, owner), balance);251		}252		<TotalSupply<T>>::insert((collection.id, token), total_supply);253		// TODO: ERC20 transfer event254		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255			collection.id,256			token,257			owner.clone(),258			amount,259		));260		Ok(())261	}262263	pub fn transfer(264		collection: &RefungibleHandle<T>,265		from: &T::CrossAccountId,266		to: &T::CrossAccountId,267		token: TokenId,268		amount: u128,269	) -> DispatchResult {270		ensure!(271			collection.limits.transfers_enabled(),272			<CommonError<T>>::TransferNotAllowed273		);274275		if collection.access == AccessMode::AllowList {276			collection.check_allowlist(from)?;277			collection.check_allowlist(to)?;278		}279		<PalletCommon<T>>::ensure_correct_receiver(to)?;280281		let balance_from = <Balance<T>>::get((collection.id, token, from))282			.checked_sub(amount)283			.ok_or(<CommonError<T>>::TokenValueTooLow)?;284		let mut create_target = false;285		let from_to_differ = from != to;286		let balance_to = if from != to {287			let old_balance = <Balance<T>>::get((collection.id, token, to));288			if old_balance == 0 {289				create_target = true;290			}291			Some(292				old_balance293					.checked_add(amount)294					.ok_or(ArithmeticError::Overflow)?,295			)296		} else {297			None298		};299300		let account_balance_from = if balance_from == 0 {301			Some(302				<AccountBalance<T>>::get((collection.id, from))303					.checked_sub(1)304					// Should not occur305					.ok_or(ArithmeticError::Underflow)?,306			)307		} else {308			None309		};310		// Account data is created in token, AccountBalance should be increased311		// But only if from != to as we shouldn't check overflow in this case312		let account_balance_to = if create_target && from_to_differ {313			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314				.checked_add(1)315				.ok_or(ArithmeticError::Overflow)?;316			ensure!(317				account_balance_to < collection.limits.account_token_ownership_limit(),318				<CommonError<T>>::AccountTokenLimitExceeded,319			);320321			Some(account_balance_to)322		} else {323			None324		};325326		// =========327328		if let Some(balance_to) = balance_to {329			// from != to330			if balance_from == 0 {331				<Balance<T>>::remove((collection.id, token, from));332			} else {333				<Balance<T>>::insert((collection.id, token, from), balance_from);334			}335			<Balance<T>>::insert((collection.id, token, to), balance_to);336			if let Some(account_balance_from) = account_balance_from {337				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);338				<Owned<T>>::remove((collection.id, from, token));339			}340			if let Some(account_balance_to) = account_balance_to {341				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);342				<Owned<T>>::insert((collection.id, to, token), true);343			}344		}345346		// TODO: ERC20 transfer event347		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348			collection.id,349			token,350			from.clone(),351			to.clone(),352			amount,353		));354		Ok(())355	}356357	pub fn create_multiple_items(358		collection: &RefungibleHandle<T>,359		sender: &T::CrossAccountId,360		data: Vec<CreateItemData<T>>,361	) -> DispatchResult {362		if !collection.is_owner_or_admin(sender) {363			ensure!(364				collection.mint_mode,365				<CommonError<T>>::PublicMintingNotAllowed366			);367			collection.check_allowlist(sender)?;368369			for item in data.iter() {370				for user in item.users.keys() {371					collection.check_allowlist(user)?;372				}373			}374		}375376		for item in data.iter() {377			for (owner, _) in item.users.iter() {378				<PalletCommon<T>>::ensure_correct_receiver(owner)?;379			}380		}381382		// Total pieces per tokens383		let totals = data384			.iter()385			.map(|data| {386				Ok(data387					.users388					.iter()389					.map(|u| u.1)390					.try_fold(0u128, |acc, v| acc.checked_add(*v))391					.ok_or(ArithmeticError::Overflow)?)392			})393			.collect::<Result<Vec<_>, DispatchError>>()?;394		for total in &totals {395			ensure!(396				*total <= MAX_REFUNGIBLE_PIECES,397				<Error<T>>::WrongRefungiblePieces398			);399		}400401		let first_token_id = <TokensMinted<T>>::get(collection.id);402		let tokens_minted = first_token_id403			.checked_add(data.len() as u32)404			.ok_or(ArithmeticError::Overflow)?;405		ensure!(406			tokens_minted < collection.limits.token_limit(),407			<CommonError<T>>::CollectionTokenLimitExceeded408		);409410		let mut balances = BTreeMap::new();411		for data in &data {412			for owner in data.users.keys() {413				let balance = balances414					.entry(owner)415					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));416				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;417418				ensure!(419					*balance <= collection.limits.account_token_ownership_limit(),420					<CommonError<T>>::AccountTokenLimitExceeded,421				);422			}423		}424425		// =========426427		<TokensMinted<T>>::insert(collection.id, tokens_minted);428		for (account, balance) in balances {429			<AccountBalance<T>>::insert((collection.id, account), balance);430		}431		for (i, token) in data.into_iter().enumerate() {432			let token_id = first_token_id + i as u32 + 1;433			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);434435			<TokenData<T>>::insert(436				(collection.id, token_id),437				ItemData {438					const_data: token.const_data.into(),439					variable_data: token.variable_data.into(),440				},441			);442			for (user, amount) in token.users.into_iter() {443				if amount == 0 {444					continue;445				}446				<Balance<T>>::insert((collection.id, token_id, &user), amount);447				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);448				// TODO: ERC20 transfer event449				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(450					collection.id,451					TokenId(token_id),452					user,453					amount,454				));455			}456		}457		Ok(())458	}459460	pub fn set_allowance_unchecked(461		collection: &RefungibleHandle<T>,462		sender: &T::CrossAccountId,463		spender: &T::CrossAccountId,464		token: TokenId,465		amount: u128,466	) {467		<Allowance<T>>::insert((collection.id, token, sender, spender), amount);468		// TODO: ERC20 approval event469		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(470			collection.id,471			token,472			sender.clone(),473			spender.clone(),474			amount,475		))476	}477478	pub fn set_allowance(479		collection: &RefungibleHandle<T>,480		sender: &T::CrossAccountId,481		spender: &T::CrossAccountId,482		token: TokenId,483		amount: u128,484	) -> DispatchResult {485		if collection.access == AccessMode::AllowList {486			collection.check_allowlist(sender)?;487			collection.check_allowlist(spender)?;488		}489490		<PalletCommon<T>>::ensure_correct_receiver(spender)?;491492		if <Balance<T>>::get((collection.id, token, sender)) < amount {493			ensure!(494				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),495				<CommonError<T>>::CantApproveMoreThanOwned496			);497		}498499		// =========500501		Self::set_allowance_unchecked(collection, sender, spender, token, amount);502		Ok(())503	}504505	pub fn transfer_from(506		collection: &RefungibleHandle<T>,507		spender: &T::CrossAccountId,508		from: &T::CrossAccountId,509		to: &T::CrossAccountId,510		token: TokenId,511		amount: u128,512	) -> DispatchResult {513		if spender.conv_eq(from) {514			return Self::transfer(collection, from, to, token, amount);515		}516		if collection.access == AccessMode::AllowList {517			// `from`, `to` checked in [`transfer`]518			collection.check_allowlist(spender)?;519		}520521		let allowance =522			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);523		if allowance.is_none() {524			ensure!(525				collection.ignores_allowance(spender),526				<CommonError<T>>::TokenValueNotEnough527			);528		}529530		// =========531532		Self::transfer(collection, from, to, token, amount)?;533		if let Some(allowance) = allowance {534			Self::set_allowance_unchecked(collection, from, spender, token, allowance);535		}536		Ok(())537	}538539	pub fn burn_from(540		collection: &RefungibleHandle<T>,541		spender: &T::CrossAccountId,542		from: &T::CrossAccountId,543		token: TokenId,544		amount: u128,545	) -> DispatchResult {546		if spender.conv_eq(from) {547			return Self::burn(collection, from, token, amount);548		}549		if collection.access == AccessMode::AllowList {550			// `from` checked in [`burn`]551			collection.check_allowlist(spender)?;552		}553554		let allowance =555			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);556		if allowance.is_none() {557			ensure!(558				collection.ignores_allowance(spender),559				<CommonError<T>>::TokenValueNotEnough560			);561		}562563		// =========564565		Self::burn(collection, from, token, amount)?;566		if let Some(allowance) = allowance {567			Self::set_allowance_unchecked(collection, from, spender, token, allowance);568		}569		Ok(())570	}571572	pub fn set_variable_metadata(573		collection: &RefungibleHandle<T>,574		sender: &T::CrossAccountId,575		token: TokenId,576		data: Vec<u8>,577	) -> DispatchResult {578		ensure!(579			data.len() as u32 <= CUSTOM_DATA_LIMIT,580			<CommonError<T>>::TokenVariableDataLimitExceeded581		);582		collection.check_can_update_meta(583			sender,584			&T::CrossAccountId::from_sub(collection.owner.clone()),585		)?;586587		let token_data = <TokenData<T>>::get((collection.id, token));588589		// =========590591		<TokenData<T>>::insert(592			(collection.id, token),593			ItemData {594				variable_data: data,595				..token_data596			},597		);598		Ok(())599	}600601	/// Delegated to `create_multiple_items`602	pub fn create_item(603		collection: &RefungibleHandle<T>,604		sender: &T::CrossAccountId,605		data: CreateItemData<T>,606	) -> DispatchResult {607		Self::create_multiple_items(collection, sender, vec![data])608	}609}
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -25,6 +25,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
@@ -33,7 +34,6 @@
 pub trait WeightInfo {
 	fn create_item() -> Weight;
 	fn create_multiple_items(b: u32, ) -> Weight;
-	fn burn_from() -> Weight;
 	fn burn_item_partial() -> Weight;
 	fn burn_item_fully() -> Weight;
 	fn transfer_normal() -> Weight;
@@ -45,6 +45,7 @@
 	fn transfer_from_creating() -> Weight;
 	fn transfer_from_removing() -> Weight;
 	fn transfer_from_creating_removing() -> Weight;
+	fn burn_from() -> Weight;
 	fn set_variable_metadata(b: u32, ) -> Weight;
 }
 
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -327,8 +327,7 @@
 		D: ser::Serializer,
 		V: Serialize,
 	{
-		let vec: &Vec<_> = &value;
-		vec.serialize(serializer)
+		(value as &Vec<_>).serialize(serializer)
 	}
 
 	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -1177,6 +1177,7 @@
 			EVM::account_storages(address, H256::from_slice(&tmp[..]))
 		}
 
+		#[allow(clippy::redundant_closure)]
 		fn call(
 			from: H160,
 			to: H160,
@@ -1207,6 +1208,7 @@
 			).map_err(|err| err.into())
 		}
 
+		#[allow(clippy::redundant_closure)]
 		fn create(
 			from: H160,
 			data: Vec<u8>,