difftreelog
Merge pull request #747 from UniqueNetwork/tests/refungible
in: master
Transfer tests
14 files changed
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -379,7 +379,7 @@
let balance_from = <Balance<T>>::get((collection.id, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- let balance_to = if from != to {
+ let balance_to = if from != to && amount != 0 {
Some(
<Balance<T>>::get((collection.id, to))
.checked_add(amount)
@@ -391,16 +391,17 @@
// =========
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- collection.id,
- TokenId::default(),
- nesting_budget,
- )?;
-
if let Some(balance_to) = balance_to {
- // from != to
+ // from != to && amount != 0
+
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ TokenId::default(),
+ nesting_budget,
+ )?;
+
if balance_from == 0 {
<Balance<T>>::remove((collection.id, from));
<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -291,6 +291,7 @@
<CommonWeights<T>>::burn_item(),
)
} else {
+ <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;
Ok(().into())
}
}
@@ -320,6 +321,7 @@
<CommonWeights<T>>::transfer(),
)
} else {
+ <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
Ok(().into())
}
}
@@ -360,6 +362,8 @@
<CommonWeights<T>>::transfer_from(),
)
} else {
+ <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
+
Ok(().into())
}
}
@@ -380,6 +384,8 @@
<CommonWeights<T>>::burn_from(),
)
} else {
+ <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
+
Ok(().into())
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -814,6 +814,20 @@
<PalletCommon<T>>::set_property_permission(collection, sender, permission)
}
+ pub fn check_token_immediate_ownership(
+ collection: &NonfungibleHandle<T>,
+ token: TokenId,
+ possible_owner: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ ensure!(
+ &token_data.owner == possible_owner,
+ <CommonError<T>>::NoPermission
+ );
+ Ok(())
+ }
+
/// Transfer NFT token from one account to another.
///
/// `from` account stops being the owner and `to` account becomes the owner of the token.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,6 +34,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
eth::EthCrossAccount,
+ Error as CommonError,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -508,6 +509,13 @@
) -> Result<()> {
collection.consume_store_reads(1)?;
let total_supply = <TotalSupply<T>>::get((collection.id, token));
+
+ if owner_balance == 0 {
+ return Err(dispatch_to_evm::<T>(
+ <CommonError<T>>::MustBeTokenOwner.into(),
+ ));
+ }
+
if total_supply != owner_balance {
return Err("token has multiple owners".into());
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -452,6 +452,10 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
+ if <Balance<T>>::get((collection.id, token, owner)) == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let total_supply = <TotalSupply<T>>::get((collection.id, token))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -739,12 +743,17 @@
<PalletCommon<T>>::ensure_correct_receiver(to)?;
let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
+
+ if initial_balance_from == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let updated_balance_from = initial_balance_from
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let mut create_target = false;
let from_to_differ = from != to;
- let updated_balance_to = if from != to {
+ let updated_balance_to = if from != to && amount != 0 {
let old_balance = <Balance<T>>::get((collection.id, token, to));
if old_balance == 0 {
create_target = true;
@@ -786,16 +795,17 @@
// =========
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- collection.id,
- token,
- nesting_budget,
- )?;
+ if let Some(updated_balance_to) = updated_balance_to {
+ // from != to && amount != 0
+
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ token,
+ nesting_budget,
+ )?;
- if let Some(updated_balance_to) = updated_balance_to {
- // from != to
if updated_balance_from == 0 {
<Balance<T>>::remove((collection.id, token, from));
<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
tests/src/burnItem.test.tsdiffbeforeafterboth--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -140,6 +140,31 @@
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}) => {
const collection = await helper.nft.mintCollection(alice);
const token = await collection.mintToken(alice);
@@ -155,4 +180,48 @@
await expect(collection.burnTokens(alice, 11n)).to.be.rejectedWith('common.TokenValueTooLow');
expect(await collection.getBalance({Substrate: alice.address})).to.eq(10n);
});
+
+ itSub('Zero burn NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Coll', description: 'Desc', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+
+ // 1. Zero burn of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero burn of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero burn of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, 9999, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.doesExist()).to.be.true;
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
+ itSub('zero burnFrom NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Zero burnFrom of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Zero burnFrom of not approved tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Zero burnFrom of approved tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can burn approved nft:
+ await approvedNft.burnFrom(alice, {Substrate: bob.address});
+ expect(await approvedNft.doesExist()).to.be.false;
+ });
});
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -277,7 +277,7 @@
}
});
- itEth('Cannot transferCross() more than have', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} incorrect amount`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const receiverEth = await helper.eth.createAccountWithBalance(donor);
const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);
@@ -289,8 +289,13 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'ft', sender);
- await expect(collectionEvm.methods.transferCross(receiverCrossEth, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
- });
+ // 1. Cannot transfer more than have
+ const receiver = testCase === 'transfer' ? receiverEth : receiverCrossEth;
+ await expect(collectionEvm.methods[testCase](receiver, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
+ // 2. Zero transfer allowed (EIP-20):
+ await collectionEvm.methods[testCase](receiver, 0n).send({from: sender});
+ }));
+
itEth('Can perform transfer()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -517,6 +517,26 @@
expect(receiverBalance).to.contain(tokenId);
}
});
+
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
+ const sender = await helper.eth.createAccountWithBalance(donor);
+ const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
+
+ const collection = await helper.nft.mintCollection(minter, {});
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', sender);
+
+ await collection.mintToken(minter, {Ethereum: sender});
+ const nonSendersToken = await collection.mintToken(minter, {Ethereum: tokenOwner});
+
+ // Cannot transferCross someone else's token:
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
});
describe('NFT: Fees', () => {
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -413,9 +413,10 @@
}
});
- itEth.skip('Cannot transferCross with invalid params', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
const collection = await helper.rft.mintCollection(minter, {});
@@ -423,12 +424,14 @@
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', sender);
await collection.mintToken(minter, 50n, {Ethereum: sender});
- const notSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+ const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+
// Cannot transferCross someone else's token:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, notSendersToken.tokenId).send({from: sender})).to.be.rejected;
- // FIXME: (transaction successful): Cannot transfer token if it does not exist:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, 999999).send({from: sender})).to.be.rejected;
- });
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {Pallets, requirePalletsOrSkip} from '../util';18import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util';19import {IKeyringPair} from '@polkadot/types/types';20import {Contract} from 'web3-eth-contract';212223describe('Refungible token: Information getting', () => {24 let donor: IKeyringPair;25 let alice: IKeyringPair;2627 before(async function() {28 await usingEthPlaygrounds(async (helper, privateKey) => {29 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);3031 donor = await privateKey({filename: __filename});32 [alice] = await helper.arrange.createAccounts([20n], donor);33 });34 });3536 itEth('totalSupply', async ({helper}) => {37 const caller = await helper.eth.createAccountWithBalance(donor);38 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});39 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});4041 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);42 const totalSupply = await contract.methods.totalSupply().call();43 expect(totalSupply).to.equal('200');44 });4546 itEth('balanceOf', async ({helper}) => {47 const caller = await helper.eth.createAccountWithBalance(donor);48 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});49 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});5051 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);52 const balance = await contract.methods.balanceOf(caller).call();53 expect(balance).to.equal('200');54 });5556 itEth('decimals', async ({helper}) => {57 const caller = await helper.eth.createAccountWithBalance(donor);58 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});59 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});6061 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);62 const decimals = await contract.methods.decimals().call();63 expect(decimals).to.equal('0');64 });65});6667// FIXME: Need erc721 for ReFubgible.68describe('Check ERC721 token URI for ReFungible', () => {69 let donor: IKeyringPair;7071 before(async function() {72 await usingEthPlaygrounds(async (helper, privateKey) => {73 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);7475 donor = await privateKey({filename: __filename});76 });77 });7879 async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {80 const owner = await helper.eth.createAccountWithBalance(donor);81 const receiver = helper.eth.createAccount();8283 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);84 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);8586 const result = await contract.methods.mint(receiver).send();8788 const event = result.events.Transfer;89 const tokenId = event.returnValues.tokenId;90 expect(tokenId).to.be.equal('1');91 expect(event.address).to.be.equal(collectionAddress);92 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');93 expect(event.returnValues.to).to.be.equal(receiver);9495 if (propertyKey && propertyValue) {96 // Set URL or suffix9798 await contract.methods.setProperties(tokenId, [{key: propertyKey, value: Buffer.from(propertyValue)}]).send();99 }100101 return {contract, nextTokenId: tokenId};102 }103104 itEth('Empty tokenURI', async ({helper}) => {105 const {contract, nextTokenId} = await setup(helper, '');106 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');107 });108109 itEth('TokenURI from url', async ({helper}) => {110 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');111 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');112 });113114 itEth('TokenURI from baseURI', async ({helper}) => {115 const {contract, nextTokenId} = await setup(helper, 'BaseURI_');116 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');117 });118119 itEth('TokenURI from baseURI + suffix', async ({helper}) => {120 const suffix = '/some/suffix';121 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);122 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);123 });124});125126describe('Refungible: Plain calls', () => {127 let donor: IKeyringPair;128 let alice: IKeyringPair;129130 before(async function() {131 await usingEthPlaygrounds(async (helper, privateKey) => {132 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);133134 donor = await privateKey({filename: __filename});135 [alice] = await helper.arrange.createAccounts([50n], donor);136 });137 });138139 itEth('Can perform approve()', async ({helper}) => {140 const owner = await helper.eth.createAccountWithBalance(donor);141 const spender = helper.eth.createAccount();142 const collection = await helper.rft.mintCollection(alice);143 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});144145 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);146 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);147148 {149 const result = await contract.methods.approve(spender, 100).send({from: owner});150 const event = result.events.Approval;151 expect(event.address).to.be.equal(tokenAddress);152 expect(event.returnValues.owner).to.be.equal(owner);153 expect(event.returnValues.spender).to.be.equal(spender);154 expect(event.returnValues.value).to.be.equal('100');155 }156157 {158 const allowance = await contract.methods.allowance(owner, spender).call();159 expect(+allowance).to.equal(100);160 }161 });162163 itEth('Can perform transferFrom()', async ({helper}) => {164 const owner = await helper.eth.createAccountWithBalance(donor);165 const spender = await helper.eth.createAccountWithBalance(donor);166 const receiver = helper.eth.createAccount();167 const collection = await helper.rft.mintCollection(alice);168 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});169170 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);171 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);172173 await contract.methods.approve(spender, 100).send();174175 {176 const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});177 let event = result.events.Transfer;178 expect(event.address).to.be.equal(tokenAddress);179 expect(event.returnValues.from).to.be.equal(owner);180 expect(event.returnValues.to).to.be.equal(receiver);181 expect(event.returnValues.value).to.be.equal('49');182183 event = result.events.Approval;184 expect(event.address).to.be.equal(tokenAddress);185 expect(event.returnValues.owner).to.be.equal(owner);186 expect(event.returnValues.spender).to.be.equal(spender);187 expect(event.returnValues.value).to.be.equal('51');188 }189190 {191 const balance = await contract.methods.balanceOf(receiver).call();192 expect(+balance).to.equal(49);193 }194195 {196 const balance = await contract.methods.balanceOf(owner).call();197 expect(+balance).to.equal(151);198 }199 });200201 itEth('Can perform transfer()', async ({helper}) => {202 const owner = await helper.eth.createAccountWithBalance(donor);203 const receiver = helper.eth.createAccount();204 const collection = await helper.rft.mintCollection(alice);205 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});206207 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);208 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);209210 {211 const result = await contract.methods.transfer(receiver, 50).send({from: owner});212 const event = result.events.Transfer;213 expect(event.address).to.be.equal(tokenAddress);214 expect(event.returnValues.from).to.be.equal(owner);215 expect(event.returnValues.to).to.be.equal(receiver);216 expect(event.returnValues.value).to.be.equal('50');217 }218219 {220 const balance = await contract.methods.balanceOf(owner).call();221 expect(+balance).to.equal(150);222 }223224 {225 const balance = await contract.methods.balanceOf(receiver).call();226 expect(+balance).to.equal(50);227 }228 });229230 itEth('Can perform repartition()', async ({helper}) => {231 const owner = await helper.eth.createAccountWithBalance(donor);232 const receiver = await helper.eth.createAccountWithBalance(donor);233 const collection = await helper.rft.mintCollection(alice);234 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});235236 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);237 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);238239 await contract.methods.repartition(200).send({from: owner});240 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);241 await contract.methods.transfer(receiver, 110).send({from: owner});242 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);243 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);244245 await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected; // Transaction is reverted246247 await contract.methods.transfer(receiver, 90).send({from: owner});248 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);249 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);250251 await contract.methods.repartition(150).send({from: receiver});252 await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected; // Transaction is reverted253 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);254 });255256 itEth('Can repartition with increased amount', async ({helper}) => {257 const owner = await helper.eth.createAccountWithBalance(donor);258 const collection = await helper.rft.mintCollection(alice);259 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});260261 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);262 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);263264 const result = await contract.methods.repartition(200).send();265266 const event = result.events.Transfer;267 expect(event.address).to.be.equal(tokenAddress);268 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');269 expect(event.returnValues.to).to.be.equal(owner);270 expect(event.returnValues.value).to.be.equal('100');271 });272273 itEth('Can repartition with decreased amount', async ({helper}) => {274 const owner = await helper.eth.createAccountWithBalance(donor);275 const collection = await helper.rft.mintCollection(alice);276 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});277278 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);279 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);280281 const result = await contract.methods.repartition(50).send();282 const event = result.events.Transfer;283 expect(event.address).to.be.equal(tokenAddress);284 expect(event.returnValues.from).to.be.equal(owner);285 expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');286 expect(event.returnValues.value).to.be.equal('50');287 });288289 itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {290 const caller = await helper.eth.createAccountWithBalance(donor);291 const receiver = await helper.eth.createAccountWithBalance(donor);292 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Devastation', '6', '6');293 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);294295 const result = await contract.methods.mint(caller).send();296 const tokenId = result.events.Transfer.returnValues.tokenId;297 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);298 const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);299300 await tokenContract.methods.repartition(2).send();301 await tokenContract.methods.transfer(receiver, 1).send();302303 const events: any = [];304 contract.events.allEvents((_: any, event: any) => {305 events.push(event);306 });307 await tokenContract.methods.burnFrom(caller, 1).send();308309 if (events.length == 0) await helper.wait.newBlocks(1);310 const event = events[0];311 expect(event.address).to.be.equal(collectionAddress);312 expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');313 expect(event.returnValues.to).to.be.equal(receiver);314 expect(event.returnValues.tokenId).to.be.equal(tokenId);315 });316});317318describe('Refungible: Fees', () => {319 let donor: IKeyringPair;320 let alice: IKeyringPair;321322 before(async function() {323 await usingEthPlaygrounds(async (helper, privateKey) => {324 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);325326 donor = await privateKey({filename: __filename});327 [alice] = await helper.arrange.createAccounts([50n], donor);328 });329 });330331 itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {332 const owner = await helper.eth.createAccountWithBalance(donor);333 const spender = helper.eth.createAccount();334 const collection = await helper.rft.mintCollection(alice);335 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});336337 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);338 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);339340 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));341 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));342 });343344 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {345 const owner = await helper.eth.createAccountWithBalance(donor);346 const spender = await helper.eth.createAccountWithBalance(donor);347 const collection = await helper.rft.mintCollection(alice);348 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});349350 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);351 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);352353 await contract.methods.approve(spender, 100).send({from: owner});354355 const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));356 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));357 });358359 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {360 const owner = await helper.eth.createAccountWithBalance(donor);361 const receiver = helper.eth.createAccount();362 const collection = await helper.rft.mintCollection(alice);363 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});364365 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);366 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);367368 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));369 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));370 });371});372373describe('Refungible: Substrate calls', () => {374 let donor: IKeyringPair;375 let alice: IKeyringPair;376377 before(async function() {378 await usingEthPlaygrounds(async (helper, privateKey) => {379 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);380381 donor = await privateKey({filename: __filename});382 [alice] = await helper.arrange.createAccounts([50n], donor);383 });384 });385386 itEth('Events emitted for approve()', async ({helper}) => {387 const receiver = helper.eth.createAccount();388 const collection = await helper.rft.mintCollection(alice);389 const token = await collection.mintToken(alice, 200n);390391 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);392 const contract = helper.ethNativeContract.rftToken(tokenAddress);393394 const events: any = [];395 contract.events.allEvents((_: any, event: any) => {396 events.push(event);397 });398399 expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;400 if (events.length == 0) await helper.wait.newBlocks(1);401 const event = events[0];402403 expect(event.event).to.be.equal('Approval');404 expect(event.address).to.be.equal(tokenAddress);405 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));406 expect(event.returnValues.spender).to.be.equal(receiver);407 expect(event.returnValues.value).to.be.equal('100');408 });409410 itEth('Events emitted for transferFrom()', async ({helper}) => {411 const [bob] = await helper.arrange.createAccounts([10n], donor);412 const receiver = helper.eth.createAccount();413 const collection = await helper.rft.mintCollection(alice);414 const token = await collection.mintToken(alice, 200n);415 await token.approve(alice, {Substrate: bob.address}, 100n);416417 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);418 const contract = helper.ethNativeContract.rftToken(tokenAddress);419420 const events: any = [];421 contract.events.allEvents((_: any, event: any) => {422 events.push(event);423 });424425 expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n)).to.be.true;426 if (events.length == 0) await helper.wait.newBlocks(1);427428 let event = events[0];429 expect(event.event).to.be.equal('Transfer');430 expect(event.address).to.be.equal(tokenAddress);431 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));432 expect(event.returnValues.to).to.be.equal(receiver);433 expect(event.returnValues.value).to.be.equal('51');434435 event = events[1];436 expect(event.event).to.be.equal('Approval');437 expect(event.address).to.be.equal(tokenAddress);438 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));439 expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));440 expect(event.returnValues.value).to.be.equal('49');441 });442443 itEth('Events emitted for transfer()', async ({helper}) => {444 const receiver = helper.eth.createAccount();445 const collection = await helper.rft.mintCollection(alice);446 const token = await collection.mintToken(alice, 200n);447448 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);449 const contract = helper.ethNativeContract.rftToken(tokenAddress);450451 const events: any = [];452 contract.events.allEvents((_: any, event: any) => {453 events.push(event);454 });455456 expect(await token.transfer(alice, {Ethereum: receiver}, 51n)).to.be.true;457 if (events.length == 0) await helper.wait.newBlocks(1);458 const event = events[0];459460 expect(event.event).to.be.equal('Transfer');461 expect(event.address).to.be.equal(tokenAddress);462 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));463 expect(event.returnValues.to).to.be.equal(receiver);464 expect(event.returnValues.value).to.be.equal('51');465 });466});467468describe('ERC 1633 implementation', () => {469 let donor: IKeyringPair;470471 before(async function() {472 await usingEthPlaygrounds(async (helper, privateKey) => {473 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);474475 donor = await privateKey({filename: __filename});476 });477 });478479 itEth('Default parent token address and id', async ({helper}) => {480 const owner = await helper.eth.createAccountWithBalance(donor);481482 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sands', '', 'GRAIN');483 const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);484485 const result = await collectionContract.methods.mint(owner).send();486 const tokenId = result.events.Transfer.returnValues.tokenId;487488 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);489 const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);490491 expect(await tokenContract.methods.parentToken().call()).to.be.equal(collectionAddress);492 expect(await tokenContract.methods.parentTokenId().call()).to.be.equal(tokenId);493 });494});tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.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 {itSub, usingPlaygrounds, expect} from './util';
+import {itSub, usingPlaygrounds, expect, requirePalletsOrSkip, Pallets} from './util';
const U128_MAX = (1n << 128n) - 1n;
@@ -145,3 +145,42 @@
expect(await collection.getBalance(ethAcc)).to.be.equal(10n);
});
});
+
+describe('Fungible 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.Fungible]);
+
+ donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('Cannot transfer incorrect amount of tokens', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const nonExistingCollection = helper.ft.getCollectionObject(99999);
+ await collection.mint(alice, 10n, {Substrate: bob.address});
+
+ // 1. Alice cannot transfer more than 0 tokens if balance low:
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 2. Alice cannot transfer non-existing token:
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.CollectionNotFound');
+
+ // 3. Zero transfer allowed (EIP-20):
+ await collection.transfer(bob, {Substrate: charlie.address}, 0n);
+ // 3.1 even if the balance = 0
+ await collection.transfer(alice, {Substrate: charlie.address}, 0n);
+
+ expect(await collection.getBalance({Substrate: alice.address})).to.eq(0n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.eq(10n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.eq(0n);
+ });
+});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -255,3 +255,43 @@
});
});
+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);
+ });
+});
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -122,6 +122,7 @@
});
});
+
itSub('[nft] Transfer with not existed collection_id', async ({helper}) => {
const collectionId = (1 << 32) - 1;
await expect(helper.nft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
@@ -191,6 +192,25 @@
.to.be.rejectedWith(/common\.TokenValueTooLow/);
});
+ itSub('Zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+ // 1. Zero transfer of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: bob.address}, collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero transfer of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero transfer of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, 10, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
itSub('[nft] Transfer with deleted item_id', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
const nft = await collection.mintToken(alice);
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -349,4 +349,27 @@
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
+
+ itSub('zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Cannot zero transferFrom (non-existing token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Cannot zero transferFrom (not approved token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Can zero transferFrom (approved token):
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can transfer approved nft:
+ await approvedNft.transferFrom(alice, {Substrate: bob.address}, {Substrate: alice.address});
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
});