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
before · pallets/nft/src/eth/mod.rs
1pub mod account;2pub mod erc;3pub mod sponsoring;45use pallet_evm_coder_substrate::call_internal;6use sp_std::borrow::ToOwned;7use sp_std::vec::Vec;8use pallet_evm::{PrecompileOutput};9use sp_core::{H160, U256};10use frame_support::storage::StorageMap;11use crate::{Config, CollectionById, CollectionHandle, CollectionId, CollectionMode};12use erc::{UniqueFungibleCall, UniqueNFTCall};1314pub struct NftErcSupport<T: Config>(core::marker::PhantomData<T>);1516// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection17// TODO: Unhardcode prefix18const ETH_ACCOUNT_PREFIX: [u8; 16] = [19	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,20];2122fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {23	if eth[0..16] != ETH_ACCOUNT_PREFIX {24		return None;25	}26	let mut id_bytes = [0; 4];27	id_bytes.copy_from_slice(&eth[16..20]);28	Some(u32::from_be_bytes(id_bytes))29}30pub fn collection_id_to_address(id: u32) -> H160 {31	let mut out = [0; 20];32	out[0..16].copy_from_slice(&ETH_ACCOUNT_PREFIX);33	out[16..20].copy_from_slice(&u32::to_be_bytes(id));34	H160(out)35}3637/*38fn call_internal<T: Config>(39	collection: &mut CollectionHandle<T>,40	caller: caller,41	method_id: u32,42	mut input: AbiReader,43	value: U256,44) -> Result<Option<AbiWriter>> {45	match collection.mode.clone() {46		CollectionMode::Fungible(_) => {47			call_internal();48			let call = match UniqueFungibleCall::parse(method_id, &mut input)? {49				Some(v) => v,50				None => {51					#[cfg(feature = "std")]52					{53						println!("Method not found");54					}55					return Ok(None);56				}57			};58			Ok(Some(<CollectionHandle<T> as UniqueFungible>::call(59				collection,60				Msg {61					call,62					caller,63					value,64				},65			)?))66		}67		CollectionMode::NFT => {68			let call = match UniqueNFTCall::parse(method_id, &mut input)? {69				Some(v) => v,70				None => return Ok(None),71			};72			Ok(Some(<CollectionHandle<T> as UniqueNFT>::call(73				collection,74				Msg {75					call,76					caller,77					value,78				},79			)?))80		}81		_ => Err("erc calls only supported to fungible and nft collections for now".into()),82	}83}*/8485impl<T: Config> pallet_evm::OnMethodCall<T> for NftErcSupport<T> {86	fn is_reserved(target: &H160) -> bool {87		map_eth_to_id(target).is_some()88	}89	fn is_used(target: &H160) -> bool {90		map_eth_to_id(target)91			.map(<CollectionById<T>>::contains_key)92			.unwrap_or(false)93	}94	fn get_code(target: &H160) -> Option<Vec<u8>> {95		map_eth_to_id(target)96			.and_then(<CollectionById<T>>::get)97			.map(|collection| {98				match collection.mode {99					CollectionMode::NFT => include_bytes!("stubs/UniqueNFT.raw") as &[u8],100					CollectionMode::Fungible(_) => {101						include_bytes!("stubs/UniqueFungible.raw") as &[u8]102					}103					CollectionMode::ReFungible => {104						include_bytes!("stubs/UniqueRefungible.raw") as &[u8]105					}106					CollectionMode::Invalid => include_bytes!("stubs/UniqueInvalid.raw") as &[u8],107				}108				.to_owned()109			})110	}111	fn call(112		source: &H160,113		target: &H160,114		gas_limit: u64,115		input: &[u8],116		value: U256,117	) -> Option<PrecompileOutput> {118		let mut collection = map_eth_to_id(target)119			.and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;120		let result = match collection.mode {121			CollectionMode::NFT => {122				call_internal::<UniqueNFTCall, _>(*source, &mut collection, value, input)123			}124			CollectionMode::Fungible(_) => {125				call_internal::<UniqueFungibleCall, _>(*source, &mut collection, value, input)126			}127			_ => return None,128		};129		collection.recorder.evm_to_precompile_output(result)130	}131}
after · pallets/nft/src/eth/mod.rs
1pub mod account;2pub mod erc;3pub mod sponsoring;45use pallet_evm_coder_substrate::call_internal;6use sp_std::borrow::ToOwned;7use sp_std::vec::Vec;8use pallet_evm::{PrecompileOutput};9use sp_core::{H160, U256};10use frame_support::storage::StorageMap;11use crate::{Config, CollectionById, CollectionHandle, CollectionId, CollectionMode};12use erc::{UniqueFungibleCall, UniqueNFTCall};1314pub struct NftErcSupport<T: Config>(core::marker::PhantomData<T>);1516// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection17// TODO: Unhardcode prefix18const ETH_ACCOUNT_PREFIX: [u8; 16] = [19	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,20];2122fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {23	if eth[0..16] != ETH_ACCOUNT_PREFIX {24		return None;25	}26	let mut id_bytes = [0; 4];27	id_bytes.copy_from_slice(&eth[16..20]);28	Some(u32::from_be_bytes(id_bytes))29}30pub fn collection_id_to_address(id: u32) -> H160 {31	let mut out = [0; 20];32	out[0..16].copy_from_slice(&ETH_ACCOUNT_PREFIX);33	out[16..20].copy_from_slice(&u32::to_be_bytes(id));34	H160(out)35}3637/*38fn call_internal<T: Config>(39	collection: &mut CollectionHandle<T>,40	caller: caller,41	method_id: u32,42	mut input: AbiReader,43	value: U256,44) -> Result<Option<AbiWriter>> {45	match collection.mode.clone() {46		CollectionMode::Fungible(_) => {47			call_internal();48			let call = match UniqueFungibleCall::parse(method_id, &mut input)? {49				Some(v) => v,50				None => {51					#[cfg(feature = "std")]52					{53						println!("Method not found");54					}55					return Ok(None);56				}57			};58			Ok(Some(<CollectionHandle<T> as UniqueFungible>::call(59				collection,60				Msg {61					call,62					caller,63					value,64				},65			)?))66		}67		CollectionMode::NFT => {68			let call = match UniqueNFTCall::parse(method_id, &mut input)? {69				Some(v) => v,70				None => return Ok(None),71			};72			Ok(Some(<CollectionHandle<T> as UniqueNFT>::call(73				collection,74				Msg {75					call,76					caller,77					value,78				},79			)?))80		}81		_ => Err("erc calls only supported to fungible and nft collections for now".into()),82	}83}*/8485impl<T: Config> pallet_evm::OnMethodCall<T> for NftErcSupport<T> {86	fn is_reserved(target: &H160) -> bool {87		map_eth_to_id(target).is_some()88	}89	fn is_used(target: &H160) -> bool {90		map_eth_to_id(target)91			.map(<CollectionById<T>>::contains_key)92			.unwrap_or(false)93	}94	fn get_code(target: &H160) -> Option<Vec<u8>> {95		map_eth_to_id(target)96			.and_then(<CollectionById<T>>::get)97			.map(|collection| {98				match collection.mode {99					CollectionMode::NFT => include_bytes!("stubs/UniqueNFT.raw") as &[u8],100					CollectionMode::Fungible(_) => {101						include_bytes!("stubs/UniqueFungible.raw") as &[u8]102					}103					CollectionMode::ReFungible => {104						include_bytes!("stubs/UniqueRefungible.raw") as &[u8]105					}106				}107				.to_owned()108			})109	}110	fn call(111		source: &H160,112		target: &H160,113		gas_limit: u64,114		input: &[u8],115		value: U256,116	) -> Option<PrecompileOutput> {117		let mut collection = map_eth_to_id(target)118			.and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;119		let result = match collection.mode {120			CollectionMode::NFT => {121				call_internal::<UniqueNFTCall, _>(*source, &mut collection, value, input)122			}123			CollectionMode::Fungible(_) => {124				call_internal::<UniqueFungibleCall, _>(*source, &mut collection, value, input)125			}126			_ => return None,127		};128		collection.recorder.evm_to_precompile_output(result)129	}130}
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
--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -127,7 +127,6 @@
 
 					sponsored
 				}
-				_ => false,
 			};
 		}
 
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);