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
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -707,12 +707,13 @@
 		}
 		<PalletCommon<T>>::ensure_correct_receiver(to)?;
 
-		let balance_from = <Balance<T>>::get((collection.id, token, from))
+		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
+		let updated_balance_from = initial_balance_from
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
 		let mut create_target = false;
 		let from_to_differ = from != to;
-		let balance_to = if from != to {
+		let updated_balance_to = if from != to {
 			let old_balance = <Balance<T>>::get((collection.id, token, to));
 			if old_balance == 0 {
 				create_target = true;
@@ -726,7 +727,7 @@
 			None
 		};
 
-		let account_balance_from = if balance_from == 0 {
+		let account_balance_from = if updated_balance_from == 0 {
 			Some(
 				<AccountBalance<T>>::get((collection.id, from))
 					.checked_sub(1)
@@ -762,15 +763,15 @@
 			nesting_budget,
 		)?;
 
-		if let Some(balance_to) = balance_to {
+		if let Some(updated_balance_to) = updated_balance_to {
 			// from != to
-			if balance_from == 0 {
+			if updated_balance_from == 0 {
 				<Balance<T>>::remove((collection.id, token, from));
 				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
 			} else {
-				<Balance<T>>::insert((collection.id, token, from), balance_from);
+				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);
 			}
-			<Balance<T>>::insert((collection.id, token, to), balance_to);
+			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);
 			if let Some(account_balance_from) = account_balance_from {
 				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);
 				<Owned<T>>::remove((collection.id, from, token));
@@ -800,6 +801,46 @@
 			to.clone(),
 			amount,
 		));
+
+		let total_supply = <TotalSupply<T>>::get((collection.id, token));
+
+		if amount == total_supply {
+			// if token was fully owned by `from` and will be fully owned by `to` after transfer
+			<PalletEvm<T>>::deposit_log(
+				ERC721Events::Transfer {
+					from: *from.as_eth(),
+					to: *to.as_eth(),
+					token_id: token.into(),
+				}
+				.to_log(collection_id_to_address(collection.id)),
+			);
+		} else if let Some(updated_balance_to) = updated_balance_to {
+			// if `from` not equals `to`. This condition is needed to avoid sending event
+			// when `from` fully owns token and sends part of token pieces to itself.
+			if initial_balance_from == total_supply {
+				// if token was fully owned by `from` and will be only partially owned by `to`
+				// and `from` after transfer
+				<PalletEvm<T>>::deposit_log(
+					ERC721Events::Transfer {
+						from: *from.as_eth(),
+						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+						token_id: token.into(),
+					}
+					.to_log(collection_id_to_address(collection.id)),
+				);
+			} else if updated_balance_to == total_supply {
+				// if token was partially owned by `from` and will be fully owned by `to` after transfer
+				<PalletEvm<T>>::deposit_log(
+					ERC721Events::Transfer {
+						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+						to: *to.as_eth(),
+						token_id: token.into(),
+					}
+					.to_log(collection_id_to_address(collection.id)),
+				);
+			}
+		}
+
 		Ok(())
 	}
 
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
before · tests/src/eth/reFungible.test.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {createCollectionExpectSuccess, UNIQUE} from '../util/helpers';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, tokenIdToAddress} from './util/helpers';19import reFungibleAbi from './reFungibleAbi.json';20import reFungibleTokenAbi from './reFungibleTokenAbi.json';21import {expect} from 'chai';2223describe('Refungible: Information getting', () => {24  itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {25    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);26    const helper = evmCollectionHelpers(web3, caller);27    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();28    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);29    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});30    const nextTokenId = await contract.methods.nextTokenId().call();31    await contract.methods.mint(caller, nextTokenId).send();32    const totalSupply = await contract.methods.totalSupply().call();33    expect(totalSupply).to.equal('1');34  });3536  itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {37    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);38    const helper = evmCollectionHelpers(web3, caller);39    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();40    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);41    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});4243    {44      const nextTokenId = await contract.methods.nextTokenId().call();45      await contract.methods.mint(caller, nextTokenId).send();46    }47    {48      const nextTokenId = await contract.methods.nextTokenId().call();49      await contract.methods.mint(caller, nextTokenId).send();50    }51    {52      const nextTokenId = await contract.methods.nextTokenId().call();53      await contract.methods.mint(caller, nextTokenId).send();54    }5556    const balance = await contract.methods.balanceOf(caller).call();5758    expect(balance).to.equal('3');59  });6061  itWeb3('ownerOf', async ({api, web3, privateKeyWrapper}) => {62    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);63    const helper = evmCollectionHelpers(web3, caller);64    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();65    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);66    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});6768    const tokenId = await contract.methods.nextTokenId().call();69    await contract.methods.mint(caller, tokenId).send();7071    const owner = await contract.methods.ownerOf(tokenId).call();7273    expect(owner).to.equal(caller);74  });7576  itWeb3('ownerOf after burn', async ({api, web3, privateKeyWrapper}) => {77    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);78    const receiver = createEthAccount(web3);79    const helper = evmCollectionHelpers(web3, caller);80    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();81    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);82    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});8384    const tokenId = await contract.methods.nextTokenId().call();85    await contract.methods.mint(caller, tokenId).send();8687    const tokenAddress = tokenIdToAddress(collectionId, tokenId);88    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});8990    await tokenContract.methods.repartition(2).send();91    await tokenContract.methods.transfer(receiver, 1).send();9293    await tokenContract.methods.burnFrom(caller, 1).send();9495    const owner = await contract.methods.ownerOf(tokenId).call();9697    expect(owner).to.equal(receiver);98  });99});100101describe('Refungible: Plain calls', () => {102  itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {103    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);104    const helper = evmCollectionHelpers(web3, owner);105    let result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();106    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);107    const receiver = createEthAccount(web3);108    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});109    const nextTokenId = await contract.methods.nextTokenId().call();110111    expect(nextTokenId).to.be.equal('1');112    result = await contract.methods.mintWithTokenURI(113      receiver,114      nextTokenId,115      'Test URI',116    ).send();117118    const events = normalizeEvents(result.events);119120    expect(events).to.include.deep.members([121      {122        address: collectionIdAddress,123        event: 'Transfer',124        args: {125          from: '0x0000000000000000000000000000000000000000',126          to: receiver,127          tokenId: nextTokenId,128        },129      },130    ]);131132    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');133  });134135  itWeb3('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {136    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);137    const helper = evmCollectionHelpers(web3, caller);138    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();139    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);140    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});141142    const receiver = createEthAccount(web3);143144    {145      const nextTokenId = await contract.methods.nextTokenId().call();146      expect(nextTokenId).to.be.equal('1');147      const result = await contract.methods.mintBulkWithTokenURI(148        receiver,149        [150          [nextTokenId, 'Test URI 0'],151          [+nextTokenId + 1, 'Test URI 1'],152          [+nextTokenId + 2, 'Test URI 2'],153        ],154      ).send();155      const events = normalizeEvents(result.events);156157      expect(events).to.include.deep.members([158        {159          address: collectionIdAddress,160          event: 'Transfer',161          args: {162            from: '0x0000000000000000000000000000000000000000',163            to: receiver,164            tokenId: nextTokenId,165          },166        },167        {168          address: collectionIdAddress,169          event: 'Transfer',170          args: {171            from: '0x0000000000000000000000000000000000000000',172            to: receiver,173            tokenId: String(+nextTokenId + 1),174          },175        },176        {177          address: collectionIdAddress,178          event: 'Transfer',179          args: {180            from: '0x0000000000000000000000000000000000000000',181            to: receiver,182            tokenId: String(+nextTokenId + 2),183          },184        },185      ]);186187      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');188      expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');189      expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');190    }191  });192193  itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {194    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);195    const helper = evmCollectionHelpers(web3, caller);196    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();197    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);198    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});199200    const tokenId = await contract.methods.nextTokenId().call();201    await contract.methods.mint(caller, tokenId).send();202    {203      const result = await contract.methods.burn(tokenId).send();204      const events = normalizeEvents(result.events);205206      expect(events).to.be.deep.equal([207        {208          address: collectionIdAddress,209          event: 'Transfer',210          args: {211            from: caller,212            to: '0x0000000000000000000000000000000000000000',213            tokenId: tokenId.toString(),214          },215        },216      ]);217    }218  });219220  itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {221    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);222    const helper = evmCollectionHelpers(web3, caller);223    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();224    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);225    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});226227    const receiver = createEthAccount(web3);228229    const tokenId = await contract.methods.nextTokenId().call();230    await contract.methods.mint(caller, tokenId).send();231    {232      const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();233      const events = normalizeEvents(result.events);234      expect(events).to.include.deep.members([235        {236          address: collectionIdAddress,237          event: 'Transfer',238          args: {239            from: caller,240            to: receiver,241            tokenId: tokenId.toString(),242          },243        },244      ]);245    }246247    {248      const balance = await contract.methods.balanceOf(receiver).call();249      expect(+balance).to.equal(1);250    }251252    {253      const balance = await contract.methods.balanceOf(caller).call();254      expect(+balance).to.equal(0);255    }256  });257258  itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {259    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);260    const helper = evmCollectionHelpers(web3, caller);261    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();262    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);263    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});264265    const receiver = createEthAccount(web3);266267    const tokenId = await contract.methods.nextTokenId().call();268    await contract.methods.mint(caller, tokenId).send();269270    {271      const result = await contract.methods.transfer(receiver, tokenId).send();272      const events = normalizeEvents(result.events);273      expect(events).to.include.deep.members([274        {275          address: collectionIdAddress,276          event: 'Transfer',277          args: {278            from: caller,279            to: receiver,280            tokenId: tokenId.toString(),281          },282        },283      ]);284    }285286    {287      const balance = await contract.methods.balanceOf(caller).call();288      expect(+balance).to.equal(0);289    }290291    {292      const balance = await contract.methods.balanceOf(receiver).call();293      expect(+balance).to.equal(1);294    }295  });296});297298describe('RFT: Fees', () => {299  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {300    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);301    const helper = evmCollectionHelpers(web3, caller);302    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();303    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);304    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});305306    const receiver = createEthAccount(web3);307308    const tokenId = await contract.methods.nextTokenId().call();309    await contract.methods.mint(caller, tokenId).send();310311    const cost = await recordEthFee(api, caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());312    expect(cost < BigInt(0.2 * Number(UNIQUE)));313    expect(cost > 0n);314  });315316  itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {317    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);318    const helper = evmCollectionHelpers(web3, caller);319    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();320    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);321    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});322323    const receiver = createEthAccount(web3);324325    const tokenId = await contract.methods.nextTokenId().call();326    await contract.methods.mint(caller, tokenId).send();327328    const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send());329    expect(cost < BigInt(0.2 * Number(UNIQUE)));330    expect(cost > 0n);331  });332});333334describe('Common metadata', () => {335  itWeb3('Returns collection name', async ({api, web3, privateKeyWrapper}) => {336    const collection = await createCollectionExpectSuccess({337      name: 'token name',338      mode: {type: 'ReFungible'},339    });340    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);341342    const address = collectionIdToAddress(collection);343    const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});344    const name = await contract.methods.name().call();345346    expect(name).to.equal('token name');347  });348349  itWeb3('Returns symbol name', async ({api, web3, privateKeyWrapper}) => {350    const collection = await createCollectionExpectSuccess({351      tokenPrefix: 'TOK',352      mode: {type: 'ReFungible'},353    });354    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);355356    const address = collectionIdToAddress(collection);357    const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});358    const symbol = await contract.methods.symbol().call();359360    expect(symbol).to.equal('TOK');361  });362});