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

difftreelog

refactor remove "invalid" collection mode

Yaroslav Bolyukin2021-09-14parent: #d15a825.patch.diff
in: master

7 files changed

modifiedpallets/nft/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/mod.rs
+++ b/pallets/nft/src/eth/mod.rs
@@ -103,7 +103,6 @@
 					CollectionMode::ReFungible => {
 						include_bytes!("stubs/UniqueRefungible.raw") as &[u8]
 					}
-					CollectionMode::Invalid => include_bytes!("stubs/UniqueInvalid.raw") as &[u8],
 				}
 				.to_owned()
 			})
deletedpallets/nft/src/eth/stubs/UniqueInvalid.rawdiffbeforeafterboth
--- a/pallets/nft/src/eth/stubs/UniqueInvalid.raw
+++ /dev/null
@@ -1 +0,0 @@
-TODO
\ No newline at end of file
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -1347,7 +1347,6 @@
 				sender.clone(),
 				recipient.clone(),
 			)?,
-			_ => (),
 		};
 
 		Self::deposit_event(RawEvent::Transfer(
@@ -1493,7 +1492,6 @@
 				from.clone(),
 				recipient.clone(),
 			)?,
-			_ => (),
 		};
 
 		if matches!(collection.mode, CollectionMode::Fungible(_)) {
@@ -1534,7 +1532,6 @@
 				Self::set_re_fungible_variable_data(collection, item_id, data)?
 			}
 			CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
-			_ => fail!(Error::<T>::UnexpectedCollectionType),
 		};
 
 		Ok(())
@@ -1618,7 +1615,6 @@
 			CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,
 			CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,
 			CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,
-			_ => (),
 		};
 
 		Ok(())
@@ -1723,9 +1719,6 @@
 					fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);
 				}
 			}
-			_ => {
-				fail!(Error::<T>::UnexpectedCollectionType);
-			}
 		};
 
 		Ok(())
@@ -2034,7 +2027,6 @@
 				.iter()
 				.find(|i| i.owner == *subject)
 				.map(|i| i.fraction),
-			CollectionMode::Invalid => None,
 		}
 	}
 
@@ -2071,7 +2063,6 @@
 			CollectionMode::ReFungible => {
 				<ReFungibleItemList<T>>::contains_key(collection_id, item_id)
 			}
-			_ => false,
 		};
 
 		ensure!(exists, Error::<T>::TokenNotFound);
modifiedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
before · pallets/nft/src/sponsorship.rs
1use crate::{2	Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,3	ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, CreateItemData,4	CollectionMode,5};6use core::marker::PhantomData;7use up_sponsorship::SponsorshipHandler;8use frame_support::{9	traits::{IsSubType},10	storage::{StorageMap, StorageDoubleMap},11};12use nft_data_structs::{13	TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,14	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,15};1617pub struct NftSponsorshipHandler<T>(PhantomData<T>);18impl<T: Config> NftSponsorshipHandler<T> {19	pub fn withdraw_create_item(20		who: &T::AccountId,21		collection_id: &CollectionId,22		_properties: &CreateItemData,23	) -> Option<T::AccountId> {24		let collection = CollectionById::<T>::get(collection_id)?;2526		// sponsor timeout27		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;2829		let limit = collection.limits.sponsor_transfer_timeout;30		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {31			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));32			let limit_time = last_tx_block + limit.into();33			if block_number <= limit_time {34				return None;35			}36		}37		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);3839		// check free create limit40		if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {41			collection.sponsorship.sponsor().cloned()42		} else {43			None44		}45	}4647	pub fn withdraw_transfer(48		who: &T::AccountId,49		collection_id: &CollectionId,50		item_id: &TokenId,51	) -> Option<T::AccountId> {52		let collection = CollectionById::<T>::get(collection_id)?;5354		let mut sponsor_transfer = false;55		if collection.sponsorship.confirmed() {56			let collection_limits = collection.limits.clone();57			let collection_mode = collection.mode.clone();5859			// sponsor timeout60			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;61			sponsor_transfer = match collection_mode {62				CollectionMode::NFT => {63					// get correct limit64					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {65						collection_limits.sponsor_transfer_timeout66					} else {67						NFT_SPONSOR_TRANSFER_TIMEOUT68					};6970					let mut sponsored = true;71					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {72						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);73						let limit_time = last_tx_block + limit.into();74						if block_number <= limit_time {75							sponsored = false;76						}77					}78					if sponsored {79						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);80					}8182					sponsored83				}84				CollectionMode::Fungible(_) => {85					// get correct limit86					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {87						collection_limits.sponsor_transfer_timeout88					} else {89						FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT90					};9192					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;93					let mut sponsored = true;94					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {95						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);96						let limit_time = last_tx_block + limit.into();97						if block_number <= limit_time {98							sponsored = false;99						}100					}101					if sponsored {102						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);103					}104105					sponsored106				}107				CollectionMode::ReFungible => {108					// get correct limit109					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {110						collection_limits.sponsor_transfer_timeout111					} else {112						REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT113					};114115					let mut sponsored = true;116					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {117						let last_tx_block =118							ReFungibleTransferBasket::<T>::get(collection_id, item_id);119						let limit_time = last_tx_block + limit.into();120						if block_number <= limit_time {121							sponsored = false;122						}123					}124					if sponsored {125						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);126					}127128					sponsored129				}130				_ => false,131			};132		}133134		if !sponsor_transfer {135			None136		} else {137			collection.sponsorship.sponsor().cloned()138		}139	}140141	pub fn withdraw_set_variable_meta_data(142		collection_id: &CollectionId,143		item_id: &TokenId,144		data: &[u8],145	) -> Option<T::AccountId> {146		let mut sponsor_metadata_changes = false;147148		let collection = CollectionById::<T>::get(collection_id)?;149150		if collection.sponsorship.confirmed() &&151			// Can't sponsor fungible collection, this tx will be rejected152			// as invalid153			!matches!(collection.mode, CollectionMode::Fungible(_)) &&154			data.len() <= collection.limits.sponsored_data_size as usize155		{156			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {157				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;158159				if VariableMetaDataBasket::<T>::get(collection_id, item_id)160					.map(|last_block| block_number - last_block > rate_limit)161					.unwrap_or(true)162				{163					sponsor_metadata_changes = true;164					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);165				}166			}167		}168169		if !sponsor_metadata_changes {170			None171		} else {172			collection.sponsorship.sponsor().cloned()173		}174	}175}176177impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>178where179	T: Config,180	C: IsSubType<Call<T>>,181{182	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {183		match IsSubType::<Call<T>>::is_sub_type(call)? {184			Call::create_item(collection_id, _owner, properties) => {185				Self::withdraw_create_item(who, collection_id, properties)186			}187			Call::transfer(_new_owner, collection_id, item_id, _value) => {188				Self::withdraw_transfer(who, collection_id, item_id)189			}190			Call::set_variable_meta_data(collection_id, item_id, data) => {191				Self::withdraw_set_variable_meta_data(collection_id, item_id, data)192			}193			_ => None,194		}195	}196}
after · pallets/nft/src/sponsorship.rs
1use crate::{2	Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,3	ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, CreateItemData,4	CollectionMode,5};6use core::marker::PhantomData;7use up_sponsorship::SponsorshipHandler;8use frame_support::{9	traits::{IsSubType},10	storage::{StorageMap, StorageDoubleMap},11};12use nft_data_structs::{13	TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,14	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,15};1617pub struct NftSponsorshipHandler<T>(PhantomData<T>);18impl<T: Config> NftSponsorshipHandler<T> {19	pub fn withdraw_create_item(20		who: &T::AccountId,21		collection_id: &CollectionId,22		_properties: &CreateItemData,23	) -> Option<T::AccountId> {24		let collection = CollectionById::<T>::get(collection_id)?;2526		// sponsor timeout27		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;2829		let limit = collection.limits.sponsor_transfer_timeout;30		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {31			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));32			let limit_time = last_tx_block + limit.into();33			if block_number <= limit_time {34				return None;35			}36		}37		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);3839		// check free create limit40		if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {41			collection.sponsorship.sponsor().cloned()42		} else {43			None44		}45	}4647	pub fn withdraw_transfer(48		who: &T::AccountId,49		collection_id: &CollectionId,50		item_id: &TokenId,51	) -> Option<T::AccountId> {52		let collection = CollectionById::<T>::get(collection_id)?;5354		let mut sponsor_transfer = false;55		if collection.sponsorship.confirmed() {56			let collection_limits = collection.limits.clone();57			let collection_mode = collection.mode.clone();5859			// sponsor timeout60			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;61			sponsor_transfer = match collection_mode {62				CollectionMode::NFT => {63					// get correct limit64					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {65						collection_limits.sponsor_transfer_timeout66					} else {67						NFT_SPONSOR_TRANSFER_TIMEOUT68					};6970					let mut sponsored = true;71					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {72						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);73						let limit_time = last_tx_block + limit.into();74						if block_number <= limit_time {75							sponsored = false;76						}77					}78					if sponsored {79						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);80					}8182					sponsored83				}84				CollectionMode::Fungible(_) => {85					// get correct limit86					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {87						collection_limits.sponsor_transfer_timeout88					} else {89						FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT90					};9192					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;93					let mut sponsored = true;94					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {95						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);96						let limit_time = last_tx_block + limit.into();97						if block_number <= limit_time {98							sponsored = false;99						}100					}101					if sponsored {102						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);103					}104105					sponsored106				}107				CollectionMode::ReFungible => {108					// get correct limit109					let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {110						collection_limits.sponsor_transfer_timeout111					} else {112						REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT113					};114115					let mut sponsored = true;116					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {117						let last_tx_block =118							ReFungibleTransferBasket::<T>::get(collection_id, item_id);119						let limit_time = last_tx_block + limit.into();120						if block_number <= limit_time {121							sponsored = false;122						}123					}124					if sponsored {125						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);126					}127128					sponsored129				}130			};131		}132133		if !sponsor_transfer {134			None135		} else {136			collection.sponsorship.sponsor().cloned()137		}138	}139140	pub fn withdraw_set_variable_meta_data(141		collection_id: &CollectionId,142		item_id: &TokenId,143		data: &[u8],144	) -> Option<T::AccountId> {145		let mut sponsor_metadata_changes = false;146147		let collection = CollectionById::<T>::get(collection_id)?;148149		if collection.sponsorship.confirmed() &&150			// Can't sponsor fungible collection, this tx will be rejected151			// as invalid152			!matches!(collection.mode, CollectionMode::Fungible(_)) &&153			data.len() <= collection.limits.sponsored_data_size as usize154		{155			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {156				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;157158				if VariableMetaDataBasket::<T>::get(collection_id, item_id)159					.map(|last_block| block_number - last_block > rate_limit)160					.unwrap_or(true)161				{162					sponsor_metadata_changes = true;163					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);164				}165			}166		}167168		if !sponsor_metadata_changes {169			None170		} else {171			collection.sponsorship.sponsor().cloned()172		}173	}174}175176impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>177where178	T: Config,179	C: IsSubType<Call<T>>,180{181	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {182		match IsSubType::<Call<T>>::is_sub_type(call)? {183			Call::create_item(collection_id, _owner, properties) => {184				Self::withdraw_create_item(who, collection_id, properties)185			}186			Call::transfer(_new_owner, collection_id, item_id, _value) => {187				Self::withdraw_transfer(who, collection_id, item_id)188			}189			Call::set_variable_meta_data(collection_id, item_id, data) => {190				Self::withdraw_set_variable_meta_data(collection_id, item_id, data)191			}192			_ => None,193		}194	}195}
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -73,23 +73,15 @@
 #[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub enum CollectionMode {
-	Invalid,
 	NFT,
 	// decimal points
 	Fungible(DecimalPoints),
 	ReFungible,
-}
-
-impl Default for CollectionMode {
-	fn default() -> Self {
-		Self::Invalid
-	}
 }
 
 impl CollectionMode {
 	pub fn id(&self) -> u8 {
 		match self {
-			CollectionMode::Invalid => 0,
 			CollectionMode::NFT => 1,
 			CollectionMode::Fungible(_) => 2,
 			CollectionMode::ReFungible => 3,
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -33,19 +33,6 @@
 });
 
 describe('(!negative test!) integration test: ext. createCollection():', () => {
-  it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
-    await usingApi(async (api) => {
-      const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
-
-      const badTransaction = async () => {
-        await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
-      };
-      await expect(badTransaction()).to.be.rejected;
-
-      const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
-      expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
-    });
-  });
   it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
     await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
   });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -224,10 +224,6 @@
   return result;
 }
 
-interface Invalid {
-  type: 'Invalid';
-}
-
 interface Nft {
   type: 'NFT';
 }
@@ -241,7 +237,7 @@
   type: 'ReFungible';
 }
 
-type CollectionMode = Nft | Fungible | ReFungible | Invalid;
+type CollectionMode = Nft | Fungible | ReFungible;
 
 export type CreateCollectionParams = {
   mode: CollectionMode,
@@ -275,8 +271,6 @@
       modeprm = { fungible: mode.decimalPoints };
     } else if (mode.type === 'ReFungible') {
       modeprm = { refungible: null };
-    } else if (mode.type === 'Invalid') {
-      modeprm = { invalid: null };
     }
 
     const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);
@@ -317,8 +311,6 @@
     modeprm = { fungible: mode.decimalPoints };
   } else if (mode.type === 'ReFungible') {
     modeprm = { refungible: null };
-  } else if (mode.type === 'Invalid') {
-    modeprm = { invalid: null };
   }
 
   await usingApi(async (api) => {
@@ -528,23 +520,23 @@
 export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {
 
   await usingApi(async (api) => {
-    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 
+    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag);
     const events = await submitTransactionAsync(sender, tx);
     const result = getGenericResult(events);
 
     expect(result.success).to.be.true;
-  }); 
+  });
 }
 
 export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {
 
   await usingApi(async (api) => {
-    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 
+    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag);
     const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
     const result = getGenericResult(events);
 
     expect(result.success).to.be.false;
-  }); 
+  });
 }
 
 export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
@@ -576,7 +568,7 @@
     const result = getGenericResult(events);
 
     expect(result.success).to.be.true;
-  }); 
+  });
 }
 
 export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
@@ -588,7 +580,7 @@
     const result = getGenericResult(events);
 
     expect(result.success).to.be.false;
-  }); 
+  });
 }
 
 export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
@@ -833,7 +825,7 @@
     const expectedBlockNumber = blockNumber + blockSchedule;
 
     expect(blockNumber).to.be.greaterThan(0);
-    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 
+    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
     const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);
 
     await submitTransactionAsync(sender, scheduleTx);
@@ -1004,7 +996,7 @@
 export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {
   await usingApi(async (api) => {
     const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);
-    
+
     const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
     const result = getCreateItemResult(events);