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

difftreelog

chore add transfer events for transfering from and to partial ownership

Grigoriy Simonov2022-08-03parent: #abc6b05.patch.diff
in: master

3 files changed

modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,9 +34,8 @@
 		CommonEvmHandler, CollectionCall,
 		static_property::{key, value as property_value},
 	},
-	eth::collection_id_to_address,
 };
-use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm, PrecompileHandle};
+use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::{call, dispatch_to_evm};
 use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
 use sp_core::H160;
@@ -51,6 +50,8 @@
 	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,
 };
 
+pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);
+
 /// @title A contract that allows to set and delete token properties and change token property permissions.
 #[solidity_interface(name = "TokenProperties")]
 impl<T: Config> RefungibleHandle<T> {
@@ -298,13 +299,20 @@
 		Ok(balance.into())
 	}
 
+	/// @notice Find the owner of an RFT
+	/// @dev RFTs assigned to zero address are considered invalid, and queries
+	///  about them do throw.
+	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for
+	///  the tokens that are partially owned.
+	/// @param tokenId The identifier for an RFT
+	/// @return The address of the owner of the RFT
 	fn owner_of(&self, token_id: uint256) -> Result<address> {
 		self.consume_store_reads(2)?;
 		let token = token_id.try_into()?;
 		let owner = <Pallet<T>>::token_owner(self.id, token);
 		Ok(owner
 			.map(|address| *address.as_eth())
-			.unwrap_or_else(|| H160::default()))
+			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))
 	}
 
 	/// @dev Not implemented
@@ -366,14 +374,6 @@
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)
 			.map_err(dispatch_to_evm::<T>)?;
 
-		<PalletEvm<T>>::deposit_log(
-			ERC721Events::Transfer {
-				from: *from.as_eth(),
-				to: *to.as_eth(),
-				token_id: token_id.into(),
-			}
-			.to_log(collection_id_to_address(self.id)),
-		);
 		Ok(())
 	}
 
@@ -652,14 +652,6 @@
 
 		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)
 			.map_err(dispatch_to_evm::<T>)?;
-		<PalletEvm<T>>::deposit_log(
-			ERC721Events::Transfer {
-				from: *caller.as_eth(),
-				to: *to.as_eth(),
-				token_id: token_id.into(),
-			}
-			.to_log(collection_id_to_address(self.id)),
-		);
 		Ok(())
 	}
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
707 }707 }
708 <PalletCommon<T>>::ensure_correct_receiver(to)?;708 <PalletCommon<T>>::ensure_correct_receiver(to)?;
709709
710 let balance_from = <Balance<T>>::get((collection.id, token, from))710 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
711 let updated_balance_from = initial_balance_from
711 .checked_sub(amount)712 .checked_sub(amount)
712 .ok_or(<CommonError<T>>::TokenValueTooLow)?;713 .ok_or(<CommonError<T>>::TokenValueTooLow)?;
713 let mut create_target = false;714 let mut create_target = false;
714 let from_to_differ = from != to;715 let from_to_differ = from != to;
715 let balance_to = if from != to {716 let updated_balance_to = if from != to {
716 let old_balance = <Balance<T>>::get((collection.id, token, to));717 let old_balance = <Balance<T>>::get((collection.id, token, to));
717 if old_balance == 0 {718 if old_balance == 0 {
718 create_target = true;719 create_target = true;
726 None727 None
727 };728 };
728729
729 let account_balance_from = if balance_from == 0 {730 let account_balance_from = if updated_balance_from == 0 {
730 Some(731 Some(
731 <AccountBalance<T>>::get((collection.id, from))732 <AccountBalance<T>>::get((collection.id, from))
732 .checked_sub(1)733 .checked_sub(1)
762 nesting_budget,763 nesting_budget,
763 )?;764 )?;
764765
765 if let Some(balance_to) = balance_to {766 if let Some(updated_balance_to) = updated_balance_to {
766 // from != to767 // from != to
767 if balance_from == 0 {768 if updated_balance_from == 0 {
768 <Balance<T>>::remove((collection.id, token, from));769 <Balance<T>>::remove((collection.id, token, from));
769 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);770 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
770 } else {771 } else {
771 <Balance<T>>::insert((collection.id, token, from), balance_from);772 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);
772 }773 }
773 <Balance<T>>::insert((collection.id, token, to), balance_to);774 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);
774 if let Some(account_balance_from) = account_balance_from {775 if let Some(account_balance_from) = account_balance_from {
775 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);776 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);
776 <Owned<T>>::remove((collection.id, from, token));777 <Owned<T>>::remove((collection.id, from, token));
801 amount,802 amount,
802 ));803 ));
804
805 let total_supply = <TotalSupply<T>>::get((collection.id, token));
806
807 if amount == total_supply {
808 // if token was fully owned by `from` and will be fully owned by `to` after transfer
809 <PalletEvm<T>>::deposit_log(
810 ERC721Events::Transfer {
811 from: *from.as_eth(),
812 to: *to.as_eth(),
813 token_id: token.into(),
814 }
815 .to_log(collection_id_to_address(collection.id)),
816 );
817 } else if let Some(updated_balance_to) = updated_balance_to {
818 // if `from` not equals `to`. This condition is needed to avoid sending event
819 // when `from` fully owns token and sends part of token pieces to itself.
820 if initial_balance_from == total_supply {
821 // if token was fully owned by `from` and will be only partially owned by `to`
822 // and `from` after transfer
823 <PalletEvm<T>>::deposit_log(
824 ERC721Events::Transfer {
825 from: *from.as_eth(),
826 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
827 token_id: token.into(),
828 }
829 .to_log(collection_id_to_address(collection.id)),
830 );
831 } else if updated_balance_to == total_supply {
832 // if token was partially owned by `from` and will be fully owned by `to` after transfer
833 <PalletEvm<T>>::deposit_log(
834 ERC721Events::Transfer {
835 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
836 to: *to.as_eth(),
837 token_id: token.into(),
838 }
839 .to_log(collection_id_to_address(collection.id)),
840 );
841 }
842 }
843
803 Ok(())844 Ok(())
804 }845 }
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {createCollectionExpectSuccess, UNIQUE} from '../util/helpers';
+import {createCollectionExpectSuccess, transfer, UNIQUE} from '../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, tokenIdToAddress} from './util/helpers';
 import reFungibleAbi from './reFungibleAbi.json';
 import reFungibleTokenAbi from './reFungibleTokenAbi.json';
@@ -96,6 +96,28 @@
 
     expect(owner).to.equal(receiver);
   });
+
+  itWeb3('ownerOf for partial ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const owner = await contract.methods.ownerOf(tokenId).call();
+
+    expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+  });
 });
 
 describe('Refungible: Plain calls', () => {
@@ -293,6 +315,74 @@
       expect(+balance).to.equal(1);
     }
   });
+
+  itWeb3('transfer event on transfer from partial ownership to full ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    let transfer;
+    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+    await tokenContract.methods.transfer(receiver, 1).send();
+    const events = normalizeEvents([transfer]);
+    expect(events).to.deep.equal([
+      {
+        address: collectionIdAddress,
+        event: 'Transfer',
+        args: {
+          from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+          to: receiver,
+          tokenId: tokenId.toString(),
+        },
+      },
+    ]);
+  });
+
+  itWeb3('transfer event on transfer from full ownership to partial ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    
+    let transfer;
+    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const events = normalizeEvents([transfer]);
+    expect(events).to.deep.equal([
+      {
+        address: collectionIdAddress,
+        event: 'Transfer',
+        args: {
+          from: caller,
+          to: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+          tokenId: tokenId.toString(),
+        },
+      },
+    ]);
+  });
 });
 
 describe('RFT: Fees', () => {