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

difftreelog

feat allow more fields to be set on collection creation

Yaroslav Bolyukin2022-01-11parent: #fcf0631.patch.diff
in: master

7 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
 	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
-	WithdrawReasons, CollectionStats,
+	WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+	NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
+	CreateCollectionData, SponsorshipState,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -282,6 +285,10 @@
 		TokenVariableDataLimitExceeded,
 		/// Exceeded max admin count
 		CollectionAdminCountExceeded,
+		/// Collection limit bounds per collection exceeded
+		CollectionLimitBoundsExceeded,
+		/// Tried to enable permissions which are only permitted to be disabled
+		OwnerPermissionsCantBeReverted,
 
 		/// Collection settings not allowing items transferring
 		TransferNotAllowed,
@@ -392,7 +399,10 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
 		{
 			ensure!(
 				data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
@@ -423,6 +433,29 @@
 
 		// =========
 
+		let collection = Collection {
+			owner: owner.clone(),
+			name: data.name,
+			mode: data.mode.clone(),
+			mint_mode: false,
+			access: data.access.unwrap_or_default(),
+			description: data.description,
+			token_prefix: data.token_prefix,
+			offchain_schema: data.offchain_schema,
+			schema_version: data.schema_version.unwrap_or_default(),
+			sponsorship: data
+				.pending_sponsor
+				.map(SponsorshipState::Unconfirmed)
+				.unwrap_or_default(),
+			variable_on_chain_schema: data.variable_on_chain_schema,
+			const_on_chain_schema: data.const_on_chain_schema,
+			limits: data
+				.limits
+				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
+				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+		};
+
 		// Take a (non-refundable) deposit of collection creation
 		{
 			let mut imbalance =
@@ -434,7 +467,7 @@
 				),
 			);
 			<T as Config>::Currency::settle(
-				&data.owner,
+				&owner,
 				imbalance,
 				WithdrawReasons::TRANSFER,
 				ExistenceRequirement::KeepAlive,
@@ -443,12 +476,8 @@
 		}
 
 		<CreatedCollectionCount<T>>::put(created_count);
-		<Pallet<T>>::deposit_event(Event::CollectionCreated(
-			id,
-			data.mode.id(),
-			data.owner.clone(),
-		));
-		<CollectionById<T>>::insert(id, data);
+		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
+		<CollectionById<T>>::insert(id, collection);
 		Ok(id)
 	}
 
@@ -532,6 +561,61 @@
 
 		Ok(())
 	}
+
+	pub fn clamp_limits(
+		mode: CollectionMode,
+		old_limit: &CollectionLimits,
+		mut new_limit: CollectionLimits,
+	) -> Result<CollectionLimits, DispatchError> {
+		macro_rules! limit_default {
+				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+					$(
+						if let Some($new) = $new.$field {
+							let $old = $old.$field($($arg)?);
+							let _ = $new;
+							let _ = $old;
+							$check
+						} else {
+							$new.$field = $old.$field
+						}
+					)*
+				}};
+			}
+
+		limit_default!(old_limit, new_limit,
+			account_token_ownership_limit => ensure!(
+				new_limit <= MAX_TOKEN_OWNERSHIP,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsor_transfer_timeout(match mode {
+				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+			}) => ensure!(
+				new_limit <= MAX_SPONSOR_TIMEOUT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			sponsored_data_size => ensure!(
+				new_limit <= CUSTOM_DATA_LIMIT,
+				<Error<T>>::CollectionLimitBoundsExceeded,
+			),
+			token_limit => ensure!(
+				old_limit >= new_limit && new_limit > 0,
+				<Error<T>>::CollectionTokenLimitExceeded
+			),
+			owner_can_transfer => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			owner_can_destroy => ensure!(
+				old_limit || !new_limit,
+				<Error<T>>::OwnerPermissionsCantBeReverted,
+			),
+			sponsored_data_rate_limit => {},
+			transfers_enabled => {},
+		);
+		Ok(new_limit)
+	}
 }
 
 #[macro_export]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
 
 use core::ops::Deref;
 use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use up_data_structs::{AccessMode, Collection, CollectionId, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
 };
@@ -100,8 +100,11 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: FungibleHandle<T>,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
before · pallets/nonfungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use up_data_structs::{6	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,7};8use pallet_common::{9	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,10};11use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};12use sp_core::H160;13use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};14use sp_std::{vec::Vec, vec};15use core::ops::Deref;16use sp_std::collections::btree_map::BTreeMap;17use codec::{Encode, Decode};18use scale_info::TypeInfo;1920pub use pallet::*;21#[cfg(feature = "runtime-benchmarks")]22pub mod benchmarking;23pub mod common;24pub mod erc;25pub mod weights;2627pub struct CreateItemData<T: Config> {28	pub const_data: BoundedVec<u8, CustomDataLimit>,29	pub variable_data: BoundedVec<u8, CustomDataLimit>,30	pub owner: T::CrossAccountId,31}32pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3334#[derive(Encode, Decode, TypeInfo)]35pub struct ItemData<T: Config> {36	pub const_data: Vec<u8>,37	pub variable_data: Vec<u8>,38	pub owner: T::CrossAccountId,39}4041#[frame_support::pallet]42pub mod pallet {43	use super::*;44	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};45	use up_data_structs::{CollectionId, TokenId};46	use super::weights::WeightInfo;4748	#[pallet::error]49	pub enum Error<T> {50		/// Not Nonfungible item data used to mint in Nonfungible collection.51		NotNonfungibleDataUsedToMintFungibleCollectionToken,52		/// Used amount > 1 with NFT53		NonfungibleItemsHaveNoAmount,54	}5556	#[pallet::config]57	pub trait Config: frame_system::Config + pallet_common::Config {58		type WeightInfo: WeightInfo;59	}6061	#[pallet::pallet]62	#[pallet::generate_store(pub(super) trait Store)]63	pub struct Pallet<T>(_);6465	#[pallet::storage]66	pub type TokensMinted<T: Config> =67		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;68	#[pallet::storage]69	pub type TokensBurnt<T: Config> =70		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7172	#[pallet::storage]73	pub type TokenData<T: Config> = StorageNMap<74		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),75		Value = ItemData<T>,76		QueryKind = OptionQuery,77	>;7879	/// Used to enumerate tokens owned by account80	#[pallet::storage]81	pub type Owned<T: Config> = StorageNMap<82		Key = (83			Key<Twox64Concat, CollectionId>,84			Key<Blake2_128Concat, T::CrossAccountId>,85			Key<Twox64Concat, TokenId>,86		),87		Value = bool,88		QueryKind = ValueQuery,89	>;9091	#[pallet::storage]92	pub type AccountBalance<T: Config> = StorageNMap<93		Key = (94			Key<Twox64Concat, CollectionId>,95			Key<Blake2_128Concat, T::CrossAccountId>,96		),97		Value = u32,98		QueryKind = ValueQuery,99	>;100101	#[pallet::storage]102	pub type Allowance<T: Config> = StorageNMap<103		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),104		Value = T::CrossAccountId,105		QueryKind = OptionQuery,106	>;107}108109pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);110impl<T: Config> NonfungibleHandle<T> {111	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {112		Self(inner)113	}114	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {115		self.0116	}117}118impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {119	fn recorder(&self) -> &SubstrateRecorder<T> {120		self.0.recorder()121	}122	fn into_recorder(self) -> SubstrateRecorder<T> {123		self.0.into_recorder()124	}125}126impl<T: Config> Deref for NonfungibleHandle<T> {127	type Target = pallet_common::CollectionHandle<T>;128129	fn deref(&self) -> &Self::Target {130		&self.0131	}132}133134impl<T: Config> Pallet<T> {135	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {136		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)137	}138	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {139		<TokenData<T>>::contains_key((collection.id, token))140	}141}142143// unchecked calls skips any permission checks144impl<T: Config> Pallet<T> {145	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {146		<PalletCommon<T>>::init_collection(data)147	}148	pub fn destroy_collection(149		collection: NonfungibleHandle<T>,150		sender: &T::CrossAccountId,151	) -> DispatchResult {152		let id = collection.id;153154		// =========155156		PalletCommon::destroy_collection(collection.0, sender)?;157158		<TokenData<T>>::remove_prefix((id,), None);159		<Owned<T>>::remove_prefix((id,), None);160		<TokensMinted<T>>::remove(id);161		<TokensBurnt<T>>::remove(id);162		<Allowance<T>>::remove_prefix((id,), None);163		<AccountBalance<T>>::remove_prefix((id,), None);164		Ok(())165	}166167	pub fn burn(168		collection: &NonfungibleHandle<T>,169		sender: &T::CrossAccountId,170		token: TokenId,171	) -> DispatchResult {172		let token_data =173			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;174		ensure!(175			&token_data.owner == sender176				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),177			<CommonError<T>>::NoPermission178		);179180		if collection.access == AccessMode::AllowList {181			collection.check_allowlist(sender)?;182		}183184		let burnt = <TokensBurnt<T>>::get(collection.id)185			.checked_add(1)186			.ok_or(ArithmeticError::Overflow)?;187188		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))189			.checked_sub(1)190			.ok_or(ArithmeticError::Overflow)?;191192		if balance == 0 {193			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));194		} else {195			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);196		}197		// =========198199		<Owned<T>>::remove((collection.id, &token_data.owner, token));200		<TokensBurnt<T>>::insert(collection.id, burnt);201		<TokenData<T>>::remove((collection.id, token));202		let old_spender = <Allowance<T>>::take((collection.id, token));203204		if let Some(old_spender) = old_spender {205			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(206				collection.id,207				token,208				sender.clone(),209				old_spender,210				0,211			));212		}213214		collection.log(ERC721Events::Transfer {215			from: *token_data.owner.as_eth(),216			to: H160::default(),217			token_id: token.into(),218		});219		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(220			collection.id,221			token,222			token_data.owner,223			1,224		));225		Ok(())226	}227228	pub fn transfer(229		collection: &NonfungibleHandle<T>,230		from: &T::CrossAccountId,231		to: &T::CrossAccountId,232		token: TokenId,233	) -> DispatchResult {234		ensure!(235			collection.limits.transfers_enabled(),236			<CommonError<T>>::TransferNotAllowed237		);238239		let token_data =240			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;241		ensure!(242			&token_data.owner == from243				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),244			<CommonError<T>>::NoPermission245		);246247		if collection.access == AccessMode::AllowList {248			collection.check_allowlist(from)?;249			collection.check_allowlist(to)?;250		}251		<PalletCommon<T>>::ensure_correct_receiver(to)?;252253		let balance_from = <AccountBalance<T>>::get((collection.id, from))254			.checked_sub(1)255			.ok_or(<CommonError<T>>::TokenValueTooLow)?;256		let balance_to = if from != to {257			let balance_to = <AccountBalance<T>>::get((collection.id, to))258				.checked_add(1)259				.ok_or(ArithmeticError::Overflow)?;260261			ensure!(262				balance_to < collection.limits.account_token_ownership_limit(),263				<CommonError<T>>::AccountTokenLimitExceeded,264			);265266			Some(balance_to)267		} else {268			None269		};270271		// =========272273		<TokenData<T>>::insert(274			(collection.id, token),275			ItemData {276				owner: to.clone(),277				..token_data278			},279		);280281		if let Some(balance_to) = balance_to {282			// from != to283			if balance_from == 0 {284				<AccountBalance<T>>::remove((collection.id, from));285			} else {286				<AccountBalance<T>>::insert((collection.id, from), balance_from);287			}288			<AccountBalance<T>>::insert((collection.id, to), balance_to);289			<Owned<T>>::remove((collection.id, from, token));290			<Owned<T>>::insert((collection.id, to, token), true);291		}292		Self::set_allowance_unchecked(collection, from, token, None, true);293294		collection.log(ERC721Events::Transfer {295			from: *from.as_eth(),296			to: *to.as_eth(),297			token_id: token.into(),298		});299		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(300			collection.id,301			token,302			from.clone(),303			to.clone(),304			1,305		));306		Ok(())307	}308309	pub fn create_multiple_items(310		collection: &NonfungibleHandle<T>,311		sender: &T::CrossAccountId,312		data: Vec<CreateItemData<T>>,313	) -> DispatchResult {314		if !collection.is_owner_or_admin(sender) {315			ensure!(316				collection.mint_mode,317				<CommonError<T>>::PublicMintingNotAllowed318			);319			collection.check_allowlist(sender)?;320321			for item in data.iter() {322				collection.check_allowlist(&item.owner)?;323			}324		}325326		for data in data.iter() {327			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;328		}329330		let first_token = <TokensMinted<T>>::get(collection.id);331		let tokens_minted = first_token332			.checked_add(data.len() as u32)333			.ok_or(ArithmeticError::Overflow)?;334		ensure!(335			tokens_minted <= collection.limits.token_limit(),336			<CommonError<T>>::CollectionTokenLimitExceeded337		);338339		let mut balances = BTreeMap::new();340		for data in &data {341			let balance = balances342				.entry(&data.owner)343				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));344			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;345346			ensure!(347				*balance <= collection.limits.account_token_ownership_limit(),348				<CommonError<T>>::AccountTokenLimitExceeded,349			);350		}351352		// =========353354		<TokensMinted<T>>::insert(collection.id, tokens_minted);355		for (account, balance) in balances {356			<AccountBalance<T>>::insert((collection.id, account), balance);357		}358		for (i, data) in data.into_iter().enumerate() {359			let token = first_token + i as u32 + 1;360361			<TokenData<T>>::insert(362				(collection.id, token),363				ItemData {364					const_data: data.const_data.into(),365					variable_data: data.variable_data.into(),366					owner: data.owner.clone(),367				},368			);369			<Owned<T>>::insert((collection.id, &data.owner, token), true);370371			collection.log(ERC721Events::Transfer {372				from: H160::default(),373				to: *data.owner.as_eth(),374				token_id: token.into(),375			});376			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(377				collection.id,378				TokenId(token),379				data.owner.clone(),380				1,381			));382		}383		Ok(())384	}385386	pub fn set_allowance_unchecked(387		collection: &NonfungibleHandle<T>,388		sender: &T::CrossAccountId,389		token: TokenId,390		spender: Option<&T::CrossAccountId>,391		assume_implicit_eth: bool,392	) {393		if let Some(spender) = spender {394			let old_spender = <Allowance<T>>::get((collection.id, token));395			<Allowance<T>>::insert((collection.id, token), spender);396			// In ERC721 there is only one possible approved user of token, so we set397			// approved user to spender398			collection.log(ERC721Events::Approval {399				owner: *sender.as_eth(),400				approved: *spender.as_eth(),401				token_id: token.into(),402			});403			// In Unique chain, any token can have any amount of approved users, so we need to404			// set allowance of old owner to 0, and allowance of new owner to 1405			if old_spender.as_ref() != Some(spender) {406				if let Some(old_owner) = old_spender {407					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(408						collection.id,409						token,410						sender.clone(),411						old_owner,412						0,413					));414				}415				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(416					collection.id,417					token,418					sender.clone(),419					spender.clone(),420					1,421				));422			}423		} else {424			let old_spender = <Allowance<T>>::take((collection.id, token));425			if !assume_implicit_eth {426				// In ERC721 there is only one possible approved user of token, so we set427				// approved user to zero address428				collection.log(ERC721Events::Approval {429					owner: *sender.as_eth(),430					approved: H160::default(),431					token_id: token.into(),432				});433			}434			// In Unique chain, any token can have any amount of approved users, so we need to435			// set allowance of old owner to 0436			if let Some(old_spender) = old_spender {437				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(438					collection.id,439					token,440					sender.clone(),441					old_spender,442					0,443				));444			}445		}446	}447448	pub fn set_allowance(449		collection: &NonfungibleHandle<T>,450		sender: &T::CrossAccountId,451		token: TokenId,452		spender: Option<&T::CrossAccountId>,453	) -> DispatchResult {454		if collection.access == AccessMode::AllowList {455			collection.check_allowlist(sender)?;456			if let Some(spender) = spender {457				collection.check_allowlist(spender)?;458			}459		}460461		if let Some(spender) = spender {462			<PalletCommon<T>>::ensure_correct_receiver(spender)?;463		}464		let token_data =465			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;466		if &token_data.owner != sender {467			ensure!(468				collection.ignores_owned_amount(sender),469				<CommonError<T>>::CantApproveMoreThanOwned470			);471		}472473		// =========474475		Self::set_allowance_unchecked(collection, sender, token, spender, false);476		Ok(())477	}478479	pub fn transfer_from(480		collection: &NonfungibleHandle<T>,481		spender: &T::CrossAccountId,482		from: &T::CrossAccountId,483		to: &T::CrossAccountId,484		token: TokenId,485	) -> DispatchResult {486		if spender.conv_eq(from) {487			return Self::transfer(collection, from, to, token);488		}489		if collection.access == AccessMode::AllowList {490			// `from`, `to` checked in [`transfer`]491			collection.check_allowlist(spender)?;492		}493494		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {495			ensure!(496				collection.ignores_allowance(spender),497				<CommonError<T>>::TokenValueNotEnough498			);499		}500501		// =========502503		Self::transfer(collection, from, to, token)?;504		// Allowance is reset in [`transfer`]505		Ok(())506	}507508	pub fn burn_from(509		collection: &NonfungibleHandle<T>,510		spender: &T::CrossAccountId,511		from: &T::CrossAccountId,512		token: TokenId,513	) -> DispatchResult {514		if spender.conv_eq(from) {515			return Self::burn(collection, from, token);516		}517		if collection.access == AccessMode::AllowList {518			// `from` checked in [`burn`]519			collection.check_allowlist(spender)?;520		}521522		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {523			ensure!(524				collection.ignores_allowance(spender),525				<CommonError<T>>::TokenValueNotEnough526			);527		}528529		// =========530531		Self::burn(collection, from, token)532	}533534	pub fn set_variable_metadata(535		collection: &NonfungibleHandle<T>,536		sender: &T::CrossAccountId,537		token: TokenId,538		data: Vec<u8>,539	) -> DispatchResult {540		ensure!(541			data.len() as u32 <= CUSTOM_DATA_LIMIT,542			<CommonError<T>>::TokenVariableDataLimitExceeded543		);544		let token_data =545			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;546		collection.check_can_update_meta(sender, &token_data.owner)?;547548		// =========549550		<TokenData<T>>::insert(551			(collection.id, token),552			ItemData {553				variable_data: data,554				..token_data555			},556		);557		Ok(())558	}559560	/// Delegated to `create_multiple_items`561	pub fn create_item(562		collection: &NonfungibleHandle<T>,563		sender: &T::CrossAccountId,564		data: CreateItemData<T>,565	) -> DispatchResult {566		Self::create_multiple_items(collection, sender, vec![data])567	}568}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -3,7 +3,7 @@
 use frame_support::{ensure, BoundedVec};
 use up_data_structs::{
 	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,
-	MAX_REFUNGIBLE_PIECES, TokenId,
+	MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
@@ -156,8 +156,11 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(data)
+	pub fn init_collection(
+		owner: T::AccountId,
+		data: CreateCollectionData<T::AccountId>,
+	) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(owner, data)
 	}
 	pub fn destroy_collection(
 		collection: RefungibleHandle<T>,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,11 +35,10 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
-	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-	NFT_SPONSOR_TRANSFER_TIMEOUT, AccessMode, Collection, CreateItemData, CollectionLimits,
-	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+	OFFCHAIN_SCHEMA_LIMIT, AccessMode, CreateItemData, CollectionLimits, CollectionId,
+	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	CreateCollectionData,
 };
 use pallet_common::{
 	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -81,10 +80,6 @@
 		ConfirmUnsetSponsorFail,
 		/// Length of items properties must be greater than 0.
 		EmptyArgument,
-		/// Collection limit bounds per collection exceeded
-		CollectionLimitBoundsExceeded,
-		/// Tried to enable permissions which are only permitted to be disabled
-		OwnerPermissionsCantBeReverted,
 	}
 }
 
@@ -318,42 +313,38 @@
 		// returns collection ID
 		#[weight = <SelfWeightOf<T>>::create_collection()]
 		#[transactional]
+		#[deprecated]
 		pub fn create_collection(origin,
 								 collection_name: Vec<u16>,
 								 collection_description: Vec<u16>,
 								 token_prefix: Vec<u8>,
 								 mode: CollectionMode) -> DispatchResult {
-
-			// Anyone can create a collection
-			let who = ensure_signed(origin)?;
-
-			// Create new collection
-			let new_collection = Collection {
-				owner: who,
+			Self::create_collection_ex(origin, CreateCollectionData {
 				name: collection_name,
-				mode: mode.clone(),
-				mint_mode: false,
-				access: AccessMode::Normal,
 				description: collection_description,
 				token_prefix,
-				offchain_schema: Vec::new(),
-				schema_version: SchemaVersion::ImageURL,
-				sponsorship: SponsorshipState::Disabled,
-				variable_on_chain_schema: Vec::new(),
-				const_on_chain_schema: Vec::new(),
-				limits: Default::default(),
-				meta_update_permission: Default::default(),
-			};
+				mode,
+				..Default::default()
+			})
+		}
+
+		/// This method creates a collection
+		///
+		/// Prefer it to deprecated [`created_collection`] method
+		#[weight = <SelfWeightOf<T>>::create_collection()]
+		#[transactional]
+		pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+			let owner = ensure_signed(origin)?;
 
-			let _id = match mode {
-				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
+			let _id = match data.mode {
+				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
 				CollectionMode::Fungible(decimal_points) => {
 					// check params
 					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					<PalletFungible<T>>::init_collection(new_collection)?
+					<PalletFungible<T>>::init_collection(owner, data)?
 				}
 				CollectionMode::ReFungible => {
-					<PalletRefungible<T>>::init_collection(new_collection)?
+					<PalletRefungible<T>>::init_collection(owner, data)?
 				}
 			};
 
@@ -1099,61 +1090,12 @@
 			collection_id: CollectionId,
 			new_limit: CollectionLimits,
 		) -> DispatchResult {
-			let mut new_limit = new_limit;
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
 			let old_limit = &target_collection.limits;
 
-			macro_rules! limit_default {
-				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
-					$(
-						if let Some($new) = $new.$field {
-							let $old = $old.$field($($arg)?);
-							let _ = $new;
-							let _ = $old;
-							$check
-						} else {
-							$new.$field = $old.$field
-						}
-					)*
-				}};
-			}
-
-			limit_default!(old_limit, new_limit,
-				account_token_ownership_limit => ensure!(
-					new_limit <= MAX_TOKEN_OWNERSHIP,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsor_transfer_timeout(match target_collection.mode {
-					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-				}) => ensure!(
-					new_limit <= MAX_SPONSOR_TIMEOUT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				sponsored_data_size => ensure!(
-					new_limit <= CUSTOM_DATA_LIMIT,
-					<Error<T>>::CollectionLimitBoundsExceeded,
-				),
-				token_limit => ensure!(
-					old_limit >= new_limit && new_limit > 0,
-					<CommonError<T>>::CollectionTokenLimitExceeded
-				),
-				owner_can_transfer => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				owner_can_destroy => ensure!(
-					old_limit || !new_limit,
-					<Error<T>>::OwnerPermissionsCantBeReverted,
-				),
-				sponsored_data_rate_limit => {},
-				transfers_enabled => {},
-			);
-
-			target_collection.limits = new_limit;
+			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
 				collection_id
modifiedpallets/unique/src/tests.rsdiffbeforeafterboth
--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -5,7 +5,7 @@
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
 	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
-	TokenId,
+	TokenId, MAX_TOKEN_OWNERSHIP,
 };
 use frame_support::{assert_noop, assert_ok};
 use sp_std::convert::TryInto;
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -230,6 +230,25 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derivative(Default)]
+pub struct CreateCollectionData<AccountId> {
+	#[derivative(Default(value = "CollectionMode::NFT"))]
+	pub mode: CollectionMode,
+	pub access: Option<AccessMode>,
+	pub name: Vec<u16>,
+	pub description: Vec<u16>,
+	pub token_prefix: Vec<u8>,
+	pub offchain_schema: Vec<u8>,
+	pub schema_version: Option<SchemaVersion>,
+	pub pending_sponsor: Option<AccountId>,
+	pub limits: Option<CollectionLimits>,
+	pub variable_on_chain_schema: Vec<u8>,
+	pub const_on_chain_schema: Vec<u8>,
+	pub meta_update_permission: Option<MetaUpdatePermission>,
+}
+
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct NftItemType<AccountId> {