difftreelog
fix native ft nesting
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6969,6 +6969,7 @@
"frame-benchmarking",
"frame-support",
"frame-system",
+ "pallet-balances",
"pallet-common",
"pallet-evm",
"pallet-evm-coder-substrate",
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -148,24 +148,6 @@
.map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
ExistenceRequirement::AllowDeath,
)?;
-
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- NATIVE_FUNGIBLE_COLLECTION_ID,
- TokenId::default(),
- nesting_budget,
- )?;
-
- let balance_from: u128 =
- <T as Config>::Currency::free_balance(from.as_sub()).into();
- if balance_from == 0 {
- <PalletStructure<T>>::unnest_if_nested(
- from,
- NATIVE_FUNGIBLE_COLLECTION_ID,
- TokenId::default(),
- );
- }
};
Ok(PostDispatchInfo {
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -12,6 +12,7 @@
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
+pallet-balances = { workspace = true }
pallet-common = { workspace = true }
pallet-evm = { workspace = true }
pallet-evm-coder-substrate = { workspace = true }
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,7 +166,11 @@
#[pallet::config]
pub trait Config:
- frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
+ frame_system::Config
+ + pallet_common::Config
+ + pallet_structure::Config
+ + pallet_evm::Config
+ + pallet_balances::Config
{
type WeightInfo: WeightInfo;
}
@@ -1325,11 +1329,15 @@
}
fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {
- <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);
+ if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+ <TokenChildren<T>>::insert((under.0, under.1, to_nest), true);
+ }
}
fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {
- <TokenChildren<T>>::remove((under.0, under.1, to_unnest));
+ if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+ <TokenChildren<T>>::remove((under.0, under.1, to_unnest));
+ }
}
fn collection_has_tokens(collection_id: CollectionId) -> bool {
@@ -1339,18 +1347,37 @@
}
fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {
- <TokenChildren<T>>::iter_prefix((collection_id, token_id))
- .next()
- .is_some()
+ let address = T::CrossTokenAddressMapping::token_to_address(collection_id, token_id);
+ let balance = <pallet_balances::Pallet<T>>::free_balance(address.as_sub());
+
+ balance > T::Balance::default()
+ || <TokenChildren<T>>::iter_prefix((collection_id, token_id))
+ .next()
+ .is_some()
}
pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {
- <TokenChildren<T>>::iter_prefix((collection_id, token_id))
- .map(|((child_collection_id, child_id), _)| TokenChild {
- collection: child_collection_id,
- token: child_id,
+ let mut tokens: Vec<_> = vec![];
+
+ let address = T::CrossTokenAddressMapping::token_to_address(collection_id, token_id);
+ let balance = <pallet_balances::Pallet<T>>::free_balance(address.as_sub());
+ if balance > T::Balance::default() {
+ tokens.push(TokenChild {
+ token: TokenId(0),
+ collection: pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID,
})
- .collect()
+ }
+
+ tokens.extend(
+ <TokenChildren<T>>::iter_prefix((collection_id, token_id)).map(
+ |((child_collection_id, child_id), _)| TokenChild {
+ collection: child_collection_id,
+ token: child_id,
+ },
+ ),
+ );
+
+ tokens
}
/// Mint single NFT token.
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -248,7 +248,7 @@
{mode: 'ft' as const},
{mode: 'native ft' as const},
].map(testCase => {
- itEth(`Disallow nest into collection without nesting permission [${testCase.mode}]`, async ({helper}) => {
+ itEth(`Disallow nest into collection without nesting permission [${testCase.mode}] (except for native fungible collection)`, async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
await targetContract.methods.setCollectionNesting(false).send({from: owner});
@@ -259,7 +259,11 @@
const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
- await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ if (testCase.mode === 'ft') {
+ await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ } else {
+ await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.not.rejected;
+ }
});
});
});
tests/src/sub/nesting/nesting.negative.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 {IKeyringPair} from '@polkadot/types/types';18import {expect, itSub, Pallets, usingPlaygrounds} from '../../util';19import {UniqueFTCollection, UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection, UniqueRFToken} from '../../util/playgrounds/unique';20import {itEth} from '../../eth/util';2122let alice: IKeyringPair;23let bob: IKeyringPair;24let charlie: IKeyringPair;2526describe('Negative Test: Nesting', () => {27 before(async () => {28 await usingPlaygrounds(async (helper, privateKey) => {29 const donor = await privateKey({url: import.meta.url});30 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);31 });32 });3334 [35 {mode: 'nft' as const, requiredPallets: []},36 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},37 ].map(testCase => {38 itSub.ifWithPallets(`Owner cannot nest ${testCase.mode.toUpperCase()} if nesting is disabled`, testCase.requiredPallets, async ({helper}) => {39 // Create default collection, permissions are not set:40 const aliceNFTCollection = await helper.nft.mintCollection(alice);41 const targetToken = await aliceNFTCollection.mintToken(alice);4243 const collectionForNesting = await helper[testCase.mode].mintCollection(alice);4445 // 1. Alice cannot create immediately nested tokens:46 const nestingTx = testCase.mode === 'nft'47 ? (collectionForNesting as UniqueNFTCollection).mintToken(alice, targetToken.nestingAccount())48 : (collectionForNesting as UniqueRFTCollection).mintToken(alice, 10n, targetToken.nestingAccount());49 await expect(nestingTx).to.be.rejectedWith('common.UserIsNotAllowedToNest');5051 // 2. Alice cannot mint and nest token:52 const nestedToken2 = await collectionForNesting.mintToken(alice);53 await expect(nestedToken2.nest(alice, targetToken)).to.be.rejectedWith('common.UserIsNotAllowedToNest');54 });55 });5657 [58 {mode: 'ft'},59 {mode: 'nativeFt'},60 ].map(testCase => {61 itSub(`Owner cannot nest [${testCase.mode}] if nesting is disabled`, async ({helper}) => {62 // Create default collection, permissions are not set:63 const aliceNFTCollection = await helper.nft.mintCollection(alice);64 const targetToken = await aliceNFTCollection.mintToken(alice);6566 const collectionForNesting = testCase.mode === 'ft' ? await helper.ft.mintCollection(alice) : helper.ft.getCollectionObject(0);6768 // Alice cannot create immediately nested tokens:69 await expect(testCase.mode === 'ft'70 ? collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())71 : collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');7273 // Alice can't mint and nest tokens:74 if (testCase.mode === 'ft') {75 await collectionForNesting.mint(alice, 100n);76 }77 await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');78 });79 });8081 [82 {mode: 'nft' as const},83 {mode: 'rft' as const},84 {mode: 'ft' as const},85 {mode: 'native ft' as const},86 ].map(testCase => {87 itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens`, async ({helper}) => {88 const targetCollection = await helper.nft.mintCollection(alice, {permissions:89 {nesting: {tokenOwner: true, collectionAdmin: true}},90 });91 const targetToken = await targetCollection.mintToken(alice);9293 const nestedCollectionBob = await (94 testCase.mode === 'native ft'95 ? helper.ft.getCollectionObject(0)96 : helper[testCase.mode].mintCollection(bob)97 );9899 let nestedTokenBob: UniqueNFToken | UniqueRFToken;100 switch (testCase.mode) {101 case 'nft': nestedTokenBob = await (nestedCollectionBob as UniqueNFTCollection).mintToken(bob); break;102 case 'rft': nestedTokenBob = await (nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n); break;103 case 'ft': await (nestedCollectionBob as UniqueFTCollection).mint(bob, 100n); break;104 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n)).to.be.rejectedWith('common.UnsupportedOperation'); break;105 }106107 // Bob non-owner of targetToken and non admin of targetCollection, so108 // 1. cannot mint nested token:109 switch (testCase.mode) {110 case 'nft': await expect((nestedCollectionBob as UniqueNFTCollection).mintToken(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;111 case 'rft': await expect((nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;112 case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;113 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UnsupportedOperation'); break;114 }115116 // 2. cannot nest existing token:117 switch (testCase.mode) {118 case 'nft':119 case 'rft': await expect(nestedTokenBob!.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;120 case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;121 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;122 }123 });124 });125126 [127 {mode: 'nft' as const, nesting: {tokenOwner: true, collectionAdmin: false}},128 {mode: 'nft' as const, nesting: {tokenOwner: false, collectionAdmin: true}},129 ].map(testCase => {130 itSub(`${testCase.nesting.tokenOwner'Admin''Token owner'} cannot nest when only ${testCase.nesting.tokenOwner'tokenOwner''collectionAdmin'} is allowed`, async ({helper}) => {131 // Create collection with tokenOwner or create collection with collectionAdmin permission:132 const targetCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: testCase.nesting}});133 const targetTokenCharlie = await targetCollection.mintToken(alice, {Substrate: charlie.address});134 await targetCollection.addAdmin(alice, {Substrate: bob.address});135136 const nestedCollectionCharlie = await helper[testCase.mode].mintCollection(charlie);137 const nestedCollectionBob = await helper[testCase.mode].mintCollection(bob);138 // if nesting permissions restricted for token owner – minter is bob (admin),139 // if collectionAdmin – charlie (owner)140 testCase.nesting.tokenOwner141 ? await expect(nestedCollectionBob.mintToken(bob, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/)142 : await expect(nestedCollectionCharlie.mintToken(charlie, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);143 });144 });145146 itSub.ifWithPallets('Cannot nest in non existing token', [Pallets.ReFungible], async ({helper}) => {147 const collection = await helper.nft.mintCollection(alice);148 // To avoid UserIsNotAllowedToNest error149 await helper.collection.setPermissions(alice, collection.collectionId, {nesting: {collectionAdmin: true}});150151 // The list of non-existing tokens:152 const tokenFromNonExistingCollection = helper.nft.getTokenObject(9999999, 1);153 const tokenBurnt = await collection.mintToken(alice);154 await tokenBurnt.burn(alice);155 const tokenNotMintedYet = helper.nft.getTokenObject(collection.collectionId, 2);156157 // The list of collections to nest tokens from:158 const nftCollectionForNesting = await helper.nft.mintCollection(alice);159 const rftCollectionForNesting = await helper.rft.mintCollection(alice);160 const ftCollectionForNesting = await helper.ft.mintCollection(alice);161 const nativeFtCollectionForNesting = helper.ft.getCollectionObject(0);162163 const testCases = [164 {token: tokenFromNonExistingCollection, error: 'CollectionNotFound'},165 {token: tokenBurnt, error: 'TokenNotFound'},166 {token: tokenNotMintedYet, error: 'TokenNotFound'},167 ];168169 for(const testCase of testCases) {170 // 1. Alice cannot create nested token to non-existing token171 await expect(nftCollectionForNesting.mintToken(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);172 await expect(rftCollectionForNesting.mintToken(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);173 await expect(ftCollectionForNesting.mint(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);174175 // 2. Alice cannot mint and nest token:176 const nft = await nftCollectionForNesting.mintToken(alice);177 const rft = await rftCollectionForNesting.mintToken(alice, 100n);178 const _ft = await ftCollectionForNesting.mint(alice, 100n);179 await expect(nft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);180 await expect(rft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);181 await expect(ftCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);182 await expect(nativeFtCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);183 }184 });185186 itEth.ifWithPallets('Cannot nest in collection address', [Pallets.ReFungible], async({helper}) => {187 const existingCollection = await helper.nft.mintCollection(alice);188 const existingCollectionAddress = helper.ethAddress.fromCollectionId(existingCollection.collectionId);189 const futureCollectionAddress = helper.ethAddress.fromCollectionId(99999999);190191 const nftCollectionForNesting = await helper.nft.mintCollection(alice);192193 // 1. Alice cannot create nested token to collection address194 await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');195 await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');196197 // 2. Alice cannot mint and nest token to collection address:198 const nft = await nftCollectionForNesting.mintToken(alice);199 await expect(nft.transfer(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');200 await expect(nft.transfer(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');201 });202203 itEth.ifWithPallets('Cannot nest in RFT or FT', [Pallets.ReFungible], async ({helper}) => {204 // Create default collection, permissions are not set:205 const rftCollection = await helper.rft.mintCollection(alice);206 const ftCollection = await helper.ft.mintCollection(alice);207 const nativeFtCollection = helper.ft.getCollectionObject(0);208209 const rftToken = await rftCollection.mintToken(alice);210 const _ftToken = await ftCollection.mint(alice, 100n);211212 const collectionForNesting = await helper.nft.mintCollection(alice);213214 // 1. Alice cannot create immediately nested tokens:215 await expect(collectionForNesting.mintToken(alice, rftToken.nestingAccount())).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');216 await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');217 await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.rejectedWith('common.UnsupportedOperation');218219 // 2. Alice cannot mint and nest token:220 const nestedToken2 = await collectionForNesting.mintToken(alice);221 await expect(nestedToken2.nest(alice, rftToken)).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');222 await expect(ftCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');223 await expect(nativeFtCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.rejectedWith('common.UnsupportedOperation');224 });225226 itSub('Cannot nest in restricted collection if collection is not in the list', async ({helper}) => {227 const {collectionId: allowedCollectionId} = await helper.nft.mintCollection(alice);228 const notAllowedCollectionNFT = await helper.nft.mintCollection(alice);229 const notAllowedCollectionRFT = await helper.rft.mintCollection(alice);230 const notAllowedCollectionFT = await helper.ft.mintCollection(alice);231 const notAllowedCollectionNativeFT = helper.ft.getCollectionObject(0);232233 // Collection restricted to allowedCollectionId234 const restrictedCollectionA = await helper.nft.mintCollection(alice, {permissions:235 {nesting: {tokenOwner: true, restricted: [allowedCollectionId]}},236 });237 // Create collection with restricted nesting -- even self is not allowed238 const restrictedCollectionB = await helper.nft.mintCollection(alice, {permissions:239 {nesting: {tokenOwner: true, restricted: []}},240 });241242 const targetTokenA = await restrictedCollectionA.mintToken(alice);243 const targetTokenB = await restrictedCollectionB.mintToken(alice);244245 // 1. Cannot mint in own collection after allowlisting the accounts:246 await expect(restrictedCollectionA.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);247 await expect(restrictedCollectionB.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);248249 // 2. Cannot mint from notAllowedCollection:250 await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);251 await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);252 await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);253 await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);254 await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);255 await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);256 await expect(notAllowedCollectionNativeFT.transfer(alice, targetTokenA.nestingAccount(), 100n)).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);257 await expect(notAllowedCollectionNativeFT.transfer(alice, targetTokenB.nestingAccount(), 100n)).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);258 });259260 itSub('Cannot create nesting chains greater than 5', async ({helper}) => {261 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});262 let token = await collection.mintToken(alice);263264 const maxNestingLevel = 5;265266 // Create a nested-token matryoshka267 for (let i = 0; i < maxNestingLevel; i++) {268 token = await collection.mintToken(alice, token.nestingAccount());269 }270271 // The nesting depth is limited by `maxNestingLevel`272 // 1. Cannot mint:273 await expect(collection.mintToken(alice, token.nestingAccount()))274 .to.be.rejectedWith(/structure\.DepthLimit/);275 // 2. Cannot transfer:276 const anotherToken = await collection.mintToken(alice);277 await expect(anotherToken.transfer(alice, token.nestingAccount()))278 .to.be.rejectedWith(/structure\.DepthLimit/);279 // 3. Cannot nest FT pieces:280 const ftCollection = await helper.ft.mintCollection(alice);281 await expect(ftCollection.mint(alice, 100n, token.nestingAccount()))282 .to.be.rejectedWith(/structure\.DepthLimit/);283284 expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});285 expect(await token.getChildren()).to.has.length(0);286 });287});1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {expect, itSub, Pallets, usingPlaygrounds} from '../../util';19import {UniqueFTCollection, UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection, UniqueRFToken} from '../../util/playgrounds/unique';20import {itEth} from '../../eth/util';2122let alice: IKeyringPair;23let bob: IKeyringPair;24let charlie: IKeyringPair;2526describe('Negative Test: Nesting', () => {27 before(async () => {28 await usingPlaygrounds(async (helper, privateKey) => {29 const donor = await privateKey({url: import.meta.url});30 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);31 });32 });3334 [35 {mode: 'nft' as const, requiredPallets: []},36 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},37 ].map(testCase => {38 itSub.ifWithPallets(`Owner cannot nest ${testCase.mode.toUpperCase()} if nesting is disabled`, testCase.requiredPallets, async ({helper}) => {39 // Create default collection, permissions are not set:40 const aliceNFTCollection = await helper.nft.mintCollection(alice);41 const targetToken = await aliceNFTCollection.mintToken(alice);4243 const collectionForNesting = await helper[testCase.mode].mintCollection(alice);4445 // 1. Alice cannot create immediately nested tokens:46 const nestingTx = testCase.mode === 'nft'47 ? (collectionForNesting as UniqueNFTCollection).mintToken(alice, targetToken.nestingAccount())48 : (collectionForNesting as UniqueRFTCollection).mintToken(alice, 10n, targetToken.nestingAccount());49 await expect(nestingTx).to.be.rejectedWith('common.UserIsNotAllowedToNest');5051 // 2. Alice cannot mint and nest token:52 const nestedToken2 = await collectionForNesting.mintToken(alice);53 await expect(nestedToken2.nest(alice, targetToken)).to.be.rejectedWith('common.UserIsNotAllowedToNest');54 });55 });5657 [58 {mode: 'ft'},59 {mode: 'nativeFt'},60 ].map(testCase => {61 itSub(`Owner cannot nest [${testCase.mode}] if nesting is disabled (except for native fungible collection)`, async ({helper}) => {62 // Create default collection, permissions are not set:63 const aliceNFTCollection = await helper.nft.mintCollection(alice);64 const targetToken = await aliceNFTCollection.mintToken(alice);6566 const collectionForNesting = testCase.mode === 'ft' ? await helper.ft.mintCollection(alice) : helper.ft.getCollectionObject(0);6768 // Alice cannot create immediately nested tokens:69 if (testCase.mode === 'ft') {70 await expect(collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest');71 } else {72 await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.not.rejected;73 }7475 // Alice can't mint and nest tokens:76 if (testCase.mode === 'ft') {77 await collectionForNesting.mint(alice, 100n);78 }7980 if (testCase.mode === 'ft') {81 await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');82 } else {83 await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.not.rejected;84 }85 });86 });8788 [89 {mode: 'nft' as const},90 {mode: 'rft' as const},91 {mode: 'ft' as const},92 {mode: 'native ft' as const},93 ].map(testCase => {94 itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens (except for native fungible collection)`, async ({helper}) => {95 const targetCollection = await helper.nft.mintCollection(alice, {permissions:96 {nesting: {tokenOwner: true, collectionAdmin: true}},97 });98 const targetToken = await targetCollection.mintToken(alice);99100 const nestedCollectionBob = await (101 testCase.mode === 'native ft'102 ? helper.ft.getCollectionObject(0)103 : helper[testCase.mode].mintCollection(bob)104 );105106 let nestedTokenBob: UniqueNFToken | UniqueRFToken;107 switch (testCase.mode) {108 case 'nft': nestedTokenBob = await (nestedCollectionBob as UniqueNFTCollection).mintToken(bob); break;109 case 'rft': nestedTokenBob = await (nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n); break;110 case 'ft': await (nestedCollectionBob as UniqueFTCollection).mint(bob, 100n); break;111 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n)).to.be.rejectedWith('common.UnsupportedOperation'); break;112 }113114 // Bob non-owner of targetToken and non admin of targetCollection, so115 // 1. cannot mint nested token:116 switch (testCase.mode) {117 case 'nft': await expect((nestedCollectionBob as UniqueNFTCollection).mintToken(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;118 case 'rft': await expect((nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;119 case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;120 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UnsupportedOperation'); break;121 }122123 // 2. cannot nest existing token:124 switch (testCase.mode) {125 case 'nft':126 case 'rft': await expect(nestedTokenBob!.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;127 case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;128 case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.not.rejected; break;129 }130 });131 });132133 [134 {mode: 'nft' as const, nesting: {tokenOwner: true, collectionAdmin: false}},135 {mode: 'nft' as const, nesting: {tokenOwner: false, collectionAdmin: true}},136 ].map(testCase => {137 itSub(`${testCase.nesting.tokenOwner'Admin''Token owner'} cannot nest when only ${testCase.nesting.tokenOwner'tokenOwner''collectionAdmin'} is allowed`, async ({helper}) => {138 // Create collection with tokenOwner or create collection with collectionAdmin permission:139 const targetCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: testCase.nesting}});140 const targetTokenCharlie = await targetCollection.mintToken(alice, {Substrate: charlie.address});141 await targetCollection.addAdmin(alice, {Substrate: bob.address});142143 const nestedCollectionCharlie = await helper[testCase.mode].mintCollection(charlie);144 const nestedCollectionBob = await helper[testCase.mode].mintCollection(bob);145 // if nesting permissions restricted for token owner – minter is bob (admin),146 // if collectionAdmin – charlie (owner)147 testCase.nesting.tokenOwner148 ? await expect(nestedCollectionBob.mintToken(bob, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/)149 : await expect(nestedCollectionCharlie.mintToken(charlie, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);150 });151 });152153 itSub.ifWithPallets('Cannot nest in non existing token (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {154 const collection = await helper.nft.mintCollection(alice);155 // To avoid UserIsNotAllowedToNest error156 await helper.collection.setPermissions(alice, collection.collectionId, {nesting: {collectionAdmin: true}});157158 // The list of non-existing tokens:159 const tokenFromNonExistingCollection = helper.nft.getTokenObject(9999999, 1);160 const tokenBurnt = await collection.mintToken(alice);161 await tokenBurnt.burn(alice);162 const tokenNotMintedYet = helper.nft.getTokenObject(collection.collectionId, 2);163164 // The list of collections to nest tokens from:165 const nftCollectionForNesting = await helper.nft.mintCollection(alice);166 const rftCollectionForNesting = await helper.rft.mintCollection(alice);167 const ftCollectionForNesting = await helper.ft.mintCollection(alice);168 const nativeFtCollectionForNesting = helper.ft.getCollectionObject(0);169170 const testCases = [171 {token: tokenFromNonExistingCollection, error: 'CollectionNotFound'},172 {token: tokenBurnt, error: 'TokenNotFound'},173 {token: tokenNotMintedYet, error: 'TokenNotFound'},174 ];175176 for(const testCase of testCases) {177 // 1. Alice cannot create nested token to non-existing token178 await expect(nftCollectionForNesting.mintToken(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);179 await expect(rftCollectionForNesting.mintToken(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);180 await expect(ftCollectionForNesting.mint(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);181182 // 2. Alice cannot mint and nest token:183 const nft = await nftCollectionForNesting.mintToken(alice);184 const rft = await rftCollectionForNesting.mintToken(alice, 100n);185 const _ft = await ftCollectionForNesting.mint(alice, 100n);186 await expect(nft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);187 await expect(rft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);188 await expect(ftCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);189 await expect(nativeFtCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.not.rejected;190 }191 });192193 itEth.ifWithPallets('Cannot nest in collection address', [Pallets.ReFungible], async({helper}) => {194 const existingCollection = await helper.nft.mintCollection(alice);195 const existingCollectionAddress = helper.ethAddress.fromCollectionId(existingCollection.collectionId);196 const futureCollectionAddress = helper.ethAddress.fromCollectionId(99999999);197198 const nftCollectionForNesting = await helper.nft.mintCollection(alice);199200 // 1. Alice cannot create nested token to collection address201 await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');202 await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');203204 // 2. Alice cannot mint and nest token to collection address:205 const nft = await nftCollectionForNesting.mintToken(alice);206 await expect(nft.transfer(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');207 await expect(nft.transfer(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');208 });209210 itEth.ifWithPallets('Cannot nest in RFT or FT (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {211 // Create default collection, permissions are not set:212 const rftCollection = await helper.rft.mintCollection(alice);213 const ftCollection = await helper.ft.mintCollection(alice);214 const nativeFtCollection = helper.ft.getCollectionObject(0);215216 const rftToken = await rftCollection.mintToken(alice);217 const _ftToken = await ftCollection.mint(alice, 100n);218219 const collectionForNesting = await helper.nft.mintCollection(alice);220221 // 1. Alice cannot create immediately nested tokens:222 await expect(collectionForNesting.mintToken(alice, rftToken.nestingAccount())).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');223 await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');224 await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.rejectedWith('common.UnsupportedOperation');225226 // 2. Alice cannot mint and nest token:227 const nestedToken2 = await collectionForNesting.mintToken(alice);228 await expect(nestedToken2.nest(alice, rftToken)).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');229 await expect(ftCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');230 await expect(nativeFtCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.not.rejected;231 });232233 itSub('Cannot nest in restricted collection if collection is not in the list (except native fungible collection)', async ({helper}) => {234 const {collectionId: allowedCollectionId} = await helper.nft.mintCollection(alice);235 const notAllowedCollectionNFT = await helper.nft.mintCollection(alice);236 const notAllowedCollectionRFT = await helper.rft.mintCollection(alice);237 const notAllowedCollectionFT = await helper.ft.mintCollection(alice);238 const allowedCollectionNativeFT = helper.ft.getCollectionObject(0);239240 // Collection restricted to allowedCollectionId241 const restrictedCollectionA = await helper.nft.mintCollection(alice, {permissions:242 {nesting: {tokenOwner: true, restricted: [allowedCollectionId]}},243 });244 // Create collection with restricted nesting -- even self is not allowed245 const restrictedCollectionB = await helper.nft.mintCollection(alice, {permissions:246 {nesting: {tokenOwner: true, restricted: []}},247 });248249 const targetTokenA = await restrictedCollectionA.mintToken(alice);250 const targetTokenB = await restrictedCollectionB.mintToken(alice);251252 // 1. Cannot mint in own collection after allowlisting the accounts:253 await expect(restrictedCollectionA.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);254 await expect(restrictedCollectionB.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);255256 // 2. Cannot mint from notAllowedCollection:257 await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);258 await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);259 await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);260 await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);261 await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);262 await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);263 await expect(allowedCollectionNativeFT.transfer(alice, targetTokenA.nestingAccount(), 100n)).to.be.not.rejected;264 await expect(allowedCollectionNativeFT.transfer(alice, targetTokenB.nestingAccount(), 100n)).to.be.not.rejected;265 });266267 itSub('Cannot create nesting chains greater than 5', async ({helper}) => {268 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});269 let token = await collection.mintToken(alice);270271 const maxNestingLevel = 5;272273 // Create a nested-token matryoshka274 for (let i = 0; i < maxNestingLevel; i++) {275 token = await collection.mintToken(alice, token.nestingAccount());276 }277278 // The nesting depth is limited by `maxNestingLevel`279 // 1. Cannot mint:280 await expect(collection.mintToken(alice, token.nestingAccount()))281 .to.be.rejectedWith(/structure\.DepthLimit/);282 // 2. Cannot transfer:283 const anotherToken = await collection.mintToken(alice);284 await expect(anotherToken.transfer(alice, token.nestingAccount()))285 .to.be.rejectedWith(/structure\.DepthLimit/);286 // 3. Cannot nest FT pieces:287 const ftCollection = await helper.ft.mintCollection(alice);288 await expect(ftCollection.mint(alice, 100n, token.nestingAccount()))289 .to.be.rejectedWith(/structure\.DepthLimit/);290291 expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});292 expect(await token.getChildren()).to.has.length(0);293 });294});