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

difftreelog

feat add allowanceCross method

Trubnikov Sergey2023-02-01parent: #0ba1adb.patch.diff
in: master

22 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6360,7 +6360,7 @@
 
 [[package]]
 name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
@@ -6773,7 +6773,7 @@
 
 [[package]]
 name = "pallet-refungible"
-version = "0.2.12"
+version = "0.2.13"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.10] - 2023-02-01
+
+### Added
+
+- The functions `allowanceCross` to `ERC20UniqueExtensions` interface.
+
 ## [0.1.9] - 2022-12-01
 
 ### Added
modifiedpallets/fungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -161,6 +161,21 @@
 where
 	T::AccountId: From<[u8; 32]>,
 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	fn allowance_cross(
+		&self,
+		owner: pallet_common::eth::CrossAddress,
+		spender: pallet_common::eth::CrossAddress,
+	) -> Result<U256> {
+		let owner = owner.into_sub_cross_account::<T>()?;
+		let spender = spender.into_sub_cross_account::<T>()?;
+
+		Ok(<Allowance<T>>::get((self.id, owner, spender)).into())
+	}
+
 	/// @notice A description for the collection.
 	fn description(&self) -> Result<String> {
 		Ok(decode_utf16(self.description.iter().copied())
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth
--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -511,8 +511,22 @@
 	bytes value;
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x65789571
+/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
 contract ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		spender;
+		dummy;
+		return 0;
+	}
+
 	/// @notice A description for the collection.
 	/// @dev EVM selector for this function is: 0x7284e416,
 	///  or in textual repr: description()
@@ -576,7 +590,7 @@
 	/// @param amounts array of pairs of account address and amount
 	/// @dev EVM selector for this function is: 0x1acf2d55,
 	///  or in textual repr: mintBulk((address,uint256)[])
-	function mintBulk(Tuple9[] memory amounts) public returns (bool) {
+	function mintBulk(Tuple11[] memory amounts) public returns (bool) {
 		require(false, stub_error);
 		amounts;
 		dummy = 0;
@@ -619,7 +633,7 @@
 }
 
 /// @dev anonymous struct
-struct Tuple9 {
+struct Tuple11 {
 	address field_0;
 	uint256 field_1;
 }
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.2.13] - 2023-02-01
+
+### Added
+
+- The functions `allowanceCross` to `ERC20UniqueExtensions` interface.
+
 ## [0.2.12] - 2023-01-20
 
 ### Fixed
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-refungible"
-version = "0.2.12"
+version = "0.2.13"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -203,6 +203,21 @@
 where
 	T::AccountId: From<[u8; 32]>,
 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	fn allowance_cross(
+		&self,
+		owner: pallet_common::eth::CrossAddress,
+		spender: pallet_common::eth::CrossAddress,
+	) -> Result<U256> {
+		let owner = owner.into_sub_cross_account::<T>()?;
+		let spender = spender.into_sub_cross_account::<T>()?;
+
+		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())
+	}
+
 	/// @dev Function that burns an amount of the token of a given account,
 	/// deducting from the sender's allowance for said account.
 	/// @param from The account whose tokens will be burnt.
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

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
@@ -36,8 +36,22 @@
 	}
 }
 
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
 contract ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		spender;
+		dummy;
+		return 0;
+	}
+
 	// /// @dev Function that burns an amount of the token of a given account,
 	// /// deducting from the sender's allowance for said account.
 	// /// @param from The account whose tokens will be burnt.
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -341,7 +341,9 @@
 			ERC165Call(_, _) => None,
 
 			// Not sponsored
-			BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => None,
+			AllowanceCross { .. } | BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => {
+				None
+			}
 
 			TransferCross { .. } | TransferFromCross { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
modifiedtests/src/eth/abi/fungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -101,6 +101,32 @@
           { "internalType": "uint256", "name": "sub", "type": "uint256" }
         ],
         "internalType": "struct CrossAddress",
+        "name": "owner",
+        "type": "tuple"
+      },
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "spender",
+        "type": "tuple"
+      }
+    ],
+    "name": "allowanceCross",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
         "name": "user",
         "type": "tuple"
       }
@@ -411,7 +437,7 @@
           { "internalType": "address", "name": "field_0", "type": "address" },
           { "internalType": "uint256", "name": "field_1", "type": "uint256" }
         ],
-        "internalType": "struct Tuple9[]",
+        "internalType": "struct Tuple11[]",
         "name": "amounts",
         "type": "tuple[]"
       }
modifiedtests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -61,6 +61,32 @@
   },
   {
     "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "owner",
+        "type": "tuple"
+      },
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "spender",
+        "type": "tuple"
+      }
+    ],
+    "name": "allowanceCross",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "address", "name": "spender", "type": "address" },
       { "internalType": "uint256", "name": "amount", "type": "uint256" }
     ],
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -353,8 +353,16 @@
 	bytes value;
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x65789571
+/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
 interface ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
 	/// @notice A description for the collection.
 	/// @dev EVM selector for this function is: 0x7284e416,
 	///  or in textual repr: description()
@@ -390,7 +398,7 @@
 	/// @param amounts array of pairs of account address and amount
 	/// @dev EVM selector for this function is: 0x1acf2d55,
 	///  or in textual repr: mintBulk((address,uint256)[])
-	function mintBulk(Tuple9[] memory amounts) external returns (bool);
+	function mintBulk(Tuple11[] memory amounts) external returns (bool);
 
 	/// @dev EVM selector for this function is: 0x2ada85ff,
 	///  or in textual repr: transferCross((address,uint256),uint256)
@@ -411,7 +419,7 @@
 }
 
 /// @dev anonymous struct
-struct Tuple9 {
+struct Tuple11 {
 	address field_0;
 	uint256 field_1;
 }
modifiedtests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -23,8 +23,16 @@
 	function parentTokenId() external view returns (uint256);
 }
 
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
 interface ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
 	// /// @dev Function that burns an amount of the token of a given account,
 	// /// deducting from the sender's allowance for said account.
 	// /// @param from The account whose tokens will be burnt.
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -134,6 +134,12 @@
       const allowance = await contract.methods.allowance(owner, spender).call();
       expect(+allowance).to.equal(100);
     }
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const spenderCross = helper.ethCrossAccount.fromAddress(spender);
+      const allowance = await contract.methods.allowanceCross(ownerCross, spenderCross).call();
+      expect(+allowance).to.equal(100);
+    }
   });
 
   itEth('Can perform approveCross()', async ({helper}) => {
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
after · 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 {Pallets, requirePalletsOrSkip} from '../util';18import {expect, itEth, usingEthPlaygrounds} from './util';19import {IKeyringPair} from '@polkadot/types/types';20import {ITokenPropertyPermission} from '../util/playgrounds/types';2122describe('Refungible: Plain calls', () => {23  let donor: IKeyringPair;24  let minter: IKeyringPair;25  let bob: IKeyringPair;26  let charlie: IKeyringPair;2728  before(async function() {29    await usingEthPlaygrounds(async (helper, privateKey) => {30      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);3132      donor = await privateKey({filename: __filename});33      [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);34    });35  });3637  [38    'substrate' as const,39    'ethereum' as const,40  ].map(testCase => {41    itEth(`Can perform mintCross() for ${testCase} address`, async ({helper}) => {42      const collectionAdmin = await helper.eth.createAccountWithBalance(donor);4344      const receiverEth = helper.eth.createAccount();45      const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);46      const receiverSub = bob;47      const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);4849      const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });50      const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {51        tokenOwner: false,52        collectionAdmin: true,53        mutable: false}};54      });555657      const collection = await helper.rft.mintCollection(minter, {58        tokenPrefix: 'ethp',59        tokenPropertyPermissions: permissions,60      });61      await collection.addAdmin(minter, {Ethereum: collectionAdmin});6263      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);64      const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', collectionAdmin, true);65      let expectedTokenId = await contract.methods.nextTokenId().call();66      let result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, []).send();67      let tokenId = result.events.Transfer.returnValues.tokenId;68      expect(tokenId).to.be.equal(expectedTokenId);6970      let event = result.events.Transfer;71      expect(event.address).to.be.equal(collectionAddress);72      expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');73      expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));74      expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);7576      expectedTokenId = await contract.methods.nextTokenId().call();77      result = await contract.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, properties).send();78      event = result.events.Transfer;79      expect(event.address).to.be.equal(collectionAddress);80      expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');81      expect(event.returnValues.to).to.be.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(bob.address));82      expect(await contract.methods.properties(tokenId, []).call()).to.be.like([]);8384      tokenId = result.events.Transfer.returnValues.tokenId;8586      expect(tokenId).to.be.equal(expectedTokenId);8788      expect(await contract.methods.properties(tokenId, []).call()).to.be.like(properties89        .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));9091      expect(await helper.nft.getTokenOwner(collection.collectionId, tokenId))92        .to.deep.eq(testCase === 'ethereum' ? {Ethereum: receiverEth.toLowerCase()} : {Substrate: receiverSub.address});93    });94  });9596  itEth.skip('Can perform mintBulk()', async ({helper}) => {97    const owner = await helper.eth.createAccountWithBalance(donor);98    const receiver = helper.eth.createAccount();99    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');100    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);101102    {103      const nextTokenId = await contract.methods.nextTokenId().call();104      expect(nextTokenId).to.be.equal('1');105      const result = await contract.methods.mintBulkWithTokenURI(106        receiver,107        [108          [nextTokenId, 'Test URI 0'],109          [+nextTokenId + 1, 'Test URI 1'],110          [+nextTokenId + 2, 'Test URI 2'],111        ],112      ).send();113114      const events = result.events.Transfer;115      for (let i = 0; i < 2; i++) {116        const event = events[i];117        expect(event.address).to.equal(collectionAddress);118        expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');119        expect(event.returnValues.to).to.equal(receiver);120        expect(event.returnValues.tokenId).to.equal(String(+nextTokenId + i));121      }122123      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');124      expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');125      expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');126    }127  });128129  itEth('Can perform setApprovalForAll()', async ({helper}) => {130    const owner = await helper.eth.createAccountWithBalance(donor);131    const operator = helper.eth.createAccount();132133    const collection = await helper.rft.mintCollection(minter, {});134135    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);136    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);137138    const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();139    expect(approvedBefore).to.be.equal(false);140141    {142      const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});143144      expect(result.events.ApprovalForAll).to.be.like({145        address: collectionAddress,146        event: 'ApprovalForAll',147        returnValues: {148          owner,149          operator,150          approved: true,151        },152      });153154      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();155      expect(approvedAfter).to.be.equal(true);156    }157158    {159      const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});160161      expect(result.events.ApprovalForAll).to.be.like({162        address: collectionAddress,163        event: 'ApprovalForAll',164        returnValues: {165          owner,166          operator,167          approved: false,168        },169      });170171      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();172      expect(approvedAfter).to.be.equal(false);173    }174  });175176  itEth('Can perform burn with ApprovalForAll', async ({helper}) => {177    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});178179    const owner = await helper.eth.createAccountWithBalance(donor);180    const operator = await helper.eth.createAccountWithBalance(donor, 100n);181182    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});183184    const address = helper.ethAddress.fromCollectionId(collection.collectionId);185    const contract = await helper.ethNativeContract.collection(address, 'rft');186187    {188      await contract.methods.setApprovalForAll(operator, true).send({from: owner});189      const ownerCross = helper.ethCrossAccount.fromAddress(owner);190      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});191      const events = result.events.Transfer;192193      expect(events).to.be.like({194        address,195        event: 'Transfer',196        returnValues: {197          from: owner,198          to: '0x0000000000000000000000000000000000000000',199          tokenId: token.tokenId.toString(),200        },201      });202    }203  });204205  itEth('Can perform burn with approve and approvalForAll', async ({helper}) => {206    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});207208    const owner = await helper.eth.createAccountWithBalance(donor);209    const operator = await helper.eth.createAccountWithBalance(donor, 100n);210211    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});212213    const address = helper.ethAddress.fromCollectionId(collection.collectionId);214    const contract = await helper.ethNativeContract.collection(address, 'rft');215216    const rftToken = await helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner, true);217218    {219      await rftToken.methods.approve(operator, 15n).send({from: owner});220      await contract.methods.setApprovalForAll(operator, true).send({from: owner});221      await rftToken.methods.burnFrom(owner, 10n).send({from: operator});222    }223    {224      const allowance = await rftToken.methods.allowance(owner, operator).call();225      expect(+allowance).to.be.equal(5);226    }227    {228      const ownerCross = helper.ethCrossAccount.fromAddress(owner);229      const operatorCross = helper.ethCrossAccount.fromAddress(operator);230      const allowance = await rftToken.methods.allowanceCross(ownerCross, operatorCross).call();231      expect(+allowance).to.equal(5);232    }233  });234235  itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {236    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});237238    const owner = await helper.eth.createAccountWithBalance(donor);239    const operator = await helper.eth.createAccountWithBalance(donor);240    const receiver = charlie;241242    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});243244    const address = helper.ethAddress.fromCollectionId(collection.collectionId);245    const contract = await helper.ethNativeContract.collection(address, 'rft');246247    {248      await contract.methods.setApprovalForAll(operator, true).send({from: owner});249      const ownerCross = helper.ethCrossAccount.fromAddress(owner);250      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);251      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});252      const event = result.events.Transfer;253      expect(event).to.be.like({254        address: helper.ethAddress.fromCollectionId(collection.collectionId),255        event: 'Transfer',256        returnValues: {257          from: owner,258          to: helper.address.substrateToEth(receiver.address),259          tokenId: token.tokenId.toString(),260        },261      });262    }263264    expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);265  });266267  itEth('Can perform burn()', async ({helper}) => {268    const caller = await helper.eth.createAccountWithBalance(donor);269    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');270    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);271272    const result = await contract.methods.mint(caller).send();273    const tokenId = result.events.Transfer.returnValues.tokenId;274    {275      const result = await contract.methods.burn(tokenId).send();276      const event = result.events.Transfer;277      expect(event.address).to.equal(collectionAddress);278      expect(event.returnValues.from).to.equal(caller);279      expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');280      expect(event.returnValues.tokenId).to.equal(tokenId.toString());281    }282  });283284  itEth('Can perform transferFrom()', async ({helper}) => {285    const caller = await helper.eth.createAccountWithBalance(donor);286    const receiver = helper.eth.createAccount();287    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');288    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);289290    const result = await contract.methods.mint(caller).send();291    const tokenId = result.events.Transfer.returnValues.tokenId;292293    const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);294295    const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, caller);296    await tokenContract.methods.repartition(15).send();297298    {299      const tokenEvents: any = [];300      tokenContract.events.allEvents((_: any, event: any) => {301        tokenEvents.push(event);302      });303      const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();304      if (tokenEvents.length == 0) await helper.wait.newBlocks(1);305306      let event = result.events.Transfer;307      expect(event.address).to.equal(collectionAddress);308      expect(event.returnValues.from).to.equal(caller);309      expect(event.returnValues.to).to.equal(receiver);310      expect(event.returnValues.tokenId).to.equal(tokenId.toString());311312      event = tokenEvents[0];313      expect(event.address).to.equal(tokenAddress);314      expect(event.returnValues.from).to.equal(caller);315      expect(event.returnValues.to).to.equal(receiver);316      expect(event.returnValues.value).to.equal('15');317    }318319    {320      const balance = await contract.methods.balanceOf(receiver).call();321      expect(+balance).to.equal(1);322    }323324    {325      const balance = await contract.methods.balanceOf(caller).call();326      expect(+balance).to.equal(0);327    }328  });329330  // Soft-deprecated331  itEth('Can perform burnFrom()', async ({helper}) => {332    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});333334    const owner = await helper.eth.createAccountWithBalance(donor, 100n);335    const spender = await helper.eth.createAccountWithBalance(donor, 100n);336337    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});338339    const address = helper.ethAddress.fromCollectionId(collection.collectionId);340    const contract = await helper.ethNativeContract.collection(address, 'rft', spender, true);341342    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);343    const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner);344    await tokenContract.methods.repartition(15).send();345    await tokenContract.methods.approve(spender, 15).send();346347    {348      const result = await contract.methods.burnFrom(owner, token.tokenId).send();349      const event = result.events.Transfer;350      expect(event).to.be.like({351        address: helper.ethAddress.fromCollectionId(collection.collectionId),352        event: 'Transfer',353        returnValues: {354          from: owner,355          to: '0x0000000000000000000000000000000000000000',356          tokenId: token.tokenId.toString(),357        },358      });359    }360361    expect(await collection.getTokenBalance(token.tokenId, {Ethereum: owner})).to.be.eq(0n);362  });363364  itEth('Can perform burnFromCross()', async ({helper}) => {365    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});366367    const owner = bob;368    const spender = await helper.eth.createAccountWithBalance(donor, 100n);369370    const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});371372    const address = helper.ethAddress.fromCollectionId(collection.collectionId);373    const contract = await helper.ethNativeContract.collection(address, 'rft');374375    await token.repartition(owner, 15n);376    await token.approve(owner, {Ethereum: spender}, 15n);377378    {379      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);380      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});381      const event = result.events.Transfer;382      expect(event).to.be.like({383        address: helper.ethAddress.fromCollectionId(collection.collectionId),384        event: 'Transfer',385        returnValues: {386          from: helper.address.substrateToEth(owner.address),387          to: '0x0000000000000000000000000000000000000000',388          tokenId: token.tokenId.toString(),389        },390      });391    }392393    expect(await collection.getTokenBalance(token.tokenId, {Substrate: owner.address})).to.be.eq(0n);394  });395396  itEth('Can perform transferFromCross()', async ({helper}) => {397    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});398399    const owner = bob;400    const spender = await helper.eth.createAccountWithBalance(donor, 100n);401    const receiver = charlie;402403    const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});404405    const address = helper.ethAddress.fromCollectionId(collection.collectionId);406    const contract = await helper.ethNativeContract.collection(address, 'rft');407408    await token.repartition(owner, 15n);409    await token.approve(owner, {Ethereum: spender}, 15n);410411    {412      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);413      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);414      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});415      const event = result.events.Transfer;416      expect(event).to.be.like({417        address: helper.ethAddress.fromCollectionId(collection.collectionId),418        event: 'Transfer',419        returnValues: {420          from: helper.address.substrateToEth(owner.address),421          to: helper.address.substrateToEth(receiver.address),422          tokenId: token.tokenId.toString(),423        },424      });425    }426427    expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);428  });429430  itEth('Can perform transfer()', async ({helper}) => {431    const caller = await helper.eth.createAccountWithBalance(donor);432    const receiver = helper.eth.createAccount();433    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');434    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);435436    const result = await contract.methods.mint(caller).send();437    const tokenId = result.events.Transfer.returnValues.tokenId;438439    {440      const result = await contract.methods.transfer(receiver, tokenId).send();441442      const event = result.events.Transfer;443      expect(event.address).to.equal(collectionAddress);444      expect(event.returnValues.from).to.equal(caller);445      expect(event.returnValues.to).to.equal(receiver);446      expect(event.returnValues.tokenId).to.equal(tokenId.toString());447    }448449    {450      const balance = await contract.methods.balanceOf(caller).call();451      expect(+balance).to.equal(0);452    }453454    {455      const balance = await contract.methods.balanceOf(receiver).call();456      expect(+balance).to.equal(1);457    }458  });459460  itEth('Can perform transferCross()', async ({helper}) => {461    const sender = await helper.eth.createAccountWithBalance(donor);462    const receiverEth = await helper.eth.createAccountWithBalance(donor);463    const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);464    const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);465466    const collection = await helper.rft.mintCollection(minter, {});467    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);468    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);469470    const token = await collection.mintToken(minter, 50n, {Ethereum: sender});471472    {473      // Can transferCross to ethereum address:474      const result = await collectionEvm.methods.transferCross(receiverCrossEth, token.tokenId).send({from: sender});475      // Check events:476      const event = result.events.Transfer;477      expect(event.address).to.equal(collectionAddress);478      expect(event.returnValues.from).to.equal(sender);479      expect(event.returnValues.to).to.equal(receiverEth);480      expect(event.returnValues.tokenId).to.equal(token.tokenId.toString());481      // Sender's balance decreased:482      const senderBalance = await collectionEvm.methods.balanceOf(sender).call();483      expect(+senderBalance).to.equal(0);484      expect(await token.getBalance({Ethereum: sender})).to.eq(0n);485      // Receiver's balance increased:486      const receiverBalance = await collectionEvm.methods.balanceOf(receiverEth).call();487      expect(+receiverBalance).to.equal(1);488      expect(await token.getBalance({Ethereum: receiverEth})).to.eq(50n);489    }490491    {492      // Can transferCross to substrate address:493      const substrateResult = await collectionEvm.methods.transferCross(receiverCrossSub, token.tokenId).send({from: receiverEth});494      // Check events:495      const event = substrateResult.events.Transfer;496      expect(event.address).to.be.equal(collectionAddress);497      expect(event.returnValues.from).to.be.equal(receiverEth);498      expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(minter.address));499      expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);500      // Sender's balance decreased:501      const senderBalance = await collectionEvm.methods.balanceOf(receiverEth).call();502      expect(+senderBalance).to.equal(0);503      expect(await token.getBalance({Ethereum: receiverEth})).to.eq(0n);504      // Receiver's balance increased:505      const receiverBalance = await helper.nft.getTokensByAddress(collection.collectionId, {Substrate: minter.address});506      expect(receiverBalance).to.contain(token.tokenId);507      expect(await token.getBalance({Substrate: minter.address})).to.eq(50n);508    }509  });510511  ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {512    const sender = await helper.eth.createAccountWithBalance(donor);513    const tokenOwner = await helper.eth.createAccountWithBalance(donor);514    const receiverSub = minter;515    const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);516517    const collection = await helper.rft.mintCollection(minter, {});518    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);519    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', sender);520521    await collection.mintToken(minter, 50n, {Ethereum: sender});522    const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});523524    // Cannot transferCross someone else's token:525    const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;526    await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;527    // Cannot transfer token if it does not exist:528    await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;529  }));530531  itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {532    const caller = await helper.eth.createAccountWithBalance(donor);533    const receiver = helper.eth.createAccount();534    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');535    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);536537    const result = await contract.methods.mint(caller).send();538    const tokenId = result.events.Transfer.returnValues.tokenId;539540    const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);541542    await tokenContract.methods.repartition(2).send();543    await tokenContract.methods.transfer(receiver, 1).send();544545    const events: any = [];546    contract.events.allEvents((_: any, event: any) => {547      events.push(event);548    });549550    await tokenContract.methods.transfer(receiver, 1).send();551    if (events.length == 0) await helper.wait.newBlocks(1);552    const event = events[0];553554    expect(event.address).to.equal(collectionAddress);555    expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');556    expect(event.returnValues.to).to.equal(receiver);557    expect(event.returnValues.tokenId).to.equal(tokenId.toString());558  });559560  itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {561    const caller = await helper.eth.createAccountWithBalance(donor);562    const receiver = helper.eth.createAccount();563    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');564    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);565566    const result = await contract.methods.mint(caller).send();567    const tokenId = result.events.Transfer.returnValues.tokenId;568569    const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);570571    await tokenContract.methods.repartition(2).send();572573    const events: any = [];574    contract.events.allEvents((_: any, event: any) => {575      events.push(event);576    });577578    await tokenContract.methods.transfer(receiver, 1).send();579    if (events.length == 0) await helper.wait.newBlocks(1);580    const event = events[0];581582    expect(event.address).to.equal(collectionAddress);583    expect(event.returnValues.from).to.equal(caller);584    expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');585    expect(event.returnValues.tokenId).to.equal(tokenId.toString());586  });587});588589describe('RFT: Fees', () => {590  let donor: IKeyringPair;591592  before(async function() {593    await usingEthPlaygrounds(async (helper, privateKey) => {594      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);595596      donor = await privateKey({filename: __filename});597    });598  });599600  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {601    const caller = await helper.eth.createAccountWithBalance(donor);602    const receiver = helper.eth.createAccount();603    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');604    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);605606    const result = await contract.methods.mint(caller).send();607    const tokenId = result.events.Transfer.returnValues.tokenId;608609    const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());610    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));611    expect(cost > 0n);612  });613614  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {615    const caller = await helper.eth.createAccountWithBalance(donor);616    const receiver = helper.eth.createAccount();617    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');618    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);619620    const result = await contract.methods.mint(caller).send();621    const tokenId = result.events.Transfer.returnValues.tokenId;622623    const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());624    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));625    expect(cost > 0n);626  });627});628629describe('Common metadata', () => {630  let donor: IKeyringPair;631  let alice: IKeyringPair;632633  before(async function() {634    await usingEthPlaygrounds(async (helper, privateKey) => {635      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);636637      donor = await privateKey({filename: __filename});638      [alice] = await helper.arrange.createAccounts([20n], donor);639    });640  });641642  itEth('Returns collection name', async ({helper}) => {643    const caller = helper.eth.createAccount();644    const tokenPropertyPermissions = [{645      key: 'URI',646      permission: {647        mutable: true,648        collectionAdmin: true,649        tokenOwner: false,650      },651    }];652    const collection = await helper.rft.mintCollection(653      alice,654      {655        name: 'Leviathan',656        tokenPrefix: '11',657        properties: [{key: 'ERC721Metadata', value: '1'}],658        tokenPropertyPermissions,659      },660    );661662    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);663    const name = await contract.methods.name().call();664    expect(name).to.equal('Leviathan');665  });666667  itEth('Returns symbol name', async ({helper}) => {668    const caller = await helper.eth.createAccountWithBalance(donor);669    const tokenPropertyPermissions = [{670      key: 'URI',671      permission: {672        mutable: true,673        collectionAdmin: true,674        tokenOwner: false,675      },676    }];677    const {collectionId} = await helper.rft.mintCollection(678      alice,679      {680        name: 'Leviathan',681        tokenPrefix: '12',682        properties: [{key: 'ERC721Metadata', value: '1'}],683        tokenPropertyPermissions,684      },685    );686687    const contract = await helper.ethNativeContract.collectionById(collectionId, 'rft', caller);688    const symbol = await contract.methods.symbol().call();689    expect(symbol).to.equal('12');690  });691});692693describe('Negative tests', () => {694  let donor: IKeyringPair;695  let minter: IKeyringPair;696  let alice: IKeyringPair;697698  before(async function() {699    await usingEthPlaygrounds(async (helper, privateKey) => {700      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);701702      donor = await privateKey({filename: __filename});703      [minter, alice] = await helper.arrange.createAccounts([100n, 100n], donor);704    });705  });706707  itEth('[negative] Cant perform burn without approval', async ({helper}) => {708    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});709710    const owner = await helper.eth.createAccountWithBalance(donor, 100n);711    const spender = await helper.eth.createAccountWithBalance(donor, 100n);712713    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});714715    const address = helper.ethAddress.fromCollectionId(collection.collectionId);716    const contract = await helper.ethNativeContract.collection(address, 'rft');717718    const ownerCross = helper.ethCrossAccount.fromAddress(owner);719720    await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;721722    await contract.methods.setApprovalForAll(spender, true).send({from: owner});723    await contract.methods.setApprovalForAll(spender, false).send({from: owner});724725    await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;726  });727728  itEth('[negative] Cant perform transfer without approval', async ({helper}) => {729    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});730    const owner = await helper.eth.createAccountWithBalance(donor, 100n);731    const receiver = alice;732733    const spender = await helper.eth.createAccountWithBalance(donor, 100n);734735    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});736737    const address = helper.ethAddress.fromCollectionId(collection.collectionId);738    const contract = await helper.ethNativeContract.collection(address, 'rft');739740    const ownerCross = helper.ethCrossAccount.fromAddress(owner);741    const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);742743    await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;744745    await contract.methods.setApprovalForAll(spender, true).send({from: owner});746    await contract.methods.setApprovalForAll(spender, false).send({from: owner});747748    await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;749  });750});