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
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -4,6 +4,7 @@
 use frame_support::{BoundedVec, ensure};
 use up_data_structs::{
 	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,
+	CreateCollectionData,
 };
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
@@ -142,8 +143,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: NonfungibleHandle<T>,
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
35use frame_system::{self as system, ensure_signed};35use frame_system::{self as system, ensure_signed};
36use sp_runtime::{sp_std::prelude::Vec};36use sp_runtime::{sp_std::prelude::Vec};
37use up_data_structs::{37use up_data_structs::{
38 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,38 MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
39 VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,39 OFFCHAIN_SCHEMA_LIMIT, AccessMode, CreateItemData, CollectionLimits, CollectionId,
40 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
41 NFT_SPONSOR_TRANSFER_TIMEOUT, AccessMode, Collection, CreateItemData, CollectionLimits,
42 CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,40 CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
41 CreateCollectionData,
43};42};
44use pallet_common::{43use pallet_common::{
45 account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,44 account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
81 ConfirmUnsetSponsorFail,80 ConfirmUnsetSponsorFail,
82 /// Length of items properties must be greater than 0.81 /// Length of items properties must be greater than 0.
83 EmptyArgument,82 EmptyArgument,
84 /// Collection limit bounds per collection exceeded
85 CollectionLimitBoundsExceeded,
86 /// Tried to enable permissions which are only permitted to be disabled
87 OwnerPermissionsCantBeReverted,
88 }83 }
89}84}
9085
318 // returns collection ID313 // returns collection ID
319 #[weight = <SelfWeightOf<T>>::create_collection()]314 #[weight = <SelfWeightOf<T>>::create_collection()]
320 #[transactional]315 #[transactional]
316 #[deprecated]
321 pub fn create_collection(origin,317 pub fn create_collection(origin,
322 collection_name: Vec<u16>,318 collection_name: Vec<u16>,
323 collection_description: Vec<u16>,319 collection_description: Vec<u16>,
324 token_prefix: Vec<u8>,320 token_prefix: Vec<u8>,
325 mode: CollectionMode) -> DispatchResult {321 mode: CollectionMode) -> DispatchResult {
326
327 // Anyone can create a collection
328 let who = ensure_signed(origin)?;322 Self::create_collection_ex(origin, CreateCollectionData {
329
330 // Create new collection
331 let new_collection = Collection {
332 owner: who,
333 name: collection_name,323 name: collection_name,
334 mode: mode.clone(),
335 mint_mode: false,
336 access: AccessMode::Normal,
337 description: collection_description,324 description: collection_description,
338 token_prefix,325 token_prefix,
339 offchain_schema: Vec::new(),326 mode,
340 schema_version: SchemaVersion::ImageURL,327 ..Default::default()
341 sponsorship: SponsorshipState::Disabled,328 })
342 variable_on_chain_schema: Vec::new(),329 }
330
331 /// This method creates a collection
332 ///
333 /// Prefer it to deprecated [`created_collection`] method
343 const_on_chain_schema: Vec::new(),334 #[weight = <SelfWeightOf<T>>::create_collection()]
335 #[transactional]
344 limits: Default::default(),336 pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
345 meta_update_permission: Default::default(),337 let owner = ensure_signed(origin)?;
346 };
347338
348 let _id = match mode {339 let _id = match data.mode {
349 CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},340 CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
350 CollectionMode::Fungible(decimal_points) => {341 CollectionMode::Fungible(decimal_points) => {
351 // check params342 // check params
352 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);343 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
353 <PalletFungible<T>>::init_collection(new_collection)?344 <PalletFungible<T>>::init_collection(owner, data)?
354 }345 }
355 CollectionMode::ReFungible => {346 CollectionMode::ReFungible => {
356 <PalletRefungible<T>>::init_collection(new_collection)?347 <PalletRefungible<T>>::init_collection(owner, data)?
357 }348 }
358 };349 };
359350
360 Ok(())351 Ok(())
361 }352 }
362353
363 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.354 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.
364 ///355 ///
1099 collection_id: CollectionId,1090 collection_id: CollectionId,
1100 new_limit: CollectionLimits,1091 new_limit: CollectionLimits,
1101 ) -> DispatchResult {1092 ) -> DispatchResult {
1102 let mut new_limit = new_limit;
1103 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1093 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1104 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1094 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1105 target_collection.check_is_owner(&sender)?;1095 target_collection.check_is_owner(&sender)?;
1106 let old_limit = &target_collection.limits;1096 let old_limit = &target_collection.limits;
11071097
1108 macro_rules! limit_default {
1109 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
1110 $(
1111 if let Some($new) = $new.$field {1098 target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
1112 let $old = $old.$field($($arg)?);
1113 let _ = $new;
1114 let _ = $old;
1115 $check
1116 } else {
1117 $new.$field = $old.$field
1118 }
1119 )*
1120 }};
1121 }
1122
1123 limit_default!(old_limit, new_limit,
1124 account_token_ownership_limit => ensure!(
1125 new_limit <= MAX_TOKEN_OWNERSHIP,
1126 <Error<T>>::CollectionLimitBoundsExceeded,
1127 ),
1128 sponsor_transfer_timeout(match target_collection.mode {
1129 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
1130 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
1131 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
1132 }) => ensure!(
1133 new_limit <= MAX_SPONSOR_TIMEOUT,
1134 <Error<T>>::CollectionLimitBoundsExceeded,
1135 ),
1136 sponsored_data_size => ensure!(
1137 new_limit <= CUSTOM_DATA_LIMIT,
1138 <Error<T>>::CollectionLimitBoundsExceeded,
1139 ),
1140 token_limit => ensure!(
1141 old_limit >= new_limit && new_limit > 0,
1142 <CommonError<T>>::CollectionTokenLimitExceeded
1143 ),
1144 owner_can_transfer => ensure!(
1145 old_limit || !new_limit,
1146 <Error<T>>::OwnerPermissionsCantBeReverted,
1147 ),
1148 owner_can_destroy => ensure!(
1149 old_limit || !new_limit,
1150 <Error<T>>::OwnerPermissionsCantBeReverted,
1151 ),
1152 sponsored_data_rate_limit => {},
1153 transfers_enabled => {},
1154 );
1155
1156 target_collection.limits = new_limit;
11571099
1158 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(1100 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
1159 collection_id1101 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> {