difftreelog
Merge pull request #848 from UniqueNetwork/fix/find-parent
in: master
15 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -28,8 +28,8 @@
use sp_std::{vec, vec::Vec};
use sp_core::U256;
use up_data_structs::{
- AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
- SponsoringRateLimit, SponsorshipState,
+ CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,
+ SponsorshipState,
};
use crate::{
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -80,10 +80,7 @@
if cross_account_id.is_canonical_substrate() {
Self::from_sub::<T>(cross_account_id.as_sub())
} else {
- Self {
- eth: *cross_account_id.as_eth(),
- sub: Default::default(),
- }
+ Self::from_eth(*cross_account_id.as_eth())
}
}
/// Creates [`CrossAddress`] from Substrate account.
@@ -97,6 +94,13 @@
sub: U256::from_big_endian(account_id.as_ref()),
}
}
+ /// Creates [`CrossAddress`] from Ethereum account.
+ pub fn from_eth(address: Address) -> Self {
+ Self {
+ eth: address,
+ sub: Default::default(),
+ }
+ }
/// Converts [`CrossAddress`] to `CrossAccountId`.
pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>
where
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -100,6 +100,7 @@
PropertyValue,
PropertyPermission,
PropertiesError,
+ TokenOwnerError,
PropertyKeyPermission,
TokenData,
TrySetProperty,
@@ -2134,7 +2135,7 @@
/// Get the owner of the token.
///
/// * `token` - The token for which you need to find out the owner.
- fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
+ fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
/// Returns 10 tokens owners in no particular order.
///
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,9 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
-use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
+use up_data_structs::{
+ TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData, TokenOwnerError,
+};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
weights::WeightInfo as _,
@@ -404,8 +406,8 @@
TokenId::default()
}
- fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
- None
+ fn token_owner(&self, _token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+ Err(TokenOwnerError::MultipleOwners)
}
/// Returns 10 tokens owners in no particular order.
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -19,7 +19,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{
TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,
- PropertyKeyPermission, PropertyValue,
+ PropertyKeyPermission, PropertyValue, TokenOwnerError,
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
@@ -460,13 +460,15 @@
TokenId(<TokensMinted<T>>::get(self.id))
}
- fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
- <TokenData<T>>::get((self.id, token)).map(|t| t.owner)
+ fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+ <TokenData<T>>::get((self.id, token))
+ .map(|t| t.owner)
+ .ok_or(TokenOwnerError::NotFound)
}
/// Returns token owners.
fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
- self.token_owner(token).map_or_else(|| vec![], |t| vec![t])
+ self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -728,7 +728,7 @@
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
Self::token_owner(&self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
- .ok_or(Error::Revert("key too large".into()))
+ .map_err(|_| Error::Revert("token not found".into()))
}
/// Returns the token properties.
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -741,7 +741,8 @@
Some((collection_id, nft_id)),
&target_nft_budget,
)
- .map_err(Self::map_unique_err_to_proxy)?;
+ .map_err(Self::map_unique_err_to_proxy)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
approval_required = cross_sender != target_nft_owner;
@@ -989,7 +990,8 @@
let nft_owner =
<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ .map_err(|_| <Error<T>>::ResourceDoesntExist)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
Self::try_mutate_resource_info(collection_id, nft_id, resource_id, |res| {
ensure!(res.pending, <Error<T>>::ResourceNotPending);
@@ -1044,7 +1046,8 @@
let nft_owner =
<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ .map_err(|_| <Error<T>>::ResourceDoesntExist)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
ensure!(cross_sender == nft_owner, <Error<T>>::NoPermission);
@@ -1666,7 +1669,8 @@
let budget = budget::Value::new(NESTING_BUDGET);
let nft_owner = <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(Self::map_unique_err_to_proxy)?;
+ .map_err(Self::map_unique_err_to_proxy)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
let pending = sender != nft_owner;
@@ -1720,7 +1724,8 @@
let budget = up_data_structs::budget::Value::new(NESTING_BUDGET);
let topmost_owner =
- <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?;
+ <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
let sender = T::CrossAccountId::from_sub(sender);
if topmost_owner == sender {
pallets/proxy-rmrk-core/src/rpc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/rpc.rs
+++ b/pallets/proxy-rmrk-core/src/rpc.rs
@@ -68,7 +68,7 @@
}
let owner = match collection.token_owner(nft_id) {
- Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+ Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
Some((col, tok)) => {
let rmrk_collection = <Pallet<T>>::rmrk_collection_id(col)?;
@@ -76,7 +76,7 @@
}
None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone()),
},
- None => return Ok(None),
+ _ => return Ok(None),
};
Ok(Some(RmrkInstanceInfo {
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -21,7 +21,7 @@
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,
PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,
- CreateRefungibleExSingleOwner,
+ CreateRefungibleExSingleOwner, TokenOwnerError,
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
@@ -478,7 +478,7 @@
TokenId(<TokensMinted<T>>::get(self.id))
}
- fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
+ fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
<Pallet<T>>::token_owner(self.id, token)
}
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -43,7 +43,7 @@
use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
use up_data_structs::{
CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,
- PropertyKeyPermission, PropertyPermission, TokenId,
+ PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,
};
use crate::{
@@ -411,9 +411,12 @@
self.consume_store_reads(2)?;
let token = token_id.try_into()?;
let owner = <Pallet<T>>::token_owner(self.id, token);
- Ok(owner
+ owner
.map(|address| *address.as_eth())
- .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))
+ .or_else(|err| match err {
+ TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+ TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),
+ })
}
/// @dev Not implemented
@@ -766,7 +769,12 @@
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
Self::token_owner(&self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
- .ok_or(Error::Revert("key too large".into()))
+ .or_else(|err| match err {
+ TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+ TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(
+ ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+ )),
+ })
}
/// Returns the token properties.
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -107,7 +107,7 @@
AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,
- TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,
+ TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
};
pub use pallet::*;
@@ -480,7 +480,7 @@
<Balance<T>>::remove((collection.id, token, owner));
<AccountBalance<T>>::insert((collection.id, owner), account_balance);
- if let Some(user) = Self::token_owner(collection.id, token) {
+ if let Ok(user) = Self::token_owner(collection.id, token) {
<PalletEvm<T>>::deposit_log(
ERC721Events::Transfer {
from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
@@ -1365,17 +1365,20 @@
Ok(())
}
- fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {
+ fn token_owner(
+ collection_id: CollectionId,
+ token_id: TokenId,
+ ) -> Result<T::CrossAccountId, TokenOwnerError> {
let mut owner = None;
let mut count = 0;
for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {
count += 1;
if count > 1 {
- return None;
+ return Err(TokenOwnerError::MultipleOwners);
}
owner = Some(key);
}
- owner
+ owner.ok_or(TokenOwnerError::NotFound)
}
fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -61,7 +61,9 @@
use frame_support::fail;
pub use pallet::*;
use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
-use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};
+use up_data_structs::{
+ CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
+};
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
@@ -135,6 +137,8 @@
User(CrossAccountId),
/// Could not find the token provided as the owner.
TokenNotFound,
+ /// Nested token has multiple owners.
+ MultipleOwners,
/// Token owner is another token (still, the target token may not exist).
Token(CollectionId, TokenId),
}
@@ -159,11 +163,12 @@
let handle = handle.as_dyn();
Ok(match handle.token_owner(token) {
- Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+ Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
Some((collection, token)) => Parent::Token(collection, token),
None => Parent::User(owner),
},
- None => Parent::TokenNotFound,
+ Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,
+ Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,
})
}
@@ -203,19 +208,27 @@
///
/// May return token address if parent token not yet exists
///
+ /// Returns `None` if the token has multiple owners.
+ ///
/// - `budget`: Limit for searching parents in depth.
pub fn find_topmost_owner(
collection: CollectionId,
token: TokenId,
budget: &dyn Budget,
- ) -> Result<T::CrossAccountId, DispatchError> {
+ ) -> Result<Option<T::CrossAccountId>, DispatchError> {
let owner = Self::parent_chain(collection, token)
.take_while(|_| budget.consume())
- .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
+ .find(|p| {
+ matches!(
+ p,
+ Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)
+ )
+ })
.ok_or(<Error<T>>::DepthLimit)??;
Ok(match owner {
- Parent::User(v) => v,
+ Parent::User(v) => Some(v),
+ Parent::MultipleOwners => None,
_ => fail!(<Error<T>>::TokenNotFound),
})
}
@@ -223,13 +236,15 @@
/// Find the topmost parent and check that assigning `for_nest` token as a child for
/// `token` wouldn't create a cycle.
///
+ /// Returns `None` if the token has multiple owners.
+ ///
/// - `budget`: Limit for searching parents in depth.
pub fn get_checked_topmost_owner(
collection: CollectionId,
token: TokenId,
for_nest: Option<(CollectionId, TokenId)>,
budget: &dyn Budget,
- ) -> Result<T::CrossAccountId, DispatchError> {
+ ) -> Result<Option<T::CrossAccountId>, DispatchError> {
// Tried to nest token in itself
if Some((collection, token)) == for_nest {
return Err(<Error<T>>::OuroborosDetected.into());
@@ -242,8 +257,9 @@
return Err(<Error<T>>::OuroborosDetected.into())
}
// Token is owned by other user
- Parent::User(user) => return Ok(user),
+ Parent::User(user) => return Ok(Some(user)),
Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
+ Parent::MultipleOwners => return Ok(None),
// Continue parent chain
Parent::Token(_, _) => {}
}
@@ -284,12 +300,17 @@
budget: &dyn Budget,
) -> Result<bool, DispatchError> {
let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
- Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+ Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?
+ {
+ Some(topmost_owner) => topmost_owner,
+ None => return Ok(false),
+ },
None => user,
};
- Self::get_checked_topmost_owner(collection, token, for_nest, budget)
- .map(|indirect_owner| indirect_owner == target_parent)
+ Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {
+ indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)
+ })
}
/// Checks that `under` is valid token and that `token_id` could be nested under it
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1099,6 +1099,13 @@
EmptyPropertyKey,
}
+/// Token owner error: it could be either `NotFound` ot `MultipleOwners`.
+#[derive(Debug)]
+pub enum TokenOwnerError {
+ NotFound,
+ MultipleOwners,
+}
+
/// Marker for scope of property.
///
/// Scoped property can't be changed by user. Used for external collections.
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -16,11 +16,11 @@
#[macro_export]
macro_rules! dispatch_unique_runtime {
- ($collection:ident.$method:ident($($name:ident),*)) => {{
+ ($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{
let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
let dispatch = collection.as_dyn();
- Ok::<_, DispatchError>(dispatch.$method($($name),*))
+ Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)
}};
}
@@ -73,7 +73,7 @@
}
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
- dispatch_unique_runtime!(collection.token_owner(token))
+ dispatch_unique_runtime!(collection.token_owner(token).ok())
}
fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {
@@ -83,7 +83,7 @@
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
- Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
+ Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
}
fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
tests/src/nesting/nest.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, usingPlaygrounds} from '../util';1920describe('Integration Test: Composite nesting tests', () => {21 let alice: IKeyringPair;22 let bob: IKeyringPair;2324 before(async () => {25 await usingPlaygrounds(async (helper, privateKey) => {26 const donor = await privateKey({filename: __filename});27 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);28 });29 });3031 itSub('Performs the full suite: bundles a token, transfers, and unnests', async ({helper}) => {32 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});33 const targetToken = await collection.mintToken(alice);3435 // Create an immediately nested token36 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());37 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});38 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());3940 // Create a token to be nested41 const newToken = await collection.mintToken(alice);4243 // Nest44 await newToken.nest(alice, targetToken);45 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});46 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());4748 // Move bundle to different user49 await targetToken.transfer(alice, {Substrate: bob.address});50 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});51 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());52 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});53 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());5455 // Unnest56 await newToken.unnest(bob, targetToken, {Substrate: bob.address});57 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});58 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});59 });6061 itSub('Transfers an already bundled token', async ({helper}) => {62 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});63 const tokenA = await collection.mintToken(alice);64 const tokenB = await collection.mintToken(alice);6566 // Create a nested token67 const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());68 expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());6970 // Transfer the nested token to another token71 await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;72 expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});73 expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());74 });7576 itSub('Checks token children', async ({helper}) => {77 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});78 const collectionB = await helper.ft.mintCollection(alice);7980 const targetToken = await collectionA.mintToken(alice);81 expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');8283 // Create a nested NFT token84 const tokenA = await collectionA.mintToken(alice, targetToken.nestingAccount());85 expect(await targetToken.getChildren()).to.have.deep.members([86 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},87 ], 'Children contents check at nesting #1').and.be.length(1, 'Children length check at nesting #1');8889 // Create then nest90 const tokenB = await collectionA.mintToken(alice);91 await tokenB.nest(alice, targetToken);92 expect(await targetToken.getChildren()).to.have.deep.members([93 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},94 {tokenId: tokenB.tokenId, collectionId: collectionA.collectionId},95 ], 'Children contents check at nesting #2').and.be.length(2, 'Children length check at nesting #2');9697 // Move token B to a different user outside the nesting tree98 await tokenB.unnest(alice, targetToken, {Substrate: bob.address});99 expect(await targetToken.getChildren()).to.be.have.deep.members([100 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},101 ], 'Children contents check at nesting #3 (unnesting)').and.be.length(1, 'Children length check at nesting #3 (unnesting)');102103 // Create a fungible token in another collection and then nest104 await collectionB.mint(alice, 10n);105 await collectionB.transfer(alice, targetToken.nestingAccount(), 2n);106 expect(await targetToken.getChildren()).to.be.have.deep.members([107 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},108 {tokenId: 0, collectionId: collectionB.collectionId},109 ], 'Children contents check at nesting #4 (from another collection)')110 .and.be.length(2, 'Children length check at nesting #4 (from another collection)');111112 // Move part of the fungible token inside token A deeper in the nesting tree113 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);114 expect(await targetToken.getChildren()).to.be.have.deep.members([115 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},116 {tokenId: 0, collectionId: collectionB.collectionId},117 ], 'Children contents check at nesting #5 (deeper)').and.be.length(2, 'Children length check at nesting #5 (deeper)');118 expect(await tokenA.getChildren()).to.be.have.deep.members([119 {tokenId: 0, collectionId: collectionB.collectionId},120 ], 'Children contents check at nesting #5.5 (deeper)').and.be.length(1, 'Children length check at nesting #5.5 (deeper)');121122 // Move the remaining part of the fungible token inside token A deeper in the nesting tree123 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);124 expect(await targetToken.getChildren()).to.be.have.deep.members([125 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},126 ], 'Children contents check at nesting #6 (deeper)').and.be.length(1, 'Children length check at nesting #6 (deeper)');127 expect(await tokenA.getChildren()).to.be.have.deep.members([128 {tokenId: 0, collectionId: collectionB.collectionId},129 ], 'Children contents check at nesting #6.5 (deeper)').and.be.length(1, 'Children length check at nesting #6.5 (deeper)');130 });131});132133describe('Integration Test: Various token type nesting', () => {134 let alice: IKeyringPair;135 let bob: IKeyringPair;136 let charlie: IKeyringPair;137138 before(async () => {139 await usingPlaygrounds(async (helper, privateKey) => {140 const donor = await privateKey({filename: __filename});141 [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);142 });143 });144145 itSub('Admin (NFT): allows an Admin to nest a token', async ({helper}) => {146 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true}}});147 await collection.addAdmin(alice, {Substrate: bob.address});148 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});149150 // Create an immediately nested token151 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());152 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});153 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());154155 // Create a token to be nested and nest156 const newToken = await collection.mintToken(bob);157 await newToken.nest(bob, targetToken);158 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});159 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());160 });161162 itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {163 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});164 await collection.addAdmin(alice, {Substrate: bob.address});165 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});166167 // Create an immediately nested token by an administrator168 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());169 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});170 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());171172 // Create a token to be nested and nest173 const newToken = await collection.mintToken(alice, {Substrate: charlie.address});174 await newToken.nest(charlie, targetToken);175 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});176 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());177 });178179 itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {180 const collectionA = await helper.nft.mintCollection(alice);181 await collectionA.addAdmin(alice, {Substrate: bob.address});182 const collectionB = await helper.nft.mintCollection(alice);183 await collectionB.addAdmin(alice, {Substrate: bob.address});184 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted:[collectionB.collectionId]}});185 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});186187 // Create an immediately nested token188 const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());189 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});190 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());191192 // Create a token to be nested and nest193 const newToken = await collectionB.mintToken(bob);194 await newToken.nest(bob, targetToken);195 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});196 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());197 });198199 // ---------- Non-Fungible ----------200201 itSub('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {202 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});203 await collection.addToAllowList(alice, {Substrate: charlie.address});204 const targetToken = await collection.mintToken(charlie);205 await collection.addToAllowList(alice, targetToken.nestingAccount());206207 // Create an immediately nested token208 const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());209 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});210 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());211212 // Create a token to be nested and nest213 const newToken = await collection.mintToken(charlie);214 await newToken.nest(charlie, targetToken);215 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});216 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());217 });218219 itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {220 const collectionA = await helper.nft.mintCollection(alice);221 const collectionB = await helper.nft.mintCollection(alice);222 //await collectionB.addAdmin(alice, {Substrate: bob.address});223 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});224225 await collectionA.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionB.collectionId]}});226 await collectionA.addToAllowList(alice, {Substrate: charlie.address});227 await collectionA.addToAllowList(alice, targetToken.nestingAccount());228229 await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});230 await collectionB.addToAllowList(alice, {Substrate: charlie.address});231 await collectionB.addToAllowList(alice, targetToken.nestingAccount());232233 // Create an immediately nested token234 const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());235 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});236 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());237238 // Create a token to be nested and nest239 const newToken = await collectionB.mintToken(charlie);240 await newToken.nest(charlie, targetToken);241 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});242 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());243 });244245 // ---------- Fungible ----------246247 itSub('Fungible: allows an Owner to nest/unnest their token', async ({helper}) => {248 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});249 const collectionFT = await helper.ft.mintCollection(alice);250 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});251252 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});253 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());254255 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});256 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});257 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());258259 // Create an immediately nested token260 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());261 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);262263 // Create a token to be nested and nest264 await collectionFT.mint(charlie, 5n);265 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);266 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);267 });268269 itSub('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {270 const collectionNFT = await helper.nft.mintCollection(alice);271 const collectionFT = await helper.ft.mintCollection(alice);272 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});273274 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionFT.collectionId]}});275 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});276 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());277278 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});279 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});280 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());281282 // Create an immediately nested token283 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());284 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);285286 // Create a token to be nested and nest287 await collectionFT.mint(charlie, 5n);288 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);289 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);290 });291});292293describe('Negative Test: Nesting', () => {294 let alice: IKeyringPair;295 let bob: IKeyringPair;296297 before(async () => {298 await usingPlaygrounds(async (helper, privateKey) => {299 const donor = await privateKey({filename: __filename});300 [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);301 });302 });303304 itSub('Disallows excessive token nesting', async ({helper}) => {305 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});306 let token = await collection.mintToken(alice);307308 const maxNestingLevel = 5;309310 // Create a nested-token matryoshka311 for (let i = 0; i < maxNestingLevel; i++) {312 token = await collection.mintToken(alice, token.nestingAccount());313 }314315 // The nesting depth is limited by `maxNestingLevel`316 await expect(collection.mintToken(alice, token.nestingAccount()))317 .to.be.rejectedWith(/structure\.DepthLimit/);318 expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});319 expect(await token.getChildren()).to.be.length(0);320 });321322 // ---------- Admin ------------323324 itSub('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async ({helper}) => {325 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});326 await collection.addAdmin(alice, {Substrate: bob.address});327 const targetToken = await collection.mintToken(alice);328329 // Try to create an immediately nested token as collection admin when it's disallowed330 await expect(collection.mintToken(bob, targetToken.nestingAccount()))331 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);332333 // Try to create a token to be nested and nest334 const newToken = await collection.mintToken(bob);335 await expect(newToken.nest(bob, targetToken))336 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);337338 expect(await targetToken.getChildren()).to.be.length(0);339 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});340 });341342 itSub('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async ({helper}) => {343 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});344 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});345 await collection.addToAllowList(alice, {Substrate: bob.address});346 await collection.addToAllowList(alice, targetToken.nestingAccount());347348 // Try to create a nested token as token owner when it's disallowed349 await expect(collection.mintToken(bob, targetToken.nestingAccount()))350 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);351352 // Try to create a token to be nested and nest353 const newToken = await collection.mintToken(bob);354 await expect(newToken.nest(bob, targetToken))355 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);356357 expect(await targetToken.getChildren()).to.be.length(0);358 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});359 });360361 itSub('Admin (NFT): disallows an Admin to unnest someone else\'s token', async ({helper}) => {362 const collection = await helper.nft.mintCollection(alice, {limits: {ownerCanTransfer: true}, permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});363 //await collection.addAdmin(alice, {Substrate: bob.address});364 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});365 await collection.addToAllowList(alice, {Substrate: bob.address});366 await collection.addToAllowList(alice, targetToken.nestingAccount());367368 // Try to nest somebody else's token369 const newToken = await collection.mintToken(bob);370 await expect(newToken.nest(alice, targetToken))371 .to.be.rejectedWith(/common\.NoPermission/);372373 // Try to unnest a token belonging to someone else as collection admin374 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());375 await expect(nestedToken.unnest(alice, targetToken, {Substrate: bob.address}))376 .to.be.rejectedWith(/common\.AddressNotInAllowlist/);377378 expect(await targetToken.getChildren()).to.be.length(1);379 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});380 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());381 });382383 itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {384 const collectionA = await helper.nft.mintCollection(alice);385 const collectionB = await helper.nft.mintCollection(alice);386 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted: [collectionA.collectionId]}});387 const targetToken = await collectionA.mintToken(alice);388389 // Try to create a nested token from another collection390 await expect(collectionB.mintToken(alice, targetToken.nestingAccount()))391 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);392393 // Create a token in another collection yet to be nested and try to nest394 const newToken = await collectionB.mintToken(alice);395 await expect(newToken.nest(alice, targetToken))396 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);397398 expect(await targetToken.getChildren()).to.be.length(0);399 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});400 });401402 // ---------- Non-Fungible ----------403404 itSub('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {405 // Collection is implicitly not allowed nesting at creation406 const collection = await helper.nft.mintCollection(alice);407 const targetToken = await collection.mintToken(alice);408409 // Try to create a nested token as token owner when it's disallowed410 await expect(collection.mintToken(alice, targetToken.nestingAccount()))411 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);412413 // Try to create a token to be nested and nest414 const newToken = await collection.mintToken(alice);415 await expect(newToken.nest(alice, targetToken))416 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);417418 expect(await targetToken.getChildren()).to.be.length(0);419 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});420 });421422 itSub('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {423 const collection = await helper.nft.mintCollection(alice);424 const targetToken = await collection.mintToken(alice);425426 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});427 await collection.addToAllowList(alice, {Substrate: bob.address});428 await collection.addToAllowList(alice, targetToken.nestingAccount());429430 // Try to create a token to be nested and nest431 const newToken = await collection.mintToken(alice);432 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);433434 expect(await targetToken.getChildren()).to.be.length(0);435 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});436 });437438 itSub('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {439 const collection = await helper.nft.mintCollection(alice);440 const targetToken = await collection.mintToken(alice);441442 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});443 await collection.addToAllowList(alice, {Substrate: bob.address});444 await collection.addToAllowList(alice, targetToken.nestingAccount());445446 const collectionB = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true}});447 await collectionB.addToAllowList(alice, {Substrate: bob.address});448 await collectionB.addToAllowList(alice, targetToken.nestingAccount());449450 // Try to create a token to be nested and nest451 const newToken = await collectionB.mintToken(alice);452 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);453454 expect(await targetToken.getChildren()).to.be.length(0);455 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});456 });457458 itSub('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {459 // Create collection with restricted nesting -- even self is not allowed460 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: []}}});461 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});462463 await collection.addToAllowList(alice, {Substrate: bob.address});464 await collection.addToAllowList(alice, targetToken.nestingAccount());465466 // Try to mint in own collection after allowlisting the accounts467 await expect(collection.mintToken(bob, targetToken.nestingAccount()))468 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);469 });470471 // ---------- Fungible ----------472473 itSub('Fungible: disallows to nest token if nesting is disabled', async ({helper}) => {474 const collectionNFT = await helper.nft.mintCollection(alice);475 const collectionFT = await helper.ft.mintCollection(alice);476 const targetToken = await collectionNFT.mintToken(alice);477478 // Try to create an immediately nested token479 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))480 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);481482 // Try to create a token to be nested and nest483 await collectionFT.mint(alice, 5n);484 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 2n))485 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);486 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);487 });488489 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token', async ({helper}) => {490 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});491 const collectionFT = await helper.ft.mintCollection(alice);492 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});493494 // Nest some tokens as Alice into Bob's token495 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());496497 // Try to pull it out498 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))499 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);500 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);501 });502503 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token (Restricted nesting)', async ({helper}) => {504 const collectionNFT = await helper.nft.mintCollection(alice);505 const collectionFT = await helper.ft.mintCollection(alice);506 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});507508 await collectionNFT.setPermissions(alice, {nesting: {collectionAdmin: true, tokenOwner: true, restricted: [collectionFT.collectionId]}});509510 // Nest some tokens as Alice into Bob's token511 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());512513 // Try to pull it out as Alice still514 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))515 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);516 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);517 });518519 itSub('Fungible: disallows to nest token in an unlisted collection', async ({helper}) => {520 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true, restricted: []}}});521 const collectionFT = await helper.ft.mintCollection(alice);522 const targetToken = await collectionNFT.mintToken(alice);523524 // Try to mint an immediately nested token525 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))526 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);527528 // Mint a token and try to nest it529 await collectionFT.mint(alice, 5n);530 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 1n))531 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);532533 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);534 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);535 });536});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';1920describe('Integration Test: Composite nesting tests', () => {21 let alice: IKeyringPair;22 let bob: IKeyringPair;2324 before(async () => {25 await usingPlaygrounds(async (helper, privateKey) => {26 const donor = await privateKey({filename: __filename});27 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);28 });29 });3031 itSub('Performs the full suite: bundles a token, transfers, and unnests', async ({helper}) => {32 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});33 const targetToken = await collection.mintToken(alice);3435 // Create an immediately nested token36 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());37 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});38 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());3940 // Create a token to be nested41 const newToken = await collection.mintToken(alice);4243 // Nest44 await newToken.nest(alice, targetToken);45 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});46 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());4748 // Move bundle to different user49 await targetToken.transfer(alice, {Substrate: bob.address});50 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});51 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());52 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});53 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());5455 // Unnest56 await newToken.unnest(bob, targetToken, {Substrate: bob.address});57 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});58 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});59 });6061 itSub('Transfers an already bundled token', async ({helper}) => {62 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});63 const tokenA = await collection.mintToken(alice);64 const tokenB = await collection.mintToken(alice);6566 // Create a nested token67 const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());68 expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());6970 // Transfer the nested token to another token71 await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;72 expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});73 expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());74 });7576 itSub('Checks token children', async ({helper}) => {77 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});78 const collectionB = await helper.ft.mintCollection(alice);7980 const targetToken = await collectionA.mintToken(alice);81 expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');8283 // Create a nested NFT token84 const tokenA = await collectionA.mintToken(alice, targetToken.nestingAccount());85 expect(await targetToken.getChildren()).to.have.deep.members([86 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},87 ], 'Children contents check at nesting #1').and.be.length(1, 'Children length check at nesting #1');8889 // Create then nest90 const tokenB = await collectionA.mintToken(alice);91 await tokenB.nest(alice, targetToken);92 expect(await targetToken.getChildren()).to.have.deep.members([93 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},94 {tokenId: tokenB.tokenId, collectionId: collectionA.collectionId},95 ], 'Children contents check at nesting #2').and.be.length(2, 'Children length check at nesting #2');9697 // Move token B to a different user outside the nesting tree98 await tokenB.unnest(alice, targetToken, {Substrate: bob.address});99 expect(await targetToken.getChildren()).to.be.have.deep.members([100 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},101 ], 'Children contents check at nesting #3 (unnesting)').and.be.length(1, 'Children length check at nesting #3 (unnesting)');102103 // Create a fungible token in another collection and then nest104 await collectionB.mint(alice, 10n);105 await collectionB.transfer(alice, targetToken.nestingAccount(), 2n);106 expect(await targetToken.getChildren()).to.be.have.deep.members([107 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},108 {tokenId: 0, collectionId: collectionB.collectionId},109 ], 'Children contents check at nesting #4 (from another collection)')110 .and.be.length(2, 'Children length check at nesting #4 (from another collection)');111112 // Move part of the fungible token inside token A deeper in the nesting tree113 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);114 expect(await targetToken.getChildren()).to.be.have.deep.members([115 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},116 {tokenId: 0, collectionId: collectionB.collectionId},117 ], 'Children contents check at nesting #5 (deeper)').and.be.length(2, 'Children length check at nesting #5 (deeper)');118 expect(await tokenA.getChildren()).to.be.have.deep.members([119 {tokenId: 0, collectionId: collectionB.collectionId},120 ], 'Children contents check at nesting #5.5 (deeper)').and.be.length(1, 'Children length check at nesting #5.5 (deeper)');121122 // Move the remaining part of the fungible token inside token A deeper in the nesting tree123 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);124 expect(await targetToken.getChildren()).to.be.have.deep.members([125 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},126 ], 'Children contents check at nesting #6 (deeper)').and.be.length(1, 'Children length check at nesting #6 (deeper)');127 expect(await tokenA.getChildren()).to.be.have.deep.members([128 {tokenId: 0, collectionId: collectionB.collectionId},129 ], 'Children contents check at nesting #6.5 (deeper)').and.be.length(1, 'Children length check at nesting #6.5 (deeper)');130 });131});132133describe('Integration Test: Various token type nesting', () => {134 let alice: IKeyringPair;135 let bob: IKeyringPair;136 let charlie: IKeyringPair;137138 before(async () => {139 await usingPlaygrounds(async (helper, privateKey) => {140 const donor = await privateKey({filename: __filename});141 [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 10n, 10n], donor);142 });143 });144145 itSub('Admin (NFT): allows an Admin to nest a token', async ({helper}) => {146 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true}}});147 await collection.addAdmin(alice, {Substrate: bob.address});148 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});149150 // Create an immediately nested token151 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());152 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});153 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());154155 // Create a token to be nested and nest156 const newToken = await collection.mintToken(bob);157 await newToken.nest(bob, targetToken);158 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});159 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());160 });161162 itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {163 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});164 await collection.addAdmin(alice, {Substrate: bob.address});165 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});166167 // Create an immediately nested token by an administrator168 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());169 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});170 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());171172 // Create a token to be nested and nest173 const newToken = await collection.mintToken(alice, {Substrate: charlie.address});174 await newToken.nest(charlie, targetToken);175 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});176 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());177 });178179 itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {180 const collectionA = await helper.nft.mintCollection(alice);181 await collectionA.addAdmin(alice, {Substrate: bob.address});182 const collectionB = await helper.nft.mintCollection(alice);183 await collectionB.addAdmin(alice, {Substrate: bob.address});184 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted:[collectionB.collectionId]}});185 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});186187 // Create an immediately nested token188 const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());189 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});190 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());191192 // Create a token to be nested and nest193 const newToken = await collectionB.mintToken(bob);194 await newToken.nest(bob, targetToken);195 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});196 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());197 });198199 // ---------- Non-Fungible ----------200201 itSub('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {202 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});203 await collection.addToAllowList(alice, {Substrate: charlie.address});204 const targetToken = await collection.mintToken(charlie);205 await collection.addToAllowList(alice, targetToken.nestingAccount());206207 // Create an immediately nested token208 const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());209 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});210 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());211212 // Create a token to be nested and nest213 const newToken = await collection.mintToken(charlie);214 await newToken.nest(charlie, targetToken);215 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});216 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());217 });218219 itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {220 const collectionA = await helper.nft.mintCollection(alice);221 const collectionB = await helper.nft.mintCollection(alice);222 //await collectionB.addAdmin(alice, {Substrate: bob.address});223 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});224225 await collectionA.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionB.collectionId]}});226 await collectionA.addToAllowList(alice, {Substrate: charlie.address});227 await collectionA.addToAllowList(alice, targetToken.nestingAccount());228229 await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});230 await collectionB.addToAllowList(alice, {Substrate: charlie.address});231 await collectionB.addToAllowList(alice, targetToken.nestingAccount());232233 // Create an immediately nested token234 const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());235 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});236 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());237238 // Create a token to be nested and nest239 const newToken = await collectionB.mintToken(charlie);240 await newToken.nest(charlie, targetToken);241 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});242 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());243 });244245 // ---------- Fungible ----------246247 itSub('Fungible: allows an Owner to nest/unnest their token', async ({helper}) => {248 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});249 const collectionFT = await helper.ft.mintCollection(alice);250 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});251252 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});253 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());254255 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});256 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});257 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());258259 // Create an immediately nested token260 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());261 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);262263 // Create a token to be nested and nest264 await collectionFT.mint(charlie, 5n);265 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);266 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);267 });268269 itSub('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {270 const collectionNFT = await helper.nft.mintCollection(alice);271 const collectionFT = await helper.ft.mintCollection(alice);272 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});273274 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionFT.collectionId]}});275 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});276 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());277278 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});279 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});280 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());281282 // Create an immediately nested token283 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());284 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);285286 // Create a token to be nested and nest287 await collectionFT.mint(charlie, 5n);288 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);289 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);290 });291292 itSub.ifWithPallets('ReFungible: getTopmostOwner works correctly with Nesting', [Pallets.ReFungible], async({helper}) => {293 const collectionNFT = await helper.nft.mintCollection(alice, {294 permissions: {295 nesting: {296 tokenOwner: true,297 },298 },299 });300 const collectionRFT = await helper.rft.mintCollection(alice);301302 const nft = await collectionNFT.mintToken(alice, {Substrate: alice.address});303 const rft = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});304305 expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});306307 await rft.transfer(alice, nft.nestingAccount(), 40n);308309 expect(await rft.getTopmostOwner()).deep.equal(null);310311 await rft.transfer(alice, nft.nestingAccount(), 60n);312313 expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});314315 await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 30n);316317 expect(await rft.getTopmostOwner()).deep.equal(null);318319 await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 70n);320321 expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});322 });323});324325describe('Negative Test: Nesting', () => {326 let alice: IKeyringPair;327 let bob: IKeyringPair;328329 before(async () => {330 await usingPlaygrounds(async (helper, privateKey) => {331 const donor = await privateKey({filename: __filename});332 [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);333 });334 });335336 itSub('Disallows excessive token nesting', async ({helper}) => {337 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});338 let token = await collection.mintToken(alice);339340 const maxNestingLevel = 5;341342 // Create a nested-token matryoshka343 for (let i = 0; i < maxNestingLevel; i++) {344 token = await collection.mintToken(alice, token.nestingAccount());345 }346347 // The nesting depth is limited by `maxNestingLevel`348 await expect(collection.mintToken(alice, token.nestingAccount()))349 .to.be.rejectedWith(/structure\.DepthLimit/);350 expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});351 expect(await token.getChildren()).to.be.length(0);352 });353354 // ---------- Admin ------------355356 itSub('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async ({helper}) => {357 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});358 await collection.addAdmin(alice, {Substrate: bob.address});359 const targetToken = await collection.mintToken(alice);360361 // Try to create an immediately nested token as collection admin when it's disallowed362 await expect(collection.mintToken(bob, targetToken.nestingAccount()))363 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);364365 // Try to create a token to be nested and nest366 const newToken = await collection.mintToken(bob);367 await expect(newToken.nest(bob, targetToken))368 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);369370 expect(await targetToken.getChildren()).to.be.length(0);371 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});372 });373374 itSub('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async ({helper}) => {375 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});376 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});377 await collection.addToAllowList(alice, {Substrate: bob.address});378 await collection.addToAllowList(alice, targetToken.nestingAccount());379380 // Try to create a nested token as token owner when it's disallowed381 await expect(collection.mintToken(bob, targetToken.nestingAccount()))382 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);383384 // Try to create a token to be nested and nest385 const newToken = await collection.mintToken(bob);386 await expect(newToken.nest(bob, targetToken))387 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);388389 expect(await targetToken.getChildren()).to.be.length(0);390 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});391 });392393 itSub('Admin (NFT): disallows an Admin to unnest someone else\'s token', async ({helper}) => {394 const collection = await helper.nft.mintCollection(alice, {limits: {ownerCanTransfer: true}, permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});395 //await collection.addAdmin(alice, {Substrate: bob.address});396 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});397 await collection.addToAllowList(alice, {Substrate: bob.address});398 await collection.addToAllowList(alice, targetToken.nestingAccount());399400 // Try to nest somebody else's token401 const newToken = await collection.mintToken(bob);402 await expect(newToken.nest(alice, targetToken))403 .to.be.rejectedWith(/common\.NoPermission/);404405 // Try to unnest a token belonging to someone else as collection admin406 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());407 await expect(nestedToken.unnest(alice, targetToken, {Substrate: bob.address}))408 .to.be.rejectedWith(/common\.AddressNotInAllowlist/);409410 expect(await targetToken.getChildren()).to.be.length(1);411 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});412 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());413 });414415 itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {416 const collectionA = await helper.nft.mintCollection(alice);417 const collectionB = await helper.nft.mintCollection(alice);418 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted: [collectionA.collectionId]}});419 const targetToken = await collectionA.mintToken(alice);420421 // Try to create a nested token from another collection422 await expect(collectionB.mintToken(alice, targetToken.nestingAccount()))423 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);424425 // Create a token in another collection yet to be nested and try to nest426 const newToken = await collectionB.mintToken(alice);427 await expect(newToken.nest(alice, targetToken))428 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);429430 expect(await targetToken.getChildren()).to.be.length(0);431 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});432 });433434 // ---------- Non-Fungible ----------435436 itSub('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {437 // Collection is implicitly not allowed nesting at creation438 const collection = await helper.nft.mintCollection(alice);439 const targetToken = await collection.mintToken(alice);440441 // Try to create a nested token as token owner when it's disallowed442 await expect(collection.mintToken(alice, targetToken.nestingAccount()))443 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);444445 // Try to create a token to be nested and nest446 const newToken = await collection.mintToken(alice);447 await expect(newToken.nest(alice, targetToken))448 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);449450 expect(await targetToken.getChildren()).to.be.length(0);451 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});452 });453454 itSub('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {455 const collection = await helper.nft.mintCollection(alice);456 const targetToken = await collection.mintToken(alice);457458 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});459 await collection.addToAllowList(alice, {Substrate: bob.address});460 await collection.addToAllowList(alice, targetToken.nestingAccount());461462 // Try to create a token to be nested and nest463 const newToken = await collection.mintToken(alice);464 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);465466 expect(await targetToken.getChildren()).to.be.length(0);467 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});468 });469470 itSub('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {471 const collection = await helper.nft.mintCollection(alice);472 const targetToken = await collection.mintToken(alice);473474 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});475 await collection.addToAllowList(alice, {Substrate: bob.address});476 await collection.addToAllowList(alice, targetToken.nestingAccount());477478 const collectionB = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true}});479 await collectionB.addToAllowList(alice, {Substrate: bob.address});480 await collectionB.addToAllowList(alice, targetToken.nestingAccount());481482 // Try to create a token to be nested and nest483 const newToken = await collectionB.mintToken(alice);484 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);485486 expect(await targetToken.getChildren()).to.be.length(0);487 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});488 });489490 itSub('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {491 // Create collection with restricted nesting -- even self is not allowed492 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: []}}});493 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});494495 await collection.addToAllowList(alice, {Substrate: bob.address});496 await collection.addToAllowList(alice, targetToken.nestingAccount());497498 // Try to mint in own collection after allowlisting the accounts499 await expect(collection.mintToken(bob, targetToken.nestingAccount()))500 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);501 });502503 // ---------- Fungible ----------504505 itSub('Fungible: disallows to nest token if nesting is disabled', async ({helper}) => {506 const collectionNFT = await helper.nft.mintCollection(alice);507 const collectionFT = await helper.ft.mintCollection(alice);508 const targetToken = await collectionNFT.mintToken(alice);509510 // Try to create an immediately nested token511 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))512 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);513514 // Try to create a token to be nested and nest515 await collectionFT.mint(alice, 5n);516 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 2n))517 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);518 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);519 });520521 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token', async ({helper}) => {522 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});523 const collectionFT = await helper.ft.mintCollection(alice);524 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});525526 // Nest some tokens as Alice into Bob's token527 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());528529 // Try to pull it out530 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))531 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);532 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);533 });534535 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token (Restricted nesting)', async ({helper}) => {536 const collectionNFT = await helper.nft.mintCollection(alice);537 const collectionFT = await helper.ft.mintCollection(alice);538 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});539540 await collectionNFT.setPermissions(alice, {nesting: {collectionAdmin: true, tokenOwner: true, restricted: [collectionFT.collectionId]}});541542 // Nest some tokens as Alice into Bob's token543 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());544545 // Try to pull it out as Alice still546 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))547 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);548 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);549 });550551 itSub('Fungible: disallows to nest token in an unlisted collection', async ({helper}) => {552 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true, restricted: []}}});553 const collectionFT = await helper.ft.mintCollection(alice);554 const targetToken = await collectionNFT.mintToken(alice);555556 // Try to mint an immediately nested token557 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))558 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);559560 // Mint a token and try to nest it561 await collectionFT.mint(alice, 5n);562 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 1n))563 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);564565 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);566 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);567 });568});