git.delta.rocks / unique-network / refs/commits / 5e4ac1639557

difftreelog

Merge pull request #542 from UniqueNetwork/fix/RFT_and_fractionalizer

Yaroslav Bolyukin2022-08-26parents: #eadc594 #68035dd.patch.diff
in: master

14 files changed

modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -281,15 +281,6 @@
 		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
 	}: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}
 
-	set_parent_nft_unchecked {
-		bench_init!{
-			owner: sub; collection: collection(owner);
-			sender: cross_from_sub(owner); owner: cross_sub;
-		};
-		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
-
-	}: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner,  T::CrossAccountId::from_eth(H160::default()))?}
-
 	token_owner {
 		bench_init!{
 			owner: sub; collection: collection(owner);
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
29 convert::TryInto,29 convert::TryInto,
30 ops::Deref,30 ops::Deref,
31};31};
32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
33use pallet_common::{33use pallet_common::{
34 CommonWeightInfo,34 CommonWeightInfo,
35 erc::{CommonEvmHandler, PrecompileResult, static_property::key},35 erc::{CommonEvmHandler, PrecompileResult},
36 eth::map_eth_to_id,36 eth::collection_id_to_address,
37};37};
38use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};
39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
41use sp_core::H160;
42use sp_std::vec::Vec;41use sp_std::vec::Vec;
43use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};42use up_data_structs::TokenId;
4443
45use crate::{44use crate::{
46 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,45 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,
47 TokenProperties, TotalSupply, weights::WeightInfo,46 TotalSupply, weights::WeightInfo,
48};47};
4948
50pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);49pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
5150
52#[solidity_interface(name = ERC1633)]51#[solidity_interface(name = ERC1633)]
53impl<T: Config> RefungibleTokenHandle<T> {52impl<T: Config> RefungibleTokenHandle<T> {
54 fn parent_token(&self) -> Result<address> {53 fn parent_token(&self) -> Result<address> {
55 self.consume_store_reads(2)?;
56 let props = <TokenProperties<T>>::get((self.id, self.1));
57 let key = key::parent_nft();
58
59 let key_scoped = PropertyScope::Eth
60 .apply(key)
61 .expect("property key shouldn't exceed length limit");
62 if let Some(value) = props.get(&key_scoped) {
63 Ok(H160::from_slice(value.as_slice()))54 Ok(collection_id_to_address(self.id))
64 } else {
65 Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())
66 }
67 }55 }
6856
69 fn parent_token_id(&self) -> Result<uint256> {57 fn parent_token_id(&self) -> Result<uint256> {
70 self.consume_store_reads(2)?;
71 let props = <TokenProperties<T>>::get((self.id, self.1));
72 let key = key::parent_nft();
73
74 let key_scoped = PropertyScope::Eth
75 .apply(key)
76 .expect("property key shouldn't exceed length limit");
77 if let Some(value) = props.get(&key_scoped) {
78 let nft_token_address = H160::from_slice(value.as_slice());
79 let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);
80 let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)
81 .ok_or("parent NFT should contain NFT token address")?;
82
83 Ok(token_id.into())
84 } else {
85 Ok(self.1.into())58 Ok(self.1.into())
86 }
87 }59 }
88}60}
89
90#[solidity_interface(name = ERC1633UniqueExtensions)]
91impl<T: Config> RefungibleTokenHandle<T> {
92 #[solidity(rename_selector = "setParentNFT")]
93 #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]
94 fn set_parent_nft(
95 &mut self,
96 caller: caller,
97 collection: address,
98 nft_id: uint256,
99 ) -> Result<bool> {
100 self.consume_store_reads(1)?;
101 let caller = T::CrossAccountId::from_eth(caller);
102 let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;
103 let nft_token = nft_id.try_into()?;
104
105 <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)
106 .map_err(dispatch_to_evm::<T>)?;
107
108 Ok(true)
109 }
110}
11161
112#[derive(ToLog)]62#[derive(ToLog)]
113pub enum ERC20Events {63pub enum ERC20Events {
307257
308#[solidity_interface(258#[solidity_interface(
309 name = UniqueRefungibleToken,259 name = UniqueRefungibleToken,
310 is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)260 is(ERC20, ERC20UniqueExtensions, ERC1633)
311)]261)]
312impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}262impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
313263
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1379,68 +1379,4 @@
 			Some(res)
 		}
 	}
-
-	/// Sets the NFT token as a parent for the RFT token
-	///
-	/// Throws if `sender` is not the owner of the NFT token.
-	/// Throws if `sender` is not the owner of all of the RFT token pieces.
-	pub fn set_parent_nft(
-		collection: &RefungibleHandle<T>,
-		rft_token_id: TokenId,
-		sender: T::CrossAccountId,
-		nft_collection: CollectionId,
-		nft_token: TokenId,
-	) -> DispatchResult {
-		let handle = <CollectionHandle<T>>::try_get(nft_collection)?;
-		if handle.mode != CollectionMode::NFT {
-			return Err("Only NFT token could be parent to RFT".into());
-		}
-		let dispatch = T::CollectionDispatch::dispatch(handle);
-		let dispatch = dispatch.as_dyn();
-
-		let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;
-		if owner != sender {
-			return Err("Only owned token could be set as parent".into());
-		}
-
-		let nft_token_address =
-			T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);
-
-		Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)
-	}
-
-	/// Sets the NFT token as a parent for the RFT token
-	///
-	/// `sender` should be the owner of the NFT token.
-	/// Throws if `sender` is not the owner of all of the RFT token pieces.
-	pub fn set_parent_nft_unchecked(
-		collection: &RefungibleHandle<T>,
-		rft_token_id: TokenId,
-		sender: T::CrossAccountId,
-		nft_token_address: T::CrossAccountId,
-	) -> DispatchResult {
-		let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));
-		let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));
-		if total_supply != owner_balance {
-			return Err("token has multiple owners".into());
-		}
-
-		let parent_nft_property_key = key::parent_nft();
-
-		let parent_nft_property_value =
-			property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())
-				.expect("address should fit in value length limit");
-
-		<Pallet<T>>::set_scoped_token_property(
-			collection.id,
-			rft_token_id,
-			PropertyScope::Eth,
-			Property {
-				key: parent_nft_property_key,
-				value: parent_nft_property_value,
-			},
-		)?;
-
-		Ok(())
-	}
 }
modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -21,22 +21,6 @@
 	}
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-contract ERC1633UniqueExtensions is Dummy, ERC165 {
-	/// @dev EVM selector for this function is: 0x042f1106,
-	///  or in textual repr: setParentNFT(address,uint256)
-	function setParentNFT(address collection, uint256 nftId)
-		public
-		returns (bool)
-	{
-		require(false, stub_error);
-		collection;
-		nftId;
-		dummy = 0;
-		return false;
-	}
-}
-
 /// @dev the ERC-165 identifier for this interface is 0x5755c3f2
 contract ERC1633 is Dummy, ERC165 {
 	/// @dev EVM selector for this function is: 0x80a54001,
@@ -222,6 +206,5 @@
 	ERC165,
 	ERC20,
 	ERC20UniqueExtensions,
-	ERC1633,
-	ERC1633UniqueExtensions
+	ERC1633
 {}
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -53,7 +53,6 @@
 	fn set_token_properties(b: u32, ) -> Weight;
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn repartition_item() -> Weight;
-	fn set_parent_nft_unchecked() -> Weight;
 	fn token_owner() -> Weight;
 }
 
@@ -254,14 +253,6 @@
 		(22_356_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
-	}
-	// Storage: Refungible Balance (r:1 w:0)
-	// Storage: Refungible TotalSupply (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
-	fn set_parent_nft_unchecked() -> Weight {
-		(12_015_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(3 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible Balance (r:2 w:0)
 	fn token_owner() -> Weight {
@@ -466,14 +457,6 @@
 		(22_356_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
-	}
-	// Storage: Refungible Balance (r:1 w:0)
-	// Storage: Refungible TotalSupply (r:1 w:0)
-	// Storage: Refungible TokenProperties (r:1 w:1)
-	fn set_parent_nft_unchecked() -> Weight {
-		(12_015_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible Balance (r:2 w:0)
 	fn token_owner() -> Weight {
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -154,17 +154,6 @@
 	Ok(data)
 }
 
-fn parent_nft_property_permissions() -> PropertyKeyPermission {
-	PropertyKeyPermission {
-		key: key::parent_nft(),
-		permission: PropertyPermission {
-			mutable: false,
-			collection_admin: false,
-			token_owner: true,
-		},
-	}
-}
-
 fn create_refungible_collection_internal<
 	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
 >(
@@ -188,16 +177,6 @@
 
 	let collection_id = T::CollectionDispatch::create(caller.clone(), data)
 		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
-	let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;
-	<PalletCommon<T>>::set_scoped_token_property_permissions(
-		&handle,
-		&caller,
-		PropertyScope::Eth,
-		vec![parent_nft_property_permissions()],
-	)
-	.map_err(dispatch_to_evm::<T>)?;
-
 	let address = pallet_common::eth::collection_id_to_address(collection_id);
 	Ok(address)
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1050,7 +1050,6 @@
 pub enum PropertyScope {
 	None,
 	Rmrk,
-	Eth,
 }
 
 impl PropertyScope {
@@ -1059,7 +1058,6 @@
 		let scope_str: &[u8] = match self {
 			Self::None => return Ok(key),
 			Self::Rmrk => b"rmrk",
-			Self::Eth => b"eth",
 		};
 
 		[scope_str, b":", key.as_slice()]
modifiedtests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -12,15 +12,6 @@
 	function supportsInterface(bytes4 interfaceID) external view returns (bool);
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-interface ERC1633UniqueExtensions is Dummy, ERC165 {
-	/// @dev EVM selector for this function is: 0x042f1106,
-	///  or in textual repr: setParentNFT(address,uint256)
-	function setParentNFT(address collection, uint256 nftId)
-		external
-		returns (bool);
-}
-
 /// @dev the ERC-165 identifier for this interface is 0x5755c3f2
 interface ERC1633 is Dummy, ERC165 {
 	/// @dev EVM selector for this function is: 0x80a54001,
@@ -140,6 +131,5 @@
 	ERC165,
 	ERC20,
 	ERC20UniqueExtensions,
-	ERC1633,
-	ERC1633UniqueExtensions
+	ERC1633
 {}
modifiedtests/src/eth/base.test.tsdiffbeforeafterboth
--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -94,7 +94,7 @@
   });
 
   itWeb3('ERC721 support', async ({web3}) => {
-    expect(await contract(web3).methods.supportsInterface('0x58800161').call()).to.be.true;
+    expect(await contract(web3).methods.supportsInterface('0x780e9d63').call()).to.be.true;
   });
 
   itWeb3('ERC721Metadata support', async ({web3}) => {
modifiedtests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -16,8 +16,8 @@
     }
     address rftCollection;
     mapping(address => bool) nftCollectionAllowList;
-    mapping(address => mapping(uint256 => uint256)) nft2rftMapping;
-    mapping(address => Token) rft2nftMapping;
+    mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;
+    mapping(address => Token) public rft2nftMapping;
     bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
 
     receive() external payable onlyOwner {}
@@ -137,7 +137,6 @@
             rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
 
             rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
-            rftTokenContract.setParentNFT(_collection, _token);
         } else {
             rftTokenId = nft2rftMapping[_collection][_token];
             rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
modifiedtests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -223,6 +223,28 @@
       },
     });
   });
+
+  itWeb3('Test fractionalizer NFT <-> RFT mapping ', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);
+
+    const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);
+    const refungibleAddress = collectionIdToAddress(collectionId);
+    expect(rftCollectionAddress).to.be.equal(refungibleAddress);
+    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();
+
+    const rft2nft = await fractionalizer.methods.rft2nftMapping(rftTokenAddress).call();
+    expect(rft2nft).to.be.like({
+      _collection: nftCollectionAddress,
+      _tokenId: nftTokenId,
+    });
+
+    const nft2rft = await fractionalizer.methods.nft2rftMapping(nftCollectionAddress, nftTokenId).call();
+    expect(nft2rft).to.be.eq(tokenId.toString());
+  });
 });
 
 
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -655,31 +655,6 @@
     await requirePallets(this, [Pallets.ReFungible]);
   });
 
-  itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const {collectionIdAddress:  nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
-    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send();
-    const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);
-
-    const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
-    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
-    const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
-    await refungibleContract.methods.mint(owner, refungibleTokenId).send();
-
-    const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
-    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
-    await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();
-
-    const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
-    const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
-    const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);
-    expect(tokenAddress).to.be.equal(nftTokenAddress);
-    expect(tokenId).to.be.equal(nftTokenId);
-  });
-
   itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
 
@@ -693,7 +668,7 @@
 
     const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
     const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
-    expect(tokenAddress).to.be.equal(rftTokenAddress);
+    expect(tokenAddress).to.be.equal(collectionIdAddress);
     expect(tokenId).to.be.equal(refungibleTokenId);
   });
 });
modifiedtests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleTokenAbi.json
+++ b/tests/src/eth/reFungibleTokenAbi.json
@@ -127,16 +127,6 @@
   },
   {
     "inputs": [
-      { "internalType": "address", "name": "collection", "type": "address" },
-      { "internalType": "uint256", "name": "nftId", "type": "uint256" }
-    ],
-    "name": "setParentNFT",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
     ],
     "name": "supportsInterface",