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

difftreelog

Merge pull request #835 from UniqueNetwork/tests/generalization

Yaroslav Bolyukin2023-01-18parents: #d161923 #5954afe.patch.diff
in: master

20 files changed

modifiedtests/src/apiConsts.test.tsdiffbeforeafterboth
--- a/tests/src/apiConsts.test.ts
+++ b/tests/src/apiConsts.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {ApiPromise} from '@polkadot/api';
-import {usingPlaygrounds, itSub, expect} from './util';
+import {usingPlaygrounds, itSub, expect, COLLECTION_HELPER, CONTRACT_HELPER} from './util';
 
 
 const MAX_COLLECTION_DESCRIPTION_LENGTH = 256n;
@@ -40,9 +40,6 @@
   ownerCanDestroy: true,
   transfersEnabled: true,
 };
-
-const EVM_COLLECTION_HELPERS_ADDRESS = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';
-const HELPERS_CONTRACT_ADDRESS = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';
 
 describe('integration test: API UNIQUE consts', () => {
   let api: ApiPromise;
@@ -106,11 +103,11 @@
   });
 
   itSub('HELPERS_CONTRACT_ADDRESS', () => {
-    expect(api.consts.evmContractHelpers.contractAddress.toString().toLowerCase()).to.be.equal(HELPERS_CONTRACT_ADDRESS.toLowerCase());
+    expect(api.consts.evmContractHelpers.contractAddress.toString().toLowerCase()).to.be.equal(CONTRACT_HELPER.toLowerCase());
   });
 
   itSub('EVM_COLLECTION_HELPERS_ADDRESS', () => {
-    expect(api.consts.common.contractAddress.toString().toLowerCase()).to.be.equal(EVM_COLLECTION_HELPERS_ADDRESS.toLowerCase());
+    expect(api.consts.common.contractAddress.toString().toLowerCase()).to.be.equal(COLLECTION_HELPER.toLowerCase());
   });
 });
 
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -45,32 +45,6 @@
     await collection.burnTokens(alice, 1n);
     expect(await collection.getBalance({Substrate: alice.address})).to.eq(9n);
   });
-
-  itSub.ifWithPallets('Burn item in ReFungible collection', [Pallets.ReFungible], async function({helper}) {
-    const collection = await helper.rft.mintCollection(alice);
-    const token = await collection.mintToken(alice, 100n);
-
-    await token.burn(alice, 90n);
-    expect(await token.getBalance({Substrate: alice.address})).to.eq(10n);
-
-    await token.burn(alice, 10n);
-    expect(await token.getBalance({Substrate: alice.address})).to.eq(0n);
-  });
-
-  itSub.ifWithPallets('Burn owned portion of item in ReFungible collection', [Pallets.ReFungible], async function({helper}) {
-    const collection = await helper.rft.mintCollection(alice);
-    const token = await collection.mintToken(alice, 100n);
-
-    await token.transfer(alice, {Substrate: bob.address}, 1n);
-
-    expect(await token.getBalance({Substrate: alice.address})).to.eq(99n);
-    expect(await token.getBalance({Substrate: bob.address})).to.eq(1n);
-
-    await token.burn(bob, 1n);
-
-    expect(await token.getBalance({Substrate: alice.address})).to.eq(99n);
-    expect(await token.getBalance({Substrate: bob.address})).to.eq(0n);
-  });
 });
 
 describe('integration test: ext. burnItem() with admin permissions:', () => {
@@ -104,16 +78,6 @@
     await collection.burnTokensFrom(bob, {Substrate: alice.address}, 1n);
     expect(await collection.getBalance({Substrate: alice.address})).to.eq(9n);
   });
-
-  itSub.ifWithPallets('Burn item in ReFungible collection', [Pallets.ReFungible], async function({helper}) {
-    const collection = await helper.rft.mintCollection(alice);
-    await collection.setLimits(alice, {ownerCanTransfer: true});
-    await collection.addAdmin(alice, {Substrate: bob.address});
-    const token = await collection.mintToken(alice, 100n);
-
-    await token.burnFrom(bob, {Substrate: alice.address}, 100n);
-    expect(await token.doesExist()).to.be.false;
-  });
 });
 
 describe('Negative integration test: ext. burnItem():', () => {
@@ -138,31 +102,6 @@
     const token = await collection.mintToken(alice);
 
     await expect(token.burn(bob)).to.be.rejectedWith('common.NoPermission');
-  });
-
-  itSub.ifWithPallets('RFT: cannot burn non-owned token pieces', [Pallets.ReFungible], async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice);
-    const aliceToken = await collection.mintToken(alice, 10n, {Substrate: alice.address});
-    const bobToken = await collection.mintToken(alice, 10n, {Substrate: bob.address});
-
-    // 1. Cannot burn non-owned token:
-    await expect(bobToken.burn(alice, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
-    await expect(bobToken.burn(alice, 5n)).to.be.rejectedWith('common.TokenValueTooLow');
-    // 2. Cannot burn non-existing token:
-    await expect(helper.rft.burnToken(alice, 99999, 10)).to.be.rejectedWith('common.CollectionNotFound');
-    await expect(helper.rft.burnToken(alice, collection.collectionId, 99999)).to.be.rejectedWith('common.TokenValueTooLow');
-    // 3. Can burn zero amount of owned tokens (EIP-20)
-    await aliceToken.burn(alice, 0n);
-
-    // 4. Storage is not corrupted:
-    expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
-    expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
-
-    // 4.1 Tokens can be transfered:
-    await aliceToken.transfer(alice, {Substrate: bob.address}, 10n);
-    await bobToken.transfer(bob, {Substrate: alice.address}, 10n);
-    expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
-    expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
   });
 
   itSub('Transfer a burned token', async ({helper}) => {
modifiedtests/src/eth/collectionHelperAddress.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionHelperAddress.test.ts
+++ b/tests/src/eth/collectionHelperAddress.test.ts
@@ -16,9 +16,7 @@
 
 import {itEth, usingEthPlaygrounds, expect} from './util';
 import {IKeyringPair} from '@polkadot/types/types';
-import {Pallets} from '../util';
-
-const EVM_COLLECTION_HELPERS_ADDRESS = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';
+import {COLLECTION_HELPER, Pallets} from '../util';
 
 describe('[eth]CollectionHelperAddress test: ERC20/ERC721 ', () => {
   let donor: IKeyringPair;
@@ -36,7 +34,7 @@
     const nftCollection = await helper.ethNativeContract.collection(nftCollectionAddress, 'nft', owner);
 
     expect((await nftCollection.methods.collectionHelperAddress().call())
-      .toString().toLowerCase()).to.be.equal(EVM_COLLECTION_HELPERS_ADDRESS);
+      .toString().toLowerCase()).to.be.equal(COLLECTION_HELPER);
   });
 
   itEth.ifWithPallets('RFT ', [Pallets.ReFungible], async ({helper}) => {
@@ -46,7 +44,7 @@
 
     const rftCollection = await helper.ethNativeContract.collection(rftCollectionAddress, 'rft', owner);
     expect((await rftCollection.methods.collectionHelperAddress().call())
-      .toString().toLowerCase()).to.be.equal(EVM_COLLECTION_HELPERS_ADDRESS);
+      .toString().toLowerCase()).to.be.equal(COLLECTION_HELPER);
   });
 
   itEth('FT', async ({helper}) => {
@@ -56,7 +54,7 @@
     const collection = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
     expect((await collection.methods.collectionHelperAddress().call())
-      .toString().toLowerCase()).to.be.equal(EVM_COLLECTION_HELPERS_ADDRESS);
+      .toString().toLowerCase()).to.be.equal(COLLECTION_HELPER);
   });
 
   itEth('[collectionHelpers] convert collectionId into address', async ({helper}) => {
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -18,6 +18,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itEth, usingEthPlaygrounds} from './util';
 import {CollectionLimitField} from './util/playgrounds/types';
+import {COLLECTION_HELPER} from '../util';
 
 
 describe('Create NFT collection from EVM', () => {
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -17,38 +17,6 @@
 import {expect, itEth, usingEthPlaygrounds} from './util';
 import {IKeyringPair} from '@polkadot/types/types';
 
-describe('Fungible: Information getting', () => {
-  let donor: IKeyringPair;
-  let alice: IKeyringPair;
-
-  before(async function() {
-    await usingEthPlaygrounds(async (helper, privateKey) => {
-      donor = await privateKey({filename: __filename});
-      [alice] = await helper.arrange.createAccounts([20n], donor);
-    });
-  });
-
-  itEth('totalSupply', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.ft.mintCollection(alice);
-    await collection.mint(alice, 200n);
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);
-    const totalSupply = await contract.methods.totalSupply().call();
-    expect(totalSupply).to.equal('200');
-  });
-
-  itEth('balanceOf', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.ft.mintCollection(alice);
-    await collection.mint(alice, 200n, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);
-    const balance = await contract.methods.balanceOf(caller).call();
-    expect(balance).to.equal('200');
-  });
-});
-
 describe('Fungible: Plain calls', () => {
   let donor: IKeyringPair;
   let alice: IKeyringPair;
@@ -59,24 +27,6 @@
       donor = await privateKey({filename: __filename});
       [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);
     });
-  });
-
-  itEth('Can perform mint()', async ({helper}) => {
-    const owner = await helper.eth.createAccountWithBalance(donor);
-    const receiver = helper.eth.createAccount();
-    const collection = await helper.ft.mintCollection(alice);
-    await collection.addAdmin(alice, {Ethereum: owner});
-
-    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
-
-    const result = await contract.methods.mint(receiver, 100).send();
-
-    const event = result.events.Transfer;
-    expect(event.address).to.equal(collectionAddress);
-    expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
-    expect(event.returnValues.to).to.equal(receiver);
-    expect(event.returnValues.value).to.equal('100');
   });
 
   [
addedtests/src/eth/getCode.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/getCode.test.ts
@@ -0,0 +1,53 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {expect, itEth, usingEthPlaygrounds} from './util';
+import {IKeyringPair} from '@polkadot/types/types';
+import {COLLECTION_HELPER, CONTRACT_HELPER} from '../util';
+
+describe('RPC eth_getCode', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+    });
+  });
+
+  [
+    {address: COLLECTION_HELPER},
+    {address: CONTRACT_HELPER},
+  ].map(testCase => {
+    itEth(`returns value for native contract: ${testCase.address}`, async ({helper}) => {
+      const contractCodeSub = (await helper.callRpc('api.rpc.eth.getCode', [testCase.address])).toJSON();
+      const contractCodeEth = (await helper.getWeb3().eth.getCode(testCase.address));
+
+      expect(contractCodeSub).to.has.length.greaterThan(4);
+      expect(contractCodeEth).to.has.length.greaterThan(4);
+    });
+  });
+
+  itEth('returns value for custom contract', async ({helper}) => {
+    const signer = await helper.eth.createAccountWithBalance(donor);
+    const flipper = await helper.eth.deployFlipper(signer);
+
+    const contractCodeSub = (await helper.callRpc('api.rpc.eth.getCode', [flipper.options.address])).toJSON();
+    const contractCodeEth = (await helper.getWeb3().eth.getCode(flipper.options.address));
+
+    expect(contractCodeSub).to.has.length.greaterThan(4);
+    expect(contractCodeEth).to.has.length.greaterThan(4);
+  });
+});
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -19,68 +19,6 @@
 import {Contract} from 'web3-eth-contract';
 import {ITokenPropertyPermission} from '../util/playgrounds/types';
 
-
-describe('NFT: Information getting', () => {
-  let donor: IKeyringPair;
-  let alice: IKeyringPair;
-
-  before(async function() {
-    await usingEthPlaygrounds(async (helper, privateKey) => {
-      donor = await privateKey({filename: __filename});
-      [alice] = await helper.arrange.createAccounts([10n], donor);
-    });
-  });
-
-  itEth('totalSupply', async ({helper}) => {
-    const collection = await helper.nft.mintCollection(alice, {});
-    await collection.mintToken(alice);
-
-    const caller = await helper.eth.createAccountWithBalance(donor);
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
-    const totalSupply = await contract.methods.totalSupply().call();
-
-    expect(totalSupply).to.equal('1');
-  });
-
-  itEth('balanceOf', async ({helper}) => {
-    const collection = await helper.nft.mintCollection(alice, {});
-    const caller = await helper.eth.createAccountWithBalance(donor);
-
-    await collection.mintToken(alice, {Ethereum: caller});
-    await collection.mintToken(alice, {Ethereum: caller});
-    await collection.mintToken(alice, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
-    const balance = await contract.methods.balanceOf(caller).call();
-
-    expect(balance).to.equal('3');
-  });
-
-  itEth('ownerOf', async ({helper}) => {
-    const collection = await helper.nft.mintCollection(alice, {});
-    const caller = await helper.eth.createAccountWithBalance(donor);
-
-    const token = await collection.mintToken(alice, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
-
-    const owner = await contract.methods.ownerOf(token.tokenId).call();
-
-    expect(owner).to.equal(caller);
-  });
-
-  itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {
-    const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});
-    const caller = helper.eth.createAccount();
-
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
-
-    expect(await contract.methods.name().call()).to.equal('test');
-    expect(await contract.methods.symbol().call()).to.equal('TEST');
-  });
-});
-
 describe('Check ERC721 token URI for NFT', () => {
   let donor: IKeyringPair;
 
@@ -148,30 +86,6 @@
       donor = await privateKey({filename: __filename});
       [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
     });
-  });
-
-  itEth('Can perform mint() & get crossOwner()', async ({helper}) => {
-    const owner = await helper.eth.createAccountWithBalance(donor);
-    const receiver = helper.eth.createAccount();
-
-    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-
-    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
-    const tokenId = result.events.Transfer.returnValues.tokenId;
-    expect(tokenId).to.be.equal('1');
-
-    const event = result.events.Transfer;
-    expect(event.address).to.be.equal(collectionAddress);
-    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
-    expect(event.returnValues.to).to.be.equal(receiver);
-
-    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
-    expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
-    // TODO: this wont work right now, need release 919000 first
-    // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
-    // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();
-    // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);
   });
 
   // TODO combine all minting tests in one place
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -19,90 +19,6 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {ITokenPropertyPermission} from '../util/playgrounds/types';
 
-describe('Refungible: Information getting', () => {
-  let donor: IKeyringPair;
-
-  before(async function() {
-    await usingEthPlaygrounds(async (helper, privateKey) => {
-      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
-
-      donor = await privateKey({filename: __filename});
-    });
-  });
-
-  itEth('totalSupply', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'TotalSupply', '6', '6');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-
-    await contract.methods.mint(caller).send();
-
-    const totalSupply = await contract.methods.totalSupply().call();
-    expect(totalSupply).to.equal('1');
-  });
-
-  itEth('balanceOf', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'BalanceOf', '6', '6');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-
-    await contract.methods.mint(caller).send();
-    await contract.methods.mint(caller).send();
-    await contract.methods.mint(caller).send();
-
-    const balance = await contract.methods.balanceOf(caller).call();
-    expect(balance).to.equal('3');
-  });
-
-  itEth('ownerOf', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf', '6', '6');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-
-    const result = await contract.methods.mint(caller).send();
-    const tokenId = result.events.Transfer.returnValues.tokenId;
-
-    const owner = await contract.methods.ownerOf(tokenId).call();
-    expect(owner).to.equal(caller);
-  });
-
-  itEth('ownerOf after burn', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-
-    const result = await contract.methods.mint(caller).send();
-    const tokenId = result.events.Transfer.returnValues.tokenId;
-    const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller, true);
-
-    await tokenContract.methods.repartition(2).send();
-    await tokenContract.methods.transfer(receiver, 1).send();
-
-    await tokenContract.methods.burnFrom(caller, 1).send();
-
-    const owner = await contract.methods.ownerOf(tokenId).call();
-    expect(owner).to.equal(receiver);
-  });
-
-  itEth('ownerOf for partial ownership', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Partial-OwnerOf', '6', '6');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-
-    const result = await contract.methods.mint(caller).send();
-    const tokenId = result.events.Transfer.returnValues.tokenId;
-    const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
-
-    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', () => {
   let donor: IKeyringPair;
   let minter: IKeyringPair;
@@ -116,25 +32,6 @@
       donor = await privateKey({filename: __filename});
       [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
     });
-  });
-
-  itEth('Can perform mint() & crossOwnerOf()', async ({helper}) => {
-    const owner = await helper.eth.createAccountWithBalance(donor);
-    const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
-    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
-
-    const event = result.events.Transfer;
-    expect(event.address).to.equal(collectionAddress);
-    expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
-    expect(event.returnValues.to).to.equal(receiver);
-    const tokenId = event.returnValues.tokenId;
-    expect(tokenId).to.be.equal('1');
-
-    expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
-    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
   });
 
   [
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -19,51 +19,6 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Contract} from 'web3-eth-contract';
 
-
-describe('Refungible token: Information getting', () => {
-  let donor: IKeyringPair;
-  let alice: IKeyringPair;
-
-  before(async function() {
-    await usingEthPlaygrounds(async (helper, privateKey) => {
-      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
-
-      donor = await privateKey({filename: __filename});
-      [alice] = await helper.arrange.createAccounts([20n], donor);
-    });
-  });
-
-  itEth('totalSupply', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
-    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
-    const totalSupply = await contract.methods.totalSupply().call();
-    expect(totalSupply).to.equal('200');
-  });
-
-  itEth('balanceOf', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
-    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
-    const balance = await contract.methods.balanceOf(caller).call();
-    expect(balance).to.equal('200');
-  });
-
-  itEth('decimals', async ({helper}) => {
-    const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
-    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
-
-    const contract = await helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
-    const decimals = await contract.methods.decimals().call();
-    expect(decimals).to.equal('0');
-  });
-});
-
 // FIXME: Need erc721 for ReFubgible.
 describe('Check ERC721 token URI for ReFungible', () => {
   let donor: IKeyringPair;
addedtests/src/eth/tokens/callMethodsERC20.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/tokens/callMethodsERC20.test.ts
@@ -0,0 +1,91 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {Pallets, requirePalletsOrSkip} from '../../util';
+import {expect, itEth, usingEthPlaygrounds} from '../util';
+import {IKeyringPair} from '@polkadot/types/types';
+
+[
+  {mode: 'ft' as const, requiredPallets: []},
+  {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+].map(testCase => {
+  describe(`${testCase.mode.toUpperCase()}: ERC-20 call methods`, () => {
+    let donor: IKeyringPair;
+
+    before(async function() {
+      await usingEthPlaygrounds(async (helper, privateKey) => {
+        requirePalletsOrSkip(this, helper, testCase.requiredPallets);
+        donor = await privateKey({filename: __filename});
+      });
+    });
+
+    itEth('totalSupply', async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
+
+      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+      if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+
+      // Use collection contract for FT or token contract for RFT:
+      const contract = testCase.mode === 'ft'
+        ? collection
+        : await helper.ethNativeContract.rftTokenById(collectionId, 1, caller);
+
+      // Mint tokens:
+      testCase.mode === 'ft'
+        ? await contract.methods.mint(...mintingParams).send({from: caller})
+        : await contract.methods.repartition(200).send({from: caller});
+
+      const totalSupply = await contract.methods.totalSupply().call();
+      expect(totalSupply).to.equal('200');
+    });
+
+    itEth('balanceOf', async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
+
+      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+
+      // Use collection contract for FT or token contract for RFT:
+      const contract = testCase.mode === 'ft'
+        ? collection
+        : await helper.ethNativeContract.rftTokenById(collectionId, 1, caller);
+
+      // Mint tokens:
+      testCase.mode === 'ft'
+        ? await contract.methods.mint(...mintingParams).send({from: caller})
+        : await contract.methods.repartition(200).send({from: caller});
+
+      const balance = await contract.methods.balanceOf(caller).call();
+      expect(balance).to.equal('200');
+    });
+
+    itEth('decimals', async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      if (testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
+
+      // Use collection contract for FT or token contract for RFT:
+      const contract = testCase.mode === 'ft'
+        ? collection
+        : await helper.ethNativeContract.rftTokenById(collectionId, 1, caller);
+
+      const decimals = await contract.methods.decimals().call();
+      expect(decimals).to.equal(testCase.mode === 'rft' ? '0' : '18');
+    });
+  });
+});
\ No newline at end of file
addedtests/src/eth/tokens/callMethodsERC721.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/tokens/callMethodsERC721.test.ts
@@ -0,0 +1,143 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {Pallets} from '../../util';
+import {expect, itEth, usingEthPlaygrounds} from '../util';
+import {IKeyringPair} from '@polkadot/types/types';
+
+
+describe('ERC-721 call methods', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+    });
+  });
+
+  [
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'nft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: name/symbol/description`, testCase.requiredPallets, async ({helper}) => {
+      const callerEth = await helper.eth.createAccountWithBalance(donor);
+      const [callerSub] = await helper.arrange.createAccounts([100n], donor);
+      const [name, description, tokenPrefix] = ['Name', 'Description', 'Symbol'];
+
+      const {collection: collectionEth} = await helper.eth.createCollection(testCase.mode, callerEth, name, description, tokenPrefix);
+      await collectionEth.methods.mint(callerEth).send({from: callerEth});
+      const {collectionId} = await helper[testCase.mode].mintCollection(callerSub, {name, description, tokenPrefix});
+      const collectionSub = await helper.ethNativeContract.collectionById(collectionId, testCase.mode, callerEth);
+
+      // Can get name/symbol/description for Eth collection
+      expect(await collectionEth.methods.name().call()).to.eq(name);
+      expect(await collectionEth.methods.symbol().call()).to.eq(tokenPrefix);
+      expect(await collectionEth.methods.description().call()).to.eq(description);
+      // Can get name/symbol/description for Sub collection
+      expect(await collectionSub.methods.name().call()).to.eq(name);
+      expect(await collectionSub.methods.symbol().call()).to.eq(tokenPrefix);
+      expect(await collectionSub.methods.description().call()).to.eq(description);
+    });
+  });
+
+  [
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'nft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: totalSupply`, testCase.requiredPallets, async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+
+      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+      await collection.methods.mint(caller).send({from: caller});
+
+      const totalSupply = await collection.methods.totalSupply().call();
+      expect(totalSupply).to.equal('1');
+    });
+  });
+
+  [
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'nft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: balanceOf`, testCase.requiredPallets, async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+
+      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+      await collection.methods.mint(caller).send({from: caller});
+      await collection.methods.mint(caller).send({from: caller});
+      await collection.methods.mint(caller).send({from: caller});
+
+      const balance = await collection.methods.balanceOf(caller).call();
+      expect(balance).to.equal('3');
+    });
+  });
+
+  [
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'nft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf`, testCase.requiredPallets, async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf', '6', '6');
+
+      const result = await collection.methods.mint(caller).send();
+      const tokenId = result.events.Transfer.returnValues.tokenId;
+
+      const owner = await collection.methods.ownerOf(tokenId).call();
+      expect(owner).to.equal(caller);
+    });
+  });
+
+  [
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    // TODO {mode: 'nft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf after burn`, testCase.requiredPallets, async ({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const receiver = helper.eth.createAccount();
+      const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf-AfterBurn', '6', '6');
+
+      const result = await collection.methods.mint(caller).send();
+      const tokenId = result.events.Transfer.returnValues.tokenId;
+      const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller, true);
+
+      await tokenContract.methods.repartition(2).send();
+      await tokenContract.methods.transfer(receiver, 1).send();
+
+      await tokenContract.methods.burnFrom(caller, 1).send();
+
+      const owner = await collection.methods.ownerOf(tokenId).call();
+      expect(owner).to.equal(receiver);
+    });
+  });
+
+  itEth.ifWithPallets('RFT: ownerOf for partial ownership', [Pallets.ReFungible], async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Partial-OwnerOf', '6', '6');
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
+    const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
+
+    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');
+  });
+});
addedtests/src/eth/tokens/minting.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/tokens/minting.test.ts
@@ -0,0 +1,167 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+import {Pallets} from '../../util';
+import {expect, itEth, usingEthPlaygrounds} from '../util';
+
+
+describe('Minting tokens', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+      [alice] = await helper.arrange.createAccounts([30n, 20n], donor);
+    });
+  });
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'ft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: Can mint() for Substrate collection`, testCase.requiredPallets, async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const receiver = helper.eth.createAccount();
+      const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
+
+      const collection = await helper[testCase.mode].mintCollection(alice);
+      await collection.addAdmin(alice, {Ethereum: owner});
+
+      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+      const contract = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+      const result = await contract.methods.mint(...mintingParams).send({from: owner});
+
+      // Check events:
+      const event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.equal(receiver);
+      if (testCase.mode === 'ft')
+        expect(event.returnValues.value).to.equal('100');
+
+      // Check token exist:
+      if(testCase.mode === 'ft') {
+        expect(await helper.ft.getBalance(collection.collectionId, {Ethereum: receiver})).to.eq(100n);
+      } else {
+        const tokenId = event.returnValues.tokenId;
+        expect(tokenId).to.be.equal('1');
+        expect(await helper.collection.getLastTokenId(collection.collectionId)).to.eq(1);
+        expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
+      }
+    });
+  });
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'ft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: Can mint() for Ethereum collection`, testCase.requiredPallets, async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const receiver = helper.eth.createAccount();
+      const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
+
+      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+
+      const result = await collection.methods.mint(...mintingParams).send({from: owner});
+
+      // Check events:
+      const event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.equal(receiver);
+      if (testCase.mode === 'ft')
+        expect(event.returnValues.value).to.equal('100');
+
+      // Check token exist:
+      if(testCase.mode === 'ft') {
+        expect(await helper.ft.getBalance(collectionId, {Ethereum: receiver})).to.eq(100n);
+      } else {
+        const tokenId = event.returnValues.tokenId;
+        expect(tokenId).to.be.equal('1');
+        expect(await helper.collection.getLastTokenId(collectionId)).to.eq(1);
+        expect(await collection.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
+      }
+    });
+  });
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'ft' as const, requiredPallets: []},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: Can mint() for Ethereum collection`, testCase.requiredPallets, async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const receiver = helper.eth.createAccount();
+      const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
+
+      const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+
+      const result = await collection.methods.mint(...mintingParams).send({from: owner});
+
+      // Check events:
+      const event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.equal(receiver);
+      if (testCase.mode === 'ft')
+        expect(event.returnValues.value).to.equal('100');
+
+      // Check token exist:
+      if(testCase.mode === 'ft') {
+        expect(await helper.ft.getBalance(collectionId, {Ethereum: receiver})).to.eq(100n);
+      } else {
+        const tokenId = event.returnValues.tokenId;
+        expect(tokenId).to.be.equal('1');
+        expect(await helper.collection.getLastTokenId(collectionId)).to.eq(1);
+        expect(await collection.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
+      }
+    });
+  });
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase => {
+    itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: Can mintWithTokenURI() for Ethereum collection`, testCase.requiredPallets, async ({helper}) => {
+      const owner = await helper.eth.createAccountWithBalance(donor);
+      const receiver = helper.eth.createAccount();
+
+      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
+      const contract = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+      const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+      const tokenId = result.events.Transfer.returnValues.tokenId;
+      expect(tokenId).to.be.equal('1');
+
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.be.equal(receiver);
+
+      expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
+      expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
+      // TODO: this wont work right now, need release 919000 first
+      // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
+      // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();
+      // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);
+    });
+  });
+});
\ No newline at end of file
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json';25import fungibleAbi from '../../abi/fungible.json';26import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json';27import nonFungibleAbi from '../../abi/nonFungible.json';28import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json';29import refungibleAbi from '../../abi/reFungible.json';30import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json';31import refungibleTokenAbi from '../../abi/reFungibleToken.json';32import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json';33import contractHelpersAbi from '../../abi/contractHelpers.json';34import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';35import {TCollectionMode} from '../../../util/playgrounds/types';3637class EthGroupBase {38  helper: EthUniqueHelper;39  gasPrice?: string;4041  constructor(helper: EthUniqueHelper) {42    this.helper = helper;43  }44  async getGasPrice() {45    if (this.gasPrice)46      return this.gasPrice;47    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();48    return this.gasPrice;49  }50}5152function unlimitedMoneyHack<C>(_contract: C): C {53  const contract = _contract as any;54  // Hack: fight against gasPrice override55  for (const method in contract.methods) {56    const _method = contract.methods[method];57    contract.methods[method] = function (...args: any) {58      const encodedCall = _method.call(this, ...args);59      const _call = encodedCall.call;60      encodedCall.call = function (...args: any) {61        if (args.length === 0) {62          return _call.call(this, {gasPrice: '0'});63        }64        // No support for callback/defaultBlock, they may be placed as first argument65        if (typeof args[0] !== 'object')66          throw new Error('only options are supported');67        args[0].gasPrice = '0';68        return _call.call(this, ...args);69      };70      return encodedCall;71    };72  }73  return contract;74}7576class ContractGroup extends EthGroupBase {77  async findImports(imports?: ContractImports[]){78    if(!imports) return function(path: string) {79      return {error: `File not found: ${path}`};80    };8182    const knownImports = {} as {[key: string]: string};83    for(const imp of imports) {84      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();85    }8687    return function(path: string) {88      if(path in knownImports) return {contents: knownImports[path]};89      return {error: `File not found: ${path}`};90    };91  }9293  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {94    const compiled = JSON.parse(solc.compile(JSON.stringify({95      language: 'Solidity',96      sources: {97        [`${name}.sol`]: {98          content: src,99        },100      },101      settings: {102        outputSelection: {103          '*': {104            '*': ['*'],105          },106        },107      },108    }), {import: await this.findImports(imports)}));109110    const hasErrors = compiled['errors']111      && compiled['errors'].length > 0112      && compiled.errors.some(function(err: any) {113        return err.severity == 'error';114      });115116    if (hasErrors) {117      throw compiled.errors;118    }119    const out = compiled.contracts[`${name}.sol`][name];120121    return {122      abi: out.abi,123      object: '0x' + out.evm.bytecode.object,124    };125  }126127  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {128    const compiledContract = await this.compile(name, src, imports);129    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);130  }131132  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {133    const web3 = this.helper.getWeb3();134    const contract = new web3.eth.Contract(abi, undefined, {135      data: object,136      from: signer,137      gas: gas ?? this.helper.eth.DEFAULT_GAS,138      gasPrice: await this.getGasPrice(),139    });140    return unlimitedMoneyHack(await contract.deploy({data: object}).send({from: signer}));141  }142143}144145class NativeContractGroup extends EthGroupBase {146147  async contractHelpers(caller: string): Promise<Contract> {148    const web3 = this.helper.getWeb3();149    return unlimitedMoneyHack(new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {150      from: caller,151      gas: this.helper.eth.DEFAULT_GAS,152      gasPrice: await this.getGasPrice(),153    }));154  }155156  async collectionHelpers(caller: string) {157    const web3 = this.helper.getWeb3();158    return unlimitedMoneyHack(new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {159      from: caller,160      gas: this.helper.eth.DEFAULT_GAS,161      gasPrice: await this.getGasPrice(),162    }));163  }164165  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {166    let abi = {167      'nft': nonFungibleAbi,168      'rft': refungibleAbi,169      'ft': fungibleAbi,170    }[mode];171    if (mergeDeprecated) {172      const deprecated = {173        'nft': nonFungibleDeprecatedAbi,174        'rft': refungibleDeprecatedAbi,175        'ft': fungibleDeprecatedAbi,176      }[mode];177      abi = [...abi,...deprecated];178    }179    const web3 = this.helper.getWeb3();180    return unlimitedMoneyHack(new web3.eth.Contract(abi as any, address, {181      gas: this.helper.eth.DEFAULT_GAS,182      gasPrice: await this.getGasPrice(),183      ...(caller ? {from: caller} : {}),184    }));185  }186187  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {188    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);189  }190191  async rftToken(address: string, caller?: string, mergeDeprecated = false) {192    const web3 = this.helper.getWeb3();193    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;194    return unlimitedMoneyHack(new web3.eth.Contract(abi as any, address, {195      gas: this.helper.eth.DEFAULT_GAS,196      gasPrice: await this.getGasPrice(),197      ...(caller ? {from: caller} : {}),198    }));199  }200201  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {202    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);203  }204}205206207class EthGroup extends EthGroupBase {208  DEFAULT_GAS = 2_500_000;209210  createAccount() {211    const web3 = this.helper.getWeb3();212    const account = web3.eth.accounts.create();213    web3.eth.accounts.wallet.add(account.privateKey);214    return account.address;215  }216217  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {218    const account = this.createAccount();219    await this.transferBalanceFromSubstrate(donor, account, amount);220221    return account;222  }223224  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {225    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));226  }227228  async getCollectionCreationFee(signer: string) {229    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);230    return await collectionHelper.methods.collectionCreationFee().call();231  }232233  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {234    if(!gasLimit) gasLimit = this.DEFAULT_GAS;235    const web3 = this.helper.getWeb3();236    const gasPrice = await web3.eth.getGasPrice();237    // TODO: check execution status238    await this.helper.executeExtrinsic(239      signer,240      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],241      true,242    );243  }244245  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {246    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);247  }248249  createCollectionMethodName(mode: TCollectionMode) {250    switch (mode) {251      case 'ft':252        return 'createFTCollection';253      case 'nft':254        return 'createNFTCollection';255      case 'rft':256        return 'createRFTCollection';257    }258  }259260  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {261    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();262    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);263    const functionName: string = this.createCollectionMethodName(mode);264265    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];266    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});267268    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);269    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);270    const events = this.helper.eth.normalizeEvents(result.events);271272    return {collectionId, collectionAddress, events};273  }274275  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {276    return this.createCollection('nft', signer, name, description, tokenPrefix);277  }278279  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {280    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);281282    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);283284    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();285286    return {collectionId, collectionAddress, events};287  }288289  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {290    return this.createCollection('rft', signer, name, description, tokenPrefix);291  }292293  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {294    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);295  }296297  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {298    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);299300    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);301302    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();303304    return {collectionId, collectionAddress, events};305  }306307  async deployCollectorContract(signer: string): Promise<Contract> {308    return await this.helper.ethContract.deployByCode(signer, 'Collector', `309    // SPDX-License-Identifier: UNLICENSED310    pragma solidity ^0.8.6;311312    contract Collector {313      uint256 collected;314      fallback() external payable {315        giveMoney();316      }317      function giveMoney() public payable {318        collected += msg.value;319      }320      function getCollected() public view returns (uint256) {321        return collected;322      }323      function getUnaccounted() public view returns (uint256) {324        return address(this).balance - collected;325      }326327      function withdraw(address payable target) public {328        target.transfer(collected);329        collected = 0;330      }331    }332  `);333  }334335  async deployFlipper(signer: string): Promise<Contract> {336    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `337    // SPDX-License-Identifier: UNLICENSED338    pragma solidity ^0.8.6;339340    contract Flipper {341      bool value = false;342      function flip() public {343        value = !value;344      }345      function getValue() public view returns (bool) {346        return value;347      }348    }349  `);350  }351352  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {353    const before = await this.helper.balance.getEthereum(user);354    await call();355    // In dev mode, the transaction might not finish processing in time356    await this.helper.wait.newBlocks(1);357    const after = await this.helper.balance.getEthereum(user);358359    return before - after;360  }361362  normalizeEvents(events: any): NormalizedEvent[] {363    const output = [];364    for (const key of Object.keys(events)) {365      if (key.match(/^[0-9]+$/)) {366        output.push(events[key]);367      } else if (Array.isArray(events[key])) {368        output.push(...events[key]);369      } else {370        output.push(events[key]);371      }372    }373    output.sort((a, b) => a.logIndex - b.logIndex);374    return output.map(({address, event, returnValues}) => {375      const args: { [key: string]: string } = {};376      for (const key of Object.keys(returnValues)) {377        if (!key.match(/^[0-9]+$/)) {378          args[key] = returnValues[key];379        }380      }381      return {382        address,383        event,384        args,385      };386    });387  }388389  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {390    const wrappedCode = async () => {391      await code();392      // In dev mode, the transaction might not finish processing in time393      await this.helper.wait.newBlocks(1);394    };395    return await this.helper.arrange.calculcateFee(address, wrappedCode);396  }397}398399class EthAddressGroup extends EthGroupBase {400  extractCollectionId(address: string): number {401    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');402    return parseInt(address.substr(address.length - 8), 16);403  }404405  fromCollectionId(collectionId: number): string {406    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');407    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);408  }409410  extractTokenId(address: string): {collectionId: number, tokenId: number} {411    if (!address.startsWith('0x'))412      throw 'address not starts with "0x"';413    if (address.length > 42)414      throw 'address length is more than 20 bytes';415    return {416      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),417      tokenId: Number('0x' + address.substring(address.length - 8)),418    };419  }420421  fromTokenId(collectionId: number, tokenId: number): string  {422    return this.helper.util.getTokenAddress({collectionId, tokenId});423  }424425  normalizeAddress(address: string): string {426    return '0x' + address.substring(address.length - 40);427  }428}429export class EthPropertyGroup extends EthGroupBase {430  property(key: string, value: string): EthProperty {431    return [432      key,433      '0x'+Buffer.from(value).toString('hex'),434    ];435  }436}437export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;438439export class EthCrossAccountGroup extends EthGroupBase {440  createAccount(): CrossAddress {441    return this.fromAddress(this.helper.eth.createAccount());442  }443444  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {445    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));446  }447448  fromAddress(address: TEthereumAccount): CrossAddress {449    return {450      eth: address,451      sub: '0',452    };453  }454455  fromKeyringPair(keyring: IKeyringPair): CrossAddress {456    return {457      eth: '0x0000000000000000000000000000000000000000',458      sub: keyring.addressRaw,459    };460  }461}462463export class EthUniqueHelper extends DevUniqueHelper {464  web3: Web3 | null = null;465  web3Provider: WebsocketProvider | null = null;466467  eth: EthGroup;468  ethAddress: EthAddressGroup;469  ethCrossAccount: EthCrossAccountGroup;470  ethNativeContract: NativeContractGroup;471  ethContract: ContractGroup;472  ethProperty: EthPropertyGroup;473474  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {475    options.helperBase = options.helperBase ?? EthUniqueHelper;476477    super(logger, options);478    this.eth = new EthGroup(this);479    this.ethAddress = new EthAddressGroup(this);480    this.ethCrossAccount = new EthCrossAccountGroup(this);481    this.ethNativeContract = new NativeContractGroup(this);482    this.ethContract = new ContractGroup(this);483    this.ethProperty = new EthPropertyGroup(this);484  }485486  getWeb3(): Web3 {487    if(this.web3 === null) throw Error('Web3 not connected');488    return this.web3;489  }490491  connectWeb3(wsEndpoint: string) {492    if(this.web3 !== null) return;493    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);494    this.web3 = new Web3(this.web3Provider);495  }496497  async disconnect() {498    if(this.web3 === null) return;499    this.web3Provider?.connection.close();500501    await super.disconnect();502  }503504  clearApi() {505    super.clearApi();506    this.web3 = null;507  }508509  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {510    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;511    newHelper.web3 = this.web3;512    newHelper.web3Provider = this.web3Provider;513514    return newHelper;515  }516}
after · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json';25import fungibleAbi from '../../abi/fungible.json';26import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json';27import nonFungibleAbi from '../../abi/nonFungible.json';28import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json';29import refungibleAbi from '../../abi/reFungible.json';30import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json';31import refungibleTokenAbi from '../../abi/reFungibleToken.json';32import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json';33import contractHelpersAbi from '../../abi/contractHelpers.json';34import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';35import {TCollectionMode} from '../../../util/playgrounds/types';3637class EthGroupBase {38  helper: EthUniqueHelper;39  gasPrice?: string;4041  constructor(helper: EthUniqueHelper) {42    this.helper = helper;43  }44  async getGasPrice() {45    if (this.gasPrice)46      return this.gasPrice;47    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();48    return this.gasPrice;49  }50}5152function unlimitedMoneyHack<C>(_contract: C): C {53  const contract = _contract as any;54  // Hack: fight against gasPrice override55  for (const method in contract.methods) {56    const _method = contract.methods[method];57    contract.methods[method] = function (...args: any) {58      const encodedCall = _method.call(this, ...args);59      const _call = encodedCall.call;60      encodedCall.call = function (...args: any) {61        if (args.length === 0) {62          return _call.call(this, {gasPrice: '0'});63        }64        // No support for callback/defaultBlock, they may be placed as first argument65        if (typeof args[0] !== 'object')66          throw new Error('only options are supported');67        args[0].gasPrice = '0';68        return _call.call(this, ...args);69      };70      return encodedCall;71    };72  }73  return contract;74}7576class ContractGroup extends EthGroupBase {77  async findImports(imports?: ContractImports[]){78    if(!imports) return function(path: string) {79      return {error: `File not found: ${path}`};80    };8182    const knownImports = {} as {[key: string]: string};83    for(const imp of imports) {84      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();85    }8687    return function(path: string) {88      if(path in knownImports) return {contents: knownImports[path]};89      return {error: `File not found: ${path}`};90    };91  }9293  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {94    const compiled = JSON.parse(solc.compile(JSON.stringify({95      language: 'Solidity',96      sources: {97        [`${name}.sol`]: {98          content: src,99        },100      },101      settings: {102        outputSelection: {103          '*': {104            '*': ['*'],105          },106        },107      },108    }), {import: await this.findImports(imports)}));109110    const hasErrors = compiled['errors']111      && compiled['errors'].length > 0112      && compiled.errors.some(function(err: any) {113        return err.severity == 'error';114      });115116    if (hasErrors) {117      throw compiled.errors;118    }119    const out = compiled.contracts[`${name}.sol`][name];120121    return {122      abi: out.abi,123      object: '0x' + out.evm.bytecode.object,124    };125  }126127  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {128    const compiledContract = await this.compile(name, src, imports);129    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);130  }131132  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {133    const web3 = this.helper.getWeb3();134    const contract = new web3.eth.Contract(abi, undefined, {135      data: object,136      from: signer,137      gas: gas ?? this.helper.eth.DEFAULT_GAS,138      gasPrice: await this.getGasPrice(),139    });140    return unlimitedMoneyHack(await contract.deploy({data: object}).send({from: signer}));141  }142143}144145class NativeContractGroup extends EthGroupBase {146147  async contractHelpers(caller: string): Promise<Contract> {148    const web3 = this.helper.getWeb3();149    return unlimitedMoneyHack(new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {150      from: caller,151      gas: this.helper.eth.DEFAULT_GAS,152      gasPrice: await this.getGasPrice(),153    }));154  }155156  async collectionHelpers(caller: string) {157    const web3 = this.helper.getWeb3();158    return unlimitedMoneyHack(new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {159      from: caller,160      gas: this.helper.eth.DEFAULT_GAS,161      gasPrice: await this.getGasPrice(),162    }));163  }164165  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {166    let abi = {167      'nft': nonFungibleAbi,168      'rft': refungibleAbi,169      'ft': fungibleAbi,170    }[mode];171    if (mergeDeprecated) {172      const deprecated = {173        'nft': nonFungibleDeprecatedAbi,174        'rft': refungibleDeprecatedAbi,175        'ft': fungibleDeprecatedAbi,176      }[mode];177      abi = [...abi,...deprecated];178    }179    const web3 = this.helper.getWeb3();180    return unlimitedMoneyHack(new web3.eth.Contract(abi as any, address, {181      gas: this.helper.eth.DEFAULT_GAS,182      gasPrice: await this.getGasPrice(),183      ...(caller ? {from: caller} : {}),184    }));185  }186187  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {188    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);189  }190191  async rftToken(address: string, caller?: string, mergeDeprecated = false) {192    const web3 = this.helper.getWeb3();193    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;194    return unlimitedMoneyHack(new web3.eth.Contract(abi as any, address, {195      gas: this.helper.eth.DEFAULT_GAS,196      gasPrice: await this.getGasPrice(),197      ...(caller ? {from: caller} : {}),198    }));199  }200201  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {202    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);203  }204}205206207class EthGroup extends EthGroupBase {208  DEFAULT_GAS = 2_500_000;209210  createAccount() {211    const web3 = this.helper.getWeb3();212    const account = web3.eth.accounts.create();213    web3.eth.accounts.wallet.add(account.privateKey);214    return account.address;215  }216217  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {218    const account = this.createAccount();219    await this.transferBalanceFromSubstrate(donor, account, amount);220221    return account;222  }223224  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {225    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));226  }227228  async getCollectionCreationFee(signer: string) {229    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);230    return await collectionHelper.methods.collectionCreationFee().call();231  }232233  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {234    if(!gasLimit) gasLimit = this.DEFAULT_GAS;235    const web3 = this.helper.getWeb3();236    const gasPrice = await web3.eth.getGasPrice();237    // TODO: check execution status238    await this.helper.executeExtrinsic(239      signer,240      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],241      true,242    );243  }244245  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {246    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);247  }248249  createCollectionMethodName(mode: TCollectionMode) {250    switch (mode) {251      case 'ft':252        return 'createFTCollection';253      case 'nft':254        return 'createNFTCollection';255      case 'rft':256        return 'createRFTCollection';257    }258  }259260  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {261    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();262    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);263    const functionName: string = this.createCollectionMethodName(mode);264265    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];266    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});267268    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);269    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);270    const events = this.helper.eth.normalizeEvents(result.events);271    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);272273    return {collectionId, collectionAddress, events, collection};274  }275276  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {277    return this.createCollection('nft', signer, name, description, tokenPrefix);278  }279280  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {281    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);282283    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);284285    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();286287    return {collectionId, collectionAddress, events};288  }289290  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {291    return this.createCollection('rft', signer, name, description, tokenPrefix);292  }293294  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {295    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);296  }297298  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {299    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);300301    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);302303    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();304305    return {collectionId, collectionAddress, events};306  }307308  async deployCollectorContract(signer: string): Promise<Contract> {309    return await this.helper.ethContract.deployByCode(signer, 'Collector', `310    // SPDX-License-Identifier: UNLICENSED311    pragma solidity ^0.8.6;312313    contract Collector {314      uint256 collected;315      fallback() external payable {316        giveMoney();317      }318      function giveMoney() public payable {319        collected += msg.value;320      }321      function getCollected() public view returns (uint256) {322        return collected;323      }324      function getUnaccounted() public view returns (uint256) {325        return address(this).balance - collected;326      }327328      function withdraw(address payable target) public {329        target.transfer(collected);330        collected = 0;331      }332    }333  `);334  }335336  async deployFlipper(signer: string): Promise<Contract> {337    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `338    // SPDX-License-Identifier: UNLICENSED339    pragma solidity ^0.8.6;340341    contract Flipper {342      bool value = false;343      function flip() public {344        value = !value;345      }346      function getValue() public view returns (bool) {347        return value;348      }349    }350  `);351  }352353  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {354    const before = await this.helper.balance.getEthereum(user);355    await call();356    // In dev mode, the transaction might not finish processing in time357    await this.helper.wait.newBlocks(1);358    const after = await this.helper.balance.getEthereum(user);359360    return before - after;361  }362363  normalizeEvents(events: any): NormalizedEvent[] {364    const output = [];365    for (const key of Object.keys(events)) {366      if (key.match(/^[0-9]+$/)) {367        output.push(events[key]);368      } else if (Array.isArray(events[key])) {369        output.push(...events[key]);370      } else {371        output.push(events[key]);372      }373    }374    output.sort((a, b) => a.logIndex - b.logIndex);375    return output.map(({address, event, returnValues}) => {376      const args: { [key: string]: string } = {};377      for (const key of Object.keys(returnValues)) {378        if (!key.match(/^[0-9]+$/)) {379          args[key] = returnValues[key];380        }381      }382      return {383        address,384        event,385        args,386      };387    });388  }389390  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {391    const wrappedCode = async () => {392      await code();393      // In dev mode, the transaction might not finish processing in time394      await this.helper.wait.newBlocks(1);395    };396    return await this.helper.arrange.calculcateFee(address, wrappedCode);397  }398}399400class EthAddressGroup extends EthGroupBase {401  extractCollectionId(address: string): number {402    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');403    return parseInt(address.substr(address.length - 8), 16);404  }405406  fromCollectionId(collectionId: number): string {407    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');408    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);409  }410411  extractTokenId(address: string): {collectionId: number, tokenId: number} {412    if (!address.startsWith('0x'))413      throw 'address not starts with "0x"';414    if (address.length > 42)415      throw 'address length is more than 20 bytes';416    return {417      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),418      tokenId: Number('0x' + address.substring(address.length - 8)),419    };420  }421422  fromTokenId(collectionId: number, tokenId: number): string  {423    return this.helper.util.getTokenAddress({collectionId, tokenId});424  }425426  normalizeAddress(address: string): string {427    return '0x' + address.substring(address.length - 40);428  }429}430export class EthPropertyGroup extends EthGroupBase {431  property(key: string, value: string): EthProperty {432    return [433      key,434      '0x'+Buffer.from(value).toString('hex'),435    ];436  }437}438export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;439440export class EthCrossAccountGroup extends EthGroupBase {441  createAccount(): CrossAddress {442    return this.fromAddress(this.helper.eth.createAccount());443  }444445  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {446    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));447  }448449  fromAddress(address: TEthereumAccount): CrossAddress {450    return {451      eth: address,452      sub: '0',453    };454  }455456  fromKeyringPair(keyring: IKeyringPair): CrossAddress {457    return {458      eth: '0x0000000000000000000000000000000000000000',459      sub: keyring.addressRaw,460    };461  }462}463464export class EthUniqueHelper extends DevUniqueHelper {465  web3: Web3 | null = null;466  web3Provider: WebsocketProvider | null = null;467468  eth: EthGroup;469  ethAddress: EthAddressGroup;470  ethCrossAccount: EthCrossAccountGroup;471  ethNativeContract: NativeContractGroup;472  ethContract: ContractGroup;473  ethProperty: EthPropertyGroup;474475  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {476    options.helperBase = options.helperBase ?? EthUniqueHelper;477478    super(logger, options);479    this.eth = new EthGroup(this);480    this.ethAddress = new EthAddressGroup(this);481    this.ethCrossAccount = new EthCrossAccountGroup(this);482    this.ethNativeContract = new NativeContractGroup(this);483    this.ethContract = new ContractGroup(this);484    this.ethProperty = new EthPropertyGroup(this);485  }486487  getWeb3(): Web3 {488    if(this.web3 === null) throw Error('Web3 not connected');489    return this.web3;490  }491492  connectWeb3(wsEndpoint: string) {493    if(this.web3 !== null) return;494    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);495    this.web3 = new Web3(this.web3Provider);496  }497498  async disconnect() {499    if(this.web3 === null) return;500    this.web3Provider?.connection.close();501502    await super.disconnect();503  }504505  clearApi() {506    super.clearApi();507    this.web3 = null;508  }509510  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {511    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;512    newHelper.web3 = this.web3;513    newHelper.web3Provider = this.web3Provider;514515    return newHelper;516  }517}
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
+import {expect, itSub, usingPlaygrounds} from '../util';
 
 describe('Integration Test: Composite nesting tests', () => {
   let alice: IKeyringPair;
@@ -287,54 +287,7 @@
     await collectionFT.mint(charlie, 5n);
     await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
     expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
-  });
-
-  // ---------- Re-Fungible ----------
-
-  itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
-
-    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
-    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
-    await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
-    await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    // Create an immediately nested token
-    const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
-    expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
-
-    // Create a token to be nested and nest
-    const newToken = await collectionRFT.mintToken(charlie, 5n);
-    await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
-    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
   });
-
-  itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice);
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
-
-    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionRFT.collectionId]}});
-    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
-    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
-    await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
-    await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    // Create an immediately nested token
-    const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
-    expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
-
-    // Create a token to be nested and nest
-    const newToken = await collectionRFT.mintToken(charlie, 5n);
-    await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
-    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
-  });
 });
 
 describe('Negative Test: Nesting', () => {
@@ -579,89 +532,5 @@
 
     expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
     expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);
-  });
-
-  // ---------- Re-Fungible ----------
-
-  itSub.ifWithPallets('ReFungible: disallows to nest token if nesting is disabled', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice);
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice);
-
-    // Try to create an immediately nested token
-    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
-      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-
-    // Try to create a token to be nested and nest
-    const token = await collectionRFT.mintToken(alice, 5n);
-    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
-      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
-  });
-
-  itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice);
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice);
-
-    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
-    await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
-    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    // Try to create a token to be nested and nest
-    const newToken = await collectionRFT.mintToken(alice);
-    await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
-
-    expect(await targetToken.getChildren()).to.be.length(0);
-    expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
-
-    // Nest some tokens as Alice into Bob's token
-    await newToken.transfer(alice, targetToken.nestingAccount());
-
-    // Try to pull it out
-    await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
-      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
-    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
-  });
-
-  itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice);
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice);
-
-    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: [collectionRFT.collectionId]}});
-    await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
-    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
-
-    // Try to create a token to be nested and nest
-    const newToken = await collectionRFT.mintToken(alice);
-    await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
-
-    expect(await targetToken.getChildren()).to.be.length(0);
-    expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
-
-    // Nest some tokens as Alice into Bob's token
-    await newToken.transfer(alice, targetToken.nestingAccount());
-
-    // Try to pull it out
-    await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
-      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
-    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
-  });
-
-  itSub.ifWithPallets('ReFungible: disallows to nest token to an unlisted collection', [Pallets.ReFungible], async ({helper}) => {
-    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true, restricted: []}}});
-    const collectionRFT = await helper.rft.mintCollection(alice);
-    const targetToken = await collectionNFT.mintToken(alice);
-
-    // Try to create an immediately nested token
-    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
-      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-
-    // Try to create a token to be nested and nest
-    const token = await collectionRFT.mintToken(alice, 5n);
-    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
-      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
   });
 });
modifiedtests/src/refungible.test.tsdiffbeforeafterboth
--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -88,20 +88,6 @@
     expect((await token.getTop10Owners()).length).to.be.equal(10);
   });
 
-  itSub('Transfer token pieces', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
-    expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
-
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
-    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
-
-    await expect(token.transfer(alice, {Substrate: bob.address}, 41n))
-      .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
-  });
-
   itSub('Create multiple tokens', async ({helper}) => {
     const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
     // TODO: fix mintMultipleTokens
@@ -118,56 +104,8 @@
     const lastTokenId = await collection.getLastTokenId();
     expect(lastTokenId).to.be.equal(3);
     expect(await collection.getTokenBalance(lastTokenId, {Substrate: alice.address})).to.be.equal(100n);
-  });
-
-  itSub('Burn some pieces', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
-    expect(await token.burn(alice, 99n)).to.be.true;
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);
   });
 
-  itSub('Burn all pieces', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
-
-    expect(await token.burn(alice, 100n)).to.be.true;
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.false;
-  });
-
-  itSub('Burn some pieces for multiple users', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
-    expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
-
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
-    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
-
-    expect(await token.burn(alice, 40n)).to.be.true;
-
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
-
-    expect(await token.burn(bob, 59n)).to.be.true;
-
-    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-
-    expect(await token.burn(bob, 1n)).to.be.true;
-
-    expect(await collection.doesTokenExist(token.tokenId)).to.be.false;
-  });
-
   itSub('Set allowance for token', async ({helper}) => {
     const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
     const token = await collection.mintToken(alice, 100n);
@@ -183,68 +121,6 @@
     expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);
   });
 
-  itSub('Repartition', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-
-    expect(await token.repartition(alice, 200n)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);
-    expect(await token.getTotalPieces()).to.be.equal(200n);
-
-    expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);
-    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);
-
-    await expect(token.repartition(alice, 80n))
-      .to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);
-
-    expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;
-    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
-    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);
-
-    expect(await token.repartition(bob, 150n)).to.be.true;
-    await expect(token.transfer(bob, {Substrate: alice.address}, 160n))
-      .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
-  });
-
-  itSub('Repartition with increased amount', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-    await token.repartition(alice, 200n);
-    const chainEvents = helper.chainLog.slice(-1)[0].events;
-    const event = chainEvents.find((event: any) => event.section === 'common' && event.method === 'ItemCreated');
-    expect(event).to.deep.include({
-      section: 'common',
-      method: 'ItemCreated',
-      index: [66, 2],
-      data: [
-        collection.collectionId,
-        token.tokenId,
-        {substrate: alice.address},
-        100n,
-      ],
-    });
-  });
-
-  itSub('Repartition with decreased amount', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const token = await collection.mintToken(alice, 100n);
-    await token.repartition(alice, 50n);
-    const chainEvents = helper.chainLog.slice(-1)[0].events;
-    const event = chainEvents.find((event: any) => event.section === 'common' && event.method === 'ItemDestroyed');
-    expect(event).to.deep.include({
-      section: 'common',
-      method: 'ItemDestroyed',
-      index: [66, 3],
-      data: [
-        collection.collectionId,
-        token.tokenId,
-        {substrate: alice.address},
-        50n,
-      ],
-    });
-  });
-
   itSub('Create new collection with properties', async ({helper}) => {
     const properties = [{key: 'key1', value: 'val1'}];
     const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];
@@ -252,46 +128,5 @@
     const info = await collection.getData();
     expect(info?.raw.properties).to.be.deep.equal(properties);
     expect(info?.raw.tokenPropertyPermissions).to.be.deep.equal(tokenPropertyPermissions);
-  });
-});
-
-describe('Refungible negative tests', () => {
-  let donor: IKeyringPair;
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
-
-  before(async function() {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
-
-      donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
-    });
-  });
-
-  itSub('Cannot transfer incorrect amount of token pieces', async ({helper}) => {
-    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-    const tokenAlice = await collection.mintToken(alice, 10n, {Substrate: alice.address});
-    const tokenBob = await collection.mintToken(alice, 10n, {Substrate: bob.address});
-
-    // 1. Alice cannot transfer Bob's token:
-    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
-    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
-    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 10n)).to.be.rejectedWith('common.TokenValueTooLow');
-    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
-
-    // 2. Alice cannot transfer non-existing token:
-    await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
-    await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
-
-    // 3. Zero transfer allowed (EIP-20):
-    await tokenAlice.transfer(alice, {Substrate: charlie.address}, 0n);
-
-    expect(await tokenAlice.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
-    expect(await tokenBob.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
-    expect(await tokenAlice.getBalance({Substrate: alice.address})).to.eq(10n);
-    expect(await tokenBob.getBalance({Substrate: bob.address})).to.eq(10n);
-    expect(await tokenBob.getBalance({Substrate: charlie.address})).to.eq(0n);
   });
 });
addedtests/src/sub/refungible/burn.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/sub/refungible/burn.test.ts
@@ -0,0 +1,127 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../../util';
+
+describe('Refungible: burn', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
+    });
+  });
+
+  itSub('can burn some pieces', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+    await token.burn(alice, 99n);
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);
+  });
+
+  itSub('can burn all pieces', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+
+    await token.burn(alice, 100n);
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.false;
+  });
+
+  itSub('burn pieces for multiple users', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+
+    await token.transfer(alice, {Substrate: bob.address}, 60n);
+
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
+    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
+
+    await token.burn(alice, 40n);
+
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
+
+    await token.burn(bob, 59n);
+
+    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
+
+    await token.burn(bob, 1n);
+
+    expect(await collection.doesTokenExist(token.tokenId)).to.be.false;
+  });
+
+  itSub('burn pieces by admin', async function({helper}) {
+    const collection = await helper.rft.mintCollection(alice);
+    await collection.setLimits(alice, {ownerCanTransfer: true});
+    await collection.addAdmin(alice, {Substrate: bob.address});
+    const token = await collection.mintToken(alice, 100n);
+
+    await token.burnFrom(bob, {Substrate: alice.address}, 100n);
+    expect(await token.doesExist()).to.be.false;
+  });
+});
+
+describe('Refungible: burn negative tests', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+      donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
+  });
+
+  itSub('cannot burn non-owned token pieces', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const aliceToken = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+    const bobToken = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+    // 1. Cannot burn non-owned token:
+    await expect(bobToken.burn(alice, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+    await expect(bobToken.burn(alice, 5n)).to.be.rejectedWith('common.TokenValueTooLow');
+    // 2. Cannot burn non-existing token:
+    await expect(helper.rft.burnToken(alice, 99999, 10)).to.be.rejectedWith('common.CollectionNotFound');
+    await expect(helper.rft.burnToken(alice, collection.collectionId, 99999)).to.be.rejectedWith('common.TokenValueTooLow');
+    // 3. Can burn zero amount of owned tokens (EIP-20)
+    await aliceToken.burn(alice, 0n);
+
+    // 4. Storage is not corrupted:
+    expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+    expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+
+    // 4.1 Tokens can be transfered:
+    await aliceToken.transfer(alice, {Substrate: bob.address}, 10n);
+    await bobToken.transfer(bob, {Substrate: alice.address}, 10n);
+    expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+    expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+  });
+});
addedtests/src/sub/refungible/nesting.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/sub/refungible/nesting.test.ts
@@ -0,0 +1,180 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../../util';
+
+describe('Refungible nesting', () => {
+  let alice: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+      const donor = await privateKey({filename: __filename});
+      [alice, charlie] = await helper.arrange.createAccounts([50n, 10n], donor);
+    });
+  });
+
+  [
+    {restrictedMode: true},
+    {restrictedMode: false},
+  ].map(testCase => {
+    itSub(`Owner can nest their token${testCase.restrictedMode ? ': Restricted mode' : ''}`, async ({helper}) => {
+      const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+      const collectionRFT = await helper.rft.mintCollection(alice);
+      const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
+
+      await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionRFT.collectionId] : null}});
+      await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+      await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
+
+      await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+      await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
+      await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
+
+      // Create an immediately nested token
+      const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
+      expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
+
+      // Create a token to be nested and nest
+      const newToken = await collectionRFT.mintToken(charlie, 5n);
+      await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
+      expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
+      expect(await newToken.getBalance({Substrate: charlie.address})).to.be.equal(3n);
+    });
+  });
+
+  itSub('Owner can unnest nested token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
+
+    // Owner mints nested RFT token:
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
+
+    // 1.1 Owner can partially unnest token pieces with transferFrom:
+    await token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
+
+    // 1.2 Owner can unnest all pieces:
+    await token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 1n);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(10n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+  });
+
+  itSub('Owner can burn nested token pieces', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
+
+    // Owner mints nested RFT token:
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const token = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});
+    await token.transfer(alice, targetToken.nestingAccount(), 30n);
+
+    // 1.1 Owner can partially burnFrom nested pieces:
+    await token.burnFrom(alice, targetToken.nestingAccount(), 10n);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(70n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(20n);
+    expect(await targetToken.getChildren()).to.has.length(1);
+
+    // 1.1 Owner can burnFrom all nested pieces:
+    await token.burnFrom(alice, targetToken.nestingAccount(), 20n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+    expect(await targetToken.getChildren()).to.has.length(0);
+    expect(await token.doesExist()).to.be.true;
+
+    // 2. Target token does not contain any pieces and can be burnt:
+    await targetToken.burn(alice);
+    expect(await targetToken.doesExist()).to.be.false;
+  });
+});
+
+describe('Refungible nesting negative tests', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+      const donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);
+    });
+  });
+
+  itSub('cannot nest token if nesting is disabled', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
+
+    // Try to create an immediately nested token
+    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+
+    // Try to create a token to be nested and nest
+    const token = await collectionRFT.mintToken(alice, 5n);
+    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
+  });
+
+  [
+    {restrictedMode: true},
+    {restrictedMode: false},
+  ].map(testCase => {
+    itSub(`non-Owner cannot nest someone else's token${testCase.restrictedMode ? ': Restricted mode' : ''}`, async ({helper}) => {
+      const collectionNFT = await helper.nft.mintCollection(alice);
+      const collectionRFT = await helper.rft.mintCollection(alice);
+      const targetToken = await collectionNFT.mintToken(alice);
+
+      await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionRFT.collectionId] : null}});
+      await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
+      await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
+
+      // Try to create a token to be nested and nest
+      const newToken = await collectionRFT.mintToken(alice);
+      await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
+
+      expect(await targetToken.getChildren()).to.be.length(0);
+      expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
+
+      // Nest some tokens as Alice into Bob's token
+      await newToken.transfer(alice, targetToken.nestingAccount());
+
+      // Try to pull it out
+      await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
+        .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+      expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
+    });
+  });
+
+  itSub('ReFungible: disallows to nest token to an unlisted collection', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true, restricted: []}}});
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
+
+    // Try to create an immediately nested token
+    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+
+    // Try to create a token to be nested and nest
+    const token = await collectionRFT.mintToken(alice, 5n);
+    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
+  });
+});
addedtests/src/sub/refungible/repartition.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/sub/refungible/repartition.test.ts
@@ -0,0 +1,96 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../../util';
+
+describe('integration test: Refungible functionality:', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
+    });
+  });
+
+  itSub('Repartition', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+
+    expect(await token.repartition(alice, 200n)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);
+    expect(await token.getTotalPieces()).to.be.equal(200n);
+
+    expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);
+    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);
+
+    await expect(token.repartition(alice, 80n))
+      .to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);
+
+    expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
+    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);
+
+    expect(await token.repartition(bob, 150n)).to.be.true;
+    await expect(token.transfer(bob, {Substrate: alice.address}, 160n))
+      .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
+  });
+
+  itSub('Repartition with increased amount', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+    await token.repartition(alice, 200n);
+    const chainEvents = helper.chainLog.slice(-1)[0].events;
+    const event = chainEvents.find((event: any) => event.section === 'common' && event.method === 'ItemCreated');
+    expect(event).to.deep.include({
+      section: 'common',
+      method: 'ItemCreated',
+      index: [66, 2],
+      data: [
+        collection.collectionId,
+        token.tokenId,
+        {substrate: alice.address},
+        100n,
+      ],
+    });
+  });
+
+  itSub('Repartition with decreased amount', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+    await token.repartition(alice, 50n);
+    const chainEvents = helper.chainLog.slice(-1)[0].events;
+    const event = chainEvents.find((event: any) => event.section === 'common' && event.method === 'ItemDestroyed');
+    expect(event).to.deep.include({
+      section: 'common',
+      method: 'ItemDestroyed',
+      index: [66, 3],
+      data: [
+        collection.collectionId,
+        token.tokenId,
+        {substrate: alice.address},
+        50n,
+      ],
+    });
+  });
+});
+
addedtests/src/sub/refungible/transfer.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/sub/refungible/transfer.test.ts
@@ -0,0 +1,73 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../../util';
+
+describe('Refungible transfer tests', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = await privateKey({filename: __filename});
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    });
+  });
+
+  itSub('Can transfer token pieces', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const token = await collection.mintToken(alice, 100n);
+
+    expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
+    // 1. Can transfer less or equal than have:
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
+    expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
+  });
+
+  itSub('Cannot transfer incorrect amount of token pieces', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+    const tokenAlice = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+    const tokenBob = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+    // 1. Alice cannot transfer Bob's token:
+    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 10n)).to.be.rejectedWith('common.TokenValueTooLow');
+    await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+    // 2. Alice cannot transfer non-existing token:
+    await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+    await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+    // 3. Cannot transfer more than have:
+    await expect(tokenAlice.transfer(alice, {Substrate: bob.address}, 11n))
+      .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
+
+    // 4. Zero transfer allowed (EIP-20):
+    await tokenAlice.transfer(alice, {Substrate: charlie.address}, 0n);
+
+    expect(await tokenAlice.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+    expect(await tokenBob.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+    expect(await tokenAlice.getBalance({Substrate: alice.address})).to.eq(10n);
+    expect(await tokenBob.getBalance({Substrate: bob.address})).to.eq(10n);
+    expect(await tokenBob.getBalance({Substrate: charlie.address})).to.eq(0n);
+  });
+});
\ No newline at end of file
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -100,6 +100,9 @@
 export const LOCKING_PERIOD = 12n; // 12 blocks of relay
 export const UNLOCKING_PERIOD = 6n; // 6 blocks of parachain
 
+// Native contracts
+export const COLLECTION_HELPER = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';
+export const CONTRACT_HELPER = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';
 
 export enum Pallets {
   Inflation = 'inflation',