difftreelog
Merge pull request #607 from UniqueNetwork/tests/nesting
in: master
11 files changed
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -12,7 +12,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import { requirePalletsOrSkip } from '../../../util/playgrounds';
+import {requirePalletsOrSkip} from '../../../util/playgrounds';
chai.use(chaiAsPromised);
export const expect = chai.expect;
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -240,7 +240,7 @@
}
fromTokenId(collectionId: number, tokenId: number): string {
- return this.helper.util.getNestingTokenAddress(collectionId, tokenId);
+ return this.helper.util.getTokenAddress({collectionId, tokenId});
}
normalizeAddress(address: string): string {
tests/src/nesting/graphs.test.tsdiffbeforeafterboth--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -1,9 +1,22 @@
-import {ApiPromise} from '@polkadot/api';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-import {tokenIdToCross} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {getCreateCollectionResult, transferExpectSuccess, setCollectionLimitsExpectSuccess} from '../util/helpers';
+import {expect, itSub, usingPlaygrounds} from '../util/playgrounds';
+import {UniqueHelper, UniqueNFToken} from '../util/playgrounds/unique';
/**
* ```dot
@@ -12,46 +25,47 @@
* 8 -> 5
* ```
*/
-async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {
- const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT', permissions: {nesting: {tokenOwner: true}}}));
- const {collectionId} = getCreateCollectionResult(events);
+async function buildComplexObjectGraph(helper: UniqueHelper, sender: IKeyringPair): Promise<UniqueNFToken[]> {
+ const collection = await helper.nft.mintCollection(sender, {permissions: {nesting: {tokenOwner: true}}});
+ const tokens = await collection.mintMultipleTokens(sender, Array(8).fill({owner: {Substrate: sender.address}}));
- await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));
-
- await transferExpectSuccess(collectionId, 8, sender, tokenIdToCross(collectionId, 5));
-
- await transferExpectSuccess(collectionId, 7, sender, tokenIdToCross(collectionId, 6));
- await transferExpectSuccess(collectionId, 6, sender, tokenIdToCross(collectionId, 5));
- await transferExpectSuccess(collectionId, 5, sender, tokenIdToCross(collectionId, 2));
+ await tokens[7].nest(sender, tokens[4]);
+ await tokens[6].nest(sender, tokens[5]);
+ await tokens[5].nest(sender, tokens[4]);
+ await tokens[4].nest(sender, tokens[1]);
+ await tokens[3].nest(sender, tokens[2]);
+ await tokens[2].nest(sender, tokens[1]);
+ await tokens[1].nest(sender, tokens[0]);
- await transferExpectSuccess(collectionId, 4, sender, tokenIdToCross(collectionId, 3));
- await transferExpectSuccess(collectionId, 3, sender, tokenIdToCross(collectionId, 2));
- await transferExpectSuccess(collectionId, 2, sender, tokenIdToCross(collectionId, 1));
-
- return collectionId;
+ return tokens;
}
describe('Graphs', () => {
- it('Ouroboros can\'t be created in a complex graph', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const collection = await buildComplexObjectGraph(api, alice);
- const tokenTwoParent = tokenIdToCross(collection, 1);
+ let alice: IKeyringPair;
- // to self
- await expect(
- executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)),
- 'first transaction',
- ).to.be.rejectedWith(/structure\.OuroborosDetected/);
- // to nested part of graph
- await expect(
- executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)),
- 'second transaction',
- ).to.be.rejectedWith(/structure\.OuroborosDetected/);
- await expect(
- executeTransaction(api, alice, api.tx.unique.transferFrom(tokenTwoParent, tokenIdToCross(collection, 8), collection, 2, 1)),
- 'third transaction',
- ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice] = await helper.arrange.createAccounts([10n], donor);
});
});
+
+ itSub('Ouroboros can\'t be created in a complex graph', async ({helper}) => {
+ const tokens = await buildComplexObjectGraph(helper, alice);
+
+ // to self
+ await expect(
+ tokens[0].nest(alice, tokens[0]),
+ 'first transaction',
+ ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+ // to nested part of graph
+ await expect(
+ tokens[0].nest(alice, tokens[4]),
+ 'second transaction',
+ ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+ await expect(
+ tokens[1].transferFrom(alice, tokens[0].nestingAccount(), tokens[7].nestingAccount()),
+ 'third transaction',
+ ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+ });
});
tests/src/nesting/migration-check.test.tsdiffbeforeafterboth--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -8,7 +8,8 @@
import find from 'find-process';
// todo un-skip for migrations
-describe.skip('Migration testing', () => {
+// todo:playgrounds skipped, this one is outdated. Probably to be deleted/replaced.
+describe.skip('Migration testing: Properties', () => {
let alice: IKeyringPair;
before(async() => {
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -1,840 +1,667 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
- addCollectionAdminExpectSuccess,
- addToAllowListExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- enableAllowListExpectSuccess,
- enablePublicMintingExpectSuccess,
- getTokenChildren,
- getTokenOwner,
- getTopmostTokenOwner,
- normalizeAccountId,
- setCollectionPermissionsExpectSuccess,
- transferExpectFailure,
- transferExpectSuccess,
- transferFromExpectSuccess,
- setCollectionLimitsExpectSuccess,
- requirePallets,
- Pallets,
-} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';
+
describe('Integration Test: Composite nesting tests', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (_, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
});
});
- it('Performs the full suite: bundles a token, transfers, and unnests', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('Performs the full suite: bundles a token, transfers, and unnests', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Create an immediately nested token
+ const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
+
+ // Create a token to be nested
+ const newToken = await collection.mintToken(alice);
- // Create a token to be nested
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
- // Nest
- await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Nest
+ await newToken.nest(alice, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Move bundle to different user
- await transferExpectSuccess(collection, targetToken, alice, {Substrate: bob.address});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Move bundle to different user
+ await targetToken.transfer(alice, {Substrate: bob.address});
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Unnest
- await transferFromExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)}, {Substrate: bob.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
- });
+ // Unnest
+ await newToken.unnest(bob, targetToken, {Substrate: bob.address});
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
-
- it('Transfers an already bundled token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');
- const tokenB = await createItemExpectSuccess(alice, collection, 'NFT');
-
- // Create a nested token
- const tokenC = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});
- expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenA).toLowerCase()});
+ itSub('Transfers an already bundled token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const tokenA = await collection.mintToken(alice);
+ const tokenB = await collection.mintToken(alice);
- // Transfer the nested token to another token
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.transferFrom(
- normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}),
- normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}),
- collection,
- tokenC,
- 1,
- ),
- )).to.not.be.rejected;
- expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenB).toLowerCase()});
- });
+ // Create a nested token
+ const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());
+ expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccountInLowerCase());
+
+ // Transfer the nested token to another token
+ await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;
+ expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+ expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccountInLowerCase());
});
- it('Checks token children', async () => {
- await usingApi(async api => {
- const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionLimitsExpectSuccess(alice, collectionA, {ownerCanTransfer: true});
- await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {tokenOwner: true}});
- const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ itSub('Checks token children', async ({helper}) => {
+ const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const collectionB = await helper.ft.mintCollection(alice);
+
+ const targetToken = await collectionA.mintToken(alice);
+ expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');
- const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};
- let children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(0, 'Children length check at creation');
+ // Create a nested NFT token
+ const tokenA = await collectionA.mintToken(alice, targetToken.nestingAccount());
+ expect(await targetToken.getChildren()).to.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ ], 'Children contents check at nesting #1').and.be.length(1, 'Children length check at nesting #1');
- // Create a nested NFT token
- const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);
- children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(1, 'Children length check at nesting #1');
- expect(children).to.have.deep.members([
- {token: tokenA, collection: collectionA},
- ], 'Children contents check at nesting #1');
+ // Create then nest
+ const tokenB = await collectionA.mintToken(alice);
+ await tokenB.nest(alice, targetToken);
+ expect(await targetToken.getChildren()).to.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ {tokenId: tokenB.tokenId, collectionId: collectionA.collectionId},
+ ], 'Children contents check at nesting #2').and.be.length(2, 'Children length check at nesting #2');
- // Create then nest
- const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');
- await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);
- children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(2, 'Children length check at nesting #2');
- expect(children).to.have.deep.members([
- {token: tokenA, collection: collectionA},
- {token: tokenB, collection: collectionA},
- ], 'Children contents check at nesting #2');
+ // Move token B to a different user outside the nesting tree
+ await tokenB.unnest(alice, targetToken, {Substrate: bob.address});
+ expect(await targetToken.getChildren()).to.be.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ ], 'Children contents check at nesting #3 (unnesting)').and.be.length(1, 'Children length check at nesting #3 (unnesting)');
- // Move token B to a different user outside the nesting tree
- await transferFromExpectSuccess(collectionA, tokenB, alice, targetAddress, bob);
- children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(1, 'Children length check at unnesting');
- expect(children).to.be.have.deep.members([
- {token: tokenA, collection: collectionA},
- ], 'Children contents check at unnesting');
+ // Create a fungible token in another collection and then nest
+ await collectionB.mint(alice, 10n);
+ await collectionB.transfer(alice, targetToken.nestingAccount(), 2n);
+ expect(await targetToken.getChildren()).to.be.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ {tokenId: 0, collectionId: collectionB.collectionId},
+ ], 'Children contents check at nesting #4 (from another collection)')
+ .and.be.length(2, 'Children length check at nesting #4 (from another collection)');
+
+ // Move part of the fungible token inside token A deeper in the nesting tree
+ await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);
+ expect(await targetToken.getChildren()).to.be.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ {tokenId: 0, collectionId: collectionB.collectionId},
+ ], 'Children contents check at nesting #5 (deeper)').and.be.length(2, 'Children length check at nesting #5 (deeper)');
+ expect(await tokenA.getChildren()).to.be.have.deep.members([
+ {tokenId: 0, collectionId: collectionB.collectionId},
+ ], 'Children contents check at nesting #5.5 (deeper)').and.be.length(1, 'Children length check at nesting #5.5 (deeper)');
- // Create a fungible token in another collection and then nest
- const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');
- await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');
- children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');
- expect(children).to.be.have.deep.members([
- {token: tokenA, collection: collectionA},
- {token: tokenC, collection: collectionB},
- ], 'Children contents check at nesting #3 (from another collection)');
-
- // Move the fungible token inside token A deeper in the nesting tree
- await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');
- children = await getTokenChildren(api, collectionA, targetToken);
- expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');
- expect(children).to.be.have.deep.members([
- {token: tokenA, collection: collectionA},
- ], 'Children contents check at deeper nesting');
- });
+ // Move the remaining part of the fungible token inside token A deeper in the nesting tree
+ await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);
+ expect(await targetToken.getChildren()).to.be.have.deep.members([
+ {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+ ], 'Children contents check at nesting #6 (deeper)').and.be.length(1, 'Children length check at nesting #6 (deeper)');
+ expect(await tokenA.getChildren()).to.be.have.deep.members([
+ {tokenId: 0, collectionId: collectionB.collectionId},
+ ], 'Children contents check at nesting #6.5 (deeper)').and.be.length(1, 'Children length check at nesting #6.5 (deeper)');
});
});
-describe('Integration Test: Various token type nesting', async () => {
+describe('Integration Test: Various token type nesting', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
before(async () => {
- await usingApi(async (_, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- charlie = privateKeyWrapper('//Charlie');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);
});
});
- it('Admin (NFT): allows an Admin to nest a token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
- await addCollectionAdminExpectSuccess(alice, collection, bob.address);
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
+ itSub('Admin (NFT): allows an Admin to nest a token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true}}});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Create an immediately nested token
+ const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Create a token to be nested and nest
- const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
- await transferExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
- });
+ // Create a token to be nested and nest
+ const newToken = await collection.mintToken(bob);
+ await newToken.nest(bob, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
- it('Admin (NFT): Admin and Token Owner can operate together', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, collectionAdmin: true}});
- await addCollectionAdminExpectSuccess(alice, collection, bob.address);
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
+ itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});
- // Create a nested token by an administrator
- const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Create an immediately nested token by an administrator
+ const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Create a token and allow the owner to nest too
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
- await transferExpectSuccess(collection, newToken, charlie, {Ethereum: tokenIdToAddress(collection, nestedToken)});
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, nestedToken).toLowerCase()});
- });
+ // Create a token to be nested and nest
+ const newToken = await collection.mintToken(alice, {Substrate: charlie.address});
+ await newToken.nest(charlie, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
- it('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addCollectionAdminExpectSuccess(alice, collectionA, bob.address);
- const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addCollectionAdminExpectSuccess(alice, collectionB, bob.address);
- await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA, collectionB]}});
- const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT', charlie.address);
+ itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {
+ const collectionA = await helper.nft.mintCollection(alice);
+ await collectionA.addAdmin(alice, {Substrate: bob.address});
+ const collectionB = await helper.nft.mintCollection(alice);
+ await collectionB.addAdmin(alice, {Substrate: bob.address});
+ await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted:[collectionB.collectionId]}});
+ const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(bob, collectionB, 'NFT', {Ethereum: tokenIdToAddress(collectionA, targetToken)});
- expect(await getTopmostTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});
+ // Create an immediately nested token
+ const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Create a token to be nested and nest
- const newToken = await createItemExpectSuccess(bob, collectionB, 'NFT');
- await transferExpectSuccess(collectionB, newToken, bob, {Ethereum: tokenIdToAddress(collectionA, targetToken)});
- expect(await getTopmostTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: charlie.address});
- expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});
- });
+ // Create a token to be nested and nest
+ const newToken = await collectionB.mintToken(bob);
+ await newToken.nest(bob, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
// ---------- Non-Fungible ----------
- it('NFT: allows an Owner to nest/unnest their token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+ await collection.addToAllowList(alice, {Substrate: charlie.address});
+ const targetToken = await collection.mintToken(charlie);
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Create an immediately nested token
+ const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Create a token to be nested and nest
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
- });
+ // Create a token to be nested and nest
+ const newToken = await collection.mintToken(charlie);
+ await newToken.nest(charlie, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
- it('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
+ const collectionA = await helper.nft.mintCollection(alice);
+ const collectionB = await helper.nft.mintCollection(alice);
+ //await collectionB.addAdmin(alice, {Substrate: bob.address});
+ const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ await collectionA.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionB.collectionId]}});
+ await collectionA.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionA.addToAllowList(alice, targetToken.nestingAccount());
+
+ await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collectionB.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionB.addToAllowList(alice, targetToken.nestingAccount());
- // Create a token to be nested and nest
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
- });
+ // Create an immediately nested token
+ const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
+
+ // Create a token to be nested and nest
+ const newToken = await collectionB.mintToken(charlie);
+ await newToken.nest(charlie, targetToken);
+ expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+ expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
// ---------- Fungible ----------
- it('Fungible: allows an Owner to nest/unnest their token', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ itSub('Fungible: allows an Owner to nest/unnest their token', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- // Create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- ))).to.not.be.rejected;
+ await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collectionFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionFT.addToAllowList(alice, targetToken.nestingAccount());
- // Nest a new token
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
- });
+ // Create an immediately nested token
+ await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
+
+ // Create a token to be nested and nest
+ await collectionFT.mint(charlie, 5n);
+ await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
});
- it('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ itSub('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionFT.collectionId]}});
+ await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted: [collectionFT]}});
+ await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collectionFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionFT.addToAllowList(alice, targetToken.nestingAccount());
- // Create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- ))).to.not.be.rejected;
+ // Create an immediately nested token
+ await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
- // Nest a new token
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
- });
+ // Create a token to be nested and nest
+ await collectionFT.mint(charlie, 5n);
+ await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
});
// ---------- Re-Fungible ----------
- it('ReFungible: allows an Owner to nest/unnest their token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
- // Create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- ))).to.not.be.rejected;
+ // Create an immediately nested token
+ const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
+ expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
- // Nest a new token
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
- });
+ // Create a token to be nested and nest
+ const newToken = await collectionRFT.mintToken(charlie, 5n);
+ await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
+ expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
});
- it('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionRFT.collectionId]}});
+ await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
+ await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});
+ // Create an immediately nested token
+ const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
+ expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
- // Create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- ))).to.not.be.rejected;
-
- // Nest a new token
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
- });
+ // Create a token to be nested and nest
+ const newToken = await collectionRFT.mintToken(charlie, 5n);
+ await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
+ expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
});
});
-describe('Negative Test: Nesting', async() => {
+describe('Negative Test: Nesting', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (_, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);
});
});
- it('Disallows excessive token nesting', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
- const maxNestingLevel = 5;
- let prevToken = targetToken;
+ itSub('Disallows excessive token nesting', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ let token = await collection.mintToken(alice);
- // Create a nested-token matryoshka
- for (let i = 0; i < maxNestingLevel; i++) {
- const nestedToken = await createItemExpectSuccess(
- alice,
- collection,
- 'NFT',
- {Ethereum: tokenIdToAddress(collection, prevToken)},
- );
+ const maxNestingLevel = 5;
- prevToken = nestedToken;
- }
-
- // The nesting depth is limited by `maxNestingLevel`
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, prevToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
+ // Create a nested-token matryoshka
+ for (let i = 0; i < maxNestingLevel; i++) {
+ token = await collection.mintToken(alice, token.nestingAccount());
+ }
- expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ // The nesting depth is limited by `maxNestingLevel`
+ await expect(collection.mintToken(alice, token.nestingAccount()))
+ .to.be.rejectedWith(/structure\.DepthLimit/);
+ expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+ expect(await token.getChildren()).to.be.length(0);
});
// ---------- Admin ------------
- it('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- await addCollectionAdminExpectSuccess(alice, collection, bob.address);
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ const targetToken = await collection.mintToken(alice);
- // Try to create a nested token as collection admin when it's disallowed
- await expect(executeTransaction(api, bob, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Try to create an immediately nested token as collection admin when it's disallowed
+ await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
- await expect(executeTransaction(
- api,
- bob,
- api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),
- ), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
- });
+ // Try to create a token to be nested and nest
+ const newToken = await collection.mintToken(bob);
+ await expect(newToken.nest(bob, targetToken))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- it('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
- await addToAllowListExpectSuccess(alice, collection, bob.address);
- await enableAllowListExpectSuccess(alice, collection);
- await enablePublicMintingExpectSuccess(alice, collection);
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});
+ const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
+
+ // Try to create a nested token as token owner when it's disallowed
+ await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Try to create a nested token as collection admin when it's disallowed
- await expect(executeTransaction(api, bob, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
+ // Try to create a token to be nested and nest
+ const newToken = await collection.mintToken(bob);
+ await expect(newToken.nest(bob, targetToken))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
- await expect(executeTransaction(
- api,
- bob,
- api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),
- ), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
- });
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- it('Admin (NFT): disallows an Admin to nest and unnest someone else\'s token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionLimitsExpectSuccess(alice, collection, {ownerCanTransfer: true});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
+ itSub('Admin (NFT): disallows an Admin to unnest someone else\'s token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {limits: {ownerCanTransfer: true}, permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});
+ //await collection.addAdmin(alice, {Substrate: bob.address});
+ const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
- await addToAllowListExpectSuccess(alice, collection, bob.address);
- await enableAllowListExpectSuccess(alice, collection);
- await enablePublicMintingExpectSuccess(alice, collection);
-
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()};
+ // Try to nest somebody else's token
+ const newToken = await collection.mintToken(bob);
+ await expect(newToken.nest(alice, targetToken))
+ .to.be.rejectedWith(/common\.NoPermission/);
- // Try to nest somebody else's token
- const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.transferFrom(targetAddress, {Substrate: bob.address}, collection, newToken, 1),
- ), 'while nesting another\'s token token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
+ // Try to unnest a token belonging to someone else as collection admin
+ const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+ await expect(nestedToken.unnest(alice, targetToken, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- // Nest a token as admin and try to unnest it, now belonging to someone else
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.transferFrom(targetAddress, normalizeAccountId(alice), collection, nestedToken, 1),
- ), 'while unnesting another\'s token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal(targetAddress);
- expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});
- });
+ expect(await targetToken.getChildren()).to.be.length(1);
+ expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
- it('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA]}});
+ itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {
+ const collectionA = await helper.nft.mintCollection(alice);
+ const collectionB = await helper.nft.mintCollection(alice);
+ await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted: [collectionA.collectionId]}});
+ const targetToken = await collectionA.mintToken(alice);
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
+ // Try to create a nested token from another collection
+ await expect(collectionB.mintToken(alice, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionB, 'NFT');
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionA, targetToken)}, collectionB, newToken, 1),
- ), 'while nesting a foreign token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ // Create a token in another collection yet to be nested and try to nest
+ const newToken = await collectionB.mintToken(alice);
+ await expect(newToken.nest(alice, targetToken))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
// ---------- Non-Fungible ----------
- it('NFT: disallows to nest token if nesting is disabled', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
+ // Collection is implicitly not allowed nesting at creation
+ const collection = await helper.nft.mintCollection(alice);
+ const targetToken = await collection.mintToken(alice);
- // Try to create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+ // Try to create a nested token as token owner when it's disallowed
+ await expect(collection.mintToken(alice, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Create a token to be nested
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- // Try to nest
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ // Try to create a token to be nested and nest
+ const newToken = await collection.mintToken(alice);
+ await expect(newToken.nest(alice, targetToken))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('NFT: disallows a non-Owner to nest someone else\'s token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+ itSub('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice);
+ const targetToken = await collection.mintToken(alice);
- await addToAllowListExpectSuccess(alice, collection, bob.address);
- await enableAllowListExpectSuccess(alice, collection);
- await enablePublicMintingExpectSuccess(alice, collection);
-
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Try to create a token to be nested and nest
+ const newToken = await collection.mintToken(alice);
+ await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});
+ itSub('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice);
+ const targetToken = await collection.mintToken(alice);
- await addToAllowListExpectSuccess(alice, collection, bob.address);
- await enableAllowListExpectSuccess(alice, collection);
- await enablePublicMintingExpectSuccess(alice, collection);
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
+ const collectionB = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true}});
+ await collectionB.addToAllowList(alice, {Substrate: bob.address});
+ await collectionB.addToAllowList(alice, targetToken.nestingAccount());
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Try to create a token to be nested and nest
+ const newToken = await collectionB.mintToken(alice);
+ await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('NFT: disallows to nest token in an unlisted collection', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[]}});
+ itSub('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
+ // Create collection with restricted nesting -- even self is not allowed
+ const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: []}}});
+ const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, targetToken.nestingAccount());
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
- {nft: {}} as any,
- )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
- });
+ // Try to mint in own collection after allowlisting the accounts
+ await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
});
// ---------- Fungible ----------
-
- it('Fungible: disallows to nest token if nesting is disabled', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- // Try to create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+ itSub('Fungible: disallows to nest token if nesting is disabled', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- // Create a token to be nested
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- // Try to nest
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Try to create an immediately nested token
+ await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Create another token to be nested
- const newToken2 = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- // Try to nest inside a fungible token
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionFT, newToken)}, collectionFT, newToken2, 1)), 'while nesting new token inside fungible').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
- });
+ // Try to create a token to be nested and nest
+ await collectionFT.mint(alice, 5n);
+ await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 2n))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);
});
- it('Fungible: disallows a non-Owner to nest someone else\'s token', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
+ itSub('Fungible: disallows a non-Owner to unnest someone else\'s token', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});
- await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
- await enableAllowListExpectSuccess(alice, collectionNFT);
- await enablePublicMintingExpectSuccess(alice, collectionNFT);
+ // Nest some tokens as Alice into Bob's token
+ await collectionFT.mint(alice, 5n, targetToken.nestingAccount());
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- });
+ // Try to pull it out
+ await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
});
- it('Fungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
- await enableAllowListExpectSuccess(alice, collectionNFT);
- await enablePublicMintingExpectSuccess(alice, collectionNFT);
-
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ itSub('Fungible: disallows a non-Owner to unnest someone else\'s token (Restricted nesting)', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionFT]}});
+ await collectionNFT.setPermissions(alice, {nesting: {collectionAdmin: true, tokenOwner: true, restricted: [collectionFT.collectionId]}});
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Nest some tokens as Alice into Bob's token
+ await collectionFT.mint(alice, 5n, targetToken.nestingAccount());
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- });
+ // Try to pull it out as Alice still
+ await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
});
- it('Fungible: disallows to nest token in an unlisted collection', async () => {
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});
-
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ itSub('Fungible: disallows to nest token in an unlisted collection', async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true, restricted: []}}});
+ const collectionFT = await helper.ft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ // Try to mint an immediately nested token
+ await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
- {Fungible: {Value: 10}},
- )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+ // Mint a token and try to nest it
+ await collectionFT.mint(alice, 5n);
+ await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 1n))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- });
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+ expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);
});
// ---------- Re-Fungible ----------
-
- it('ReFungible: disallows to nest token if nesting is disabled', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-
- // Create a nested token
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- )), 'while creating a nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+ itSub.ifWithPallets('ReFungible: disallows to nest token if nesting is disabled', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- // Create a token to be nested
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- // Try to nest
- await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
- // Try to nest
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Try to create an immediately nested token
+ await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- // Create another token to be nested
- const newToken2 = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- // Try to nest inside a fungible token
- await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionRFT, newToken)}, collectionRFT, newToken2, 1)), 'while nesting new token inside refungible').to.be.rejectedWith(/refungible\.RefungibleDisallowsNesting/);
- });
+ // Try to create a token to be nested and nest
+ const token = await collectionRFT.mintToken(alice, 5n);
+ await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+ .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
});
-
- it('ReFungible: disallows a non-Owner to nest someone else\'s token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
+ itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
- await enableAllowListExpectSuccess(alice, collectionNFT);
- await enablePublicMintingExpectSuccess(alice, collectionNFT);
+ await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+ await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ // Try to create a token to be nested and nest
+ const newToken = await collectionRFT.mintToken(alice);
+ await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Nest some tokens as Alice into Bob's token
+ await newToken.transfer(alice, targetToken.nestingAccount());
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- });
+ // Try to pull it out
+ await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
});
- it('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice);
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
- await enableAllowListExpectSuccess(alice, collectionNFT);
- await enablePublicMintingExpectSuccess(alice, collectionNFT);
+ await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: [collectionRFT.collectionId]}});
+ await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
+ await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+ // Try to create a token to be nested and nest
+ const newToken = await collectionRFT.mintToken(alice);
+ await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});
+ expect(await targetToken.getChildren()).to.be.length(0);
+ expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+ // Nest some tokens as Alice into Bob's token
+ await newToken.transfer(alice, targetToken.nestingAccount());
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
- });
+ // Try to pull it out
+ await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
});
- it('ReFungible: disallows to nest token to an unlisted collection', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('ReFungible: disallows to nest token to an unlisted collection', [Pallets.ReFungible], async ({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true, restricted: []}}});
+ const collectionRFT = await helper.rft.mintCollection(alice);
+ const targetToken = await collectionNFT.mintToken(alice);
- await usingApi(async api => {
- const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});
+ // Try to create an immediately nested token
+ await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- // Create a token to attempt to be nested into
- const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-
- // Try to create a nested token in the wrong collection
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
- {ReFungible: {pieces: 100}},
- )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-
- // Try to create and nest a token in the wrong collection
- const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- });
+ // Try to create a token to be nested and nest
+ const token = await collectionRFT.mintToken(alice, 5n);
+ await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+ .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
});
});
tests/src/nesting/properties.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 {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../util/playgrounds';19import {UniqueHelper, UniqueBaseCollection, UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection, UniqueRFToken} from '../util/playgrounds/unique';2021// ---------- COLLECTION PROPERTIES2223describe('Integration Test: Collection Properties', () => {24 let alice: IKeyringPair;25 let bob: IKeyringPair;2627 before(async () => {28 await usingPlaygrounds(async (helper, privateKey) => {29 const donor = privateKey('//Alice');30 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);31 });32 });3334 itSub('Properties are initially empty', async ({helper}) => {35 const collection = await helper.nft.mintCollection(alice);36 expect(await collection.getProperties()).to.be.empty;37 });3839 async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {40 // As owner41 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;4243 await collection.addAdmin(alice, {Substrate: bob.address});4445 // As administrator46 await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;4748 const properties = await collection.getProperties();49 expect(properties).to.include.deep.members([50 {key: 'electron', value: 'come bond'},51 {key: 'black_hole', value: ''},52 ]);53 }5455 itSub('Sets properties for a NFT collection', async ({helper}) => {56 await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));57 });5859 itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {60 await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));61 });6263 async function testCheckValidNames(collection: UniqueBaseCollection) {64 // alpha symbols65 await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;6667 // numeric symbols68 await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;6970 // underscore symbol71 await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;7273 // dash symbol74 await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;7576 // dot symbol77 await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;7879 const properties = await collection.getProperties();80 expect(properties).to.include.deep.members([81 {key: 'answer', value: ''},82 {key: '451', value: ''},83 {key: 'black_hole', value: ''},84 {key: '-', value: ''},85 {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},86 ]);87 }8889 itSub('Check valid names for NFT collection properties keys', async ({helper}) => {90 await testCheckValidNames(await helper.nft.mintCollection(alice));91 });9293 itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {94 await testCheckValidNames(await helper.rft.mintCollection(alice));95 });9697 async function testChangesProperties(collection: UniqueBaseCollection) {98 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;99100 // Mutate the properties101 await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;102103 const properties = await collection.getProperties();104 expect(properties).to.include.deep.members([105 {key: 'electron', value: 'come bond'},106 {key: 'black_hole', value: 'LIGO'},107 ]);108 }109110 itSub('Changes properties of a NFT collection', async ({helper}) => {111 await testChangesProperties(await helper.nft.mintCollection(alice));112 });113114 itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {115 await testChangesProperties(await helper.rft.mintCollection(alice));116 });117118 async function testDeleteProperties(collection: UniqueBaseCollection) {119 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;120121 await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;122123 const properties = await collection.getProperties(['black_hole', 'electron']);124 expect(properties).to.be.deep.equal([125 {key: 'black_hole', value: 'LIGO'},126 ]);127 }128129 itSub('Deletes properties of a NFT collection', async ({helper}) => {130 await testDeleteProperties(await helper.nft.mintCollection(alice));131 });132133 itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {134 await testDeleteProperties(await helper.rft.mintCollection(alice));135 });136});137138describe('Negative Integration Test: Collection Properties', () => {139 let alice: IKeyringPair;140 let bob: IKeyringPair;141142 before(async () => {143 await usingPlaygrounds(async (helper, privateKey) => {144 const donor = privateKey('//Alice');145 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);146 });147 });148 149 async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) { 150 await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))151 .to.be.rejectedWith(/common\.NoPermission/);152153 expect(await collection.getProperties()).to.be.empty;154 }155156 itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {157 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));158 });159160 itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {161 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));162 });163 164 async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {165 const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();166 167 // Mute the general tx parsing error, too many bytes to process168 {169 console.error = () => {};170 await expect(collection.setProperties(alice, [171 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},172 ])).to.be.rejected;173 }174175 expect(await collection.getProperties(['electron'])).to.be.empty;176177 await expect(collection.setProperties(alice, [178 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 179 {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 180 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);181182 expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;183 }184185 itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {186 await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));187 });188189 itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {190 await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));191 });192 193 async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {194 const propertiesToBeSet = [];195 for (let i = 0; i < 65; i++) {196 propertiesToBeSet.push({197 key: 'electron_' + i,198 value: Math.random() > 0.5 ? 'high' : 'low',199 });200 }201202 await expect(collection.setProperties(alice, propertiesToBeSet)).203 to.be.rejectedWith(/common\.PropertyLimitReached/);204205 expect(await collection.getProperties()).to.be.empty;206 }207208 itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {209 await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));210 });211212 itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {213 await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));214 });215 216 async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {217 const invalidProperties = [218 [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],219 [{key: 'Mr/Sandman', value: 'Bring me a gene'}],220 [{key: 'déjà vu', value: 'hmm...'}],221 ];222223 for (let i = 0; i < invalidProperties.length; i++) {224 await expect(225 collection.setProperties(alice, invalidProperties[i]), 226 `on rejecting the new badly-named property #${i}`,227 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);228 }229230 await expect(231 collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 232 'on rejecting an unnamed property',233 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);234235 await expect(236 collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 237 'on setting the correctly-but-still-badly-named property',238 ).to.be.fulfilled;239240 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');241242 const properties = await collection.getProperties(keys);243 expect(properties).to.be.deep.equal([244 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},245 ]);246247 for (let i = 0; i < invalidProperties.length; i++) {248 await expect(249 collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 250 `on trying to delete the non-existent badly-named property #${i}`,251 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);252 }253 }254255 itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {256 await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));257 });258259 itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {260 await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));261 });262});263264// ---------- ACCESS RIGHTS265266describe('Integration Test: Access Rights to Token Properties', () => {267 let alice: IKeyringPair;268 let bob: IKeyringPair;269270 before(async () => {271 await usingPlaygrounds(async (helper, privateKey) => {272 const donor = privateKey('//Alice');273 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);274 });275 });276 277 itSub('Reads access rights to properties of a collection', async ({helper}) => {278 const collection = await helper.nft.mintCollection(alice);279 const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();280 expect(propertyRights).to.be.empty;281 });282 283 async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) { 284 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true}}]))285 .to.be.fulfilled;286287 await collection.addAdmin(alice, {Substrate: bob.address});288289 await expect(collection.setTokenPropertyPermissions(bob, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]))290 .to.be.fulfilled;291292 const propertyRights = await collection.getPropertyPermissions(['skullduggery', 'mindgame']);293 expect(propertyRights).to.include.deep.members([294 {key: 'skullduggery', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}},295 {key: 'mindgame', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},296 ]);297 }298299 itSub('Sets access rights to properties of a collection (NFT)', async ({helper}) => {300 await testSetsAccessRightsToProperties(await helper.nft.mintCollection(alice));301 });302303 itSub.ifWithPallets('Sets access rights to properties of a collection (ReFungible)', [Pallets.ReFungible], async ({helper}) => {304 await testSetsAccessRightsToProperties(await helper.rft.mintCollection(alice));305 });306 307 async function testChangesAccessRightsToProperty(collection: UniqueNFTCollection | UniqueRFTCollection) {308 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]))309 .to.be.fulfilled;310311 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))312 .to.be.fulfilled;313314 const propertyRights = await collection.getPropertyPermissions();315 expect(propertyRights).to.be.deep.equal([316 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},317 ]);318 }319320 itSub('Changes access rights to properties of a NFT collection', async ({helper}) => {321 await testChangesAccessRightsToProperty(await helper.nft.mintCollection(alice));322 });323324 itSub.ifWithPallets('Changes access rights to properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {325 await testChangesAccessRightsToProperty(await helper.rft.mintCollection(alice));326 });327});328329describe('Negative Integration Test: Access Rights to Token Properties', () => {330 let alice: IKeyringPair;331 let bob: IKeyringPair;332333 before(async () => {334 await usingPlaygrounds(async (helper, privateKey) => {335 const donor = privateKey('//Alice');336 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);337 });338 });339340 async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: UniqueNFTCollection | UniqueRFTCollection) {341 await expect(collection.setTokenPropertyPermissions(bob, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]))342 .to.be.rejectedWith(/common\.NoPermission/);343344 const propertyRights = await collection.getPropertyPermissions(['skullduggery']);345 expect(propertyRights).to.be.empty;346 }347348 itSub('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async ({helper}) => {349 await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.nft.mintCollection(alice));350 });351352 itSub.ifWithPallets('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', [Pallets.ReFungible], async ({helper}) => {353 await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.rft.mintCollection(alice));354 });355356 async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) { 357 const constitution = [];358 for (let i = 0; i < 65; i++) {359 constitution.push({360 key: 'property_' + i,361 permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},362 });363 }364365 await expect(collection.setTokenPropertyPermissions(alice, constitution))366 .to.be.rejectedWith(/common\.PropertyLimitReached/);367368 const propertyRights = await collection.getPropertyPermissions();369 expect(propertyRights).to.be.empty;370 }371372 itSub('Prevents from adding too many possible properties (NFT)', async ({helper}) => {373 await testPreventFromAddingTooManyPossibleProperties(await helper.nft.mintCollection(alice));374 });375376 itSub.ifWithPallets('Prevents from adding too many possible properties (ReFungible)', [Pallets.ReFungible], async ({helper}) => {377 await testPreventFromAddingTooManyPossibleProperties(await helper.rft.mintCollection(alice));378 });379380 async function testPreventAccessRightsModifiedIfConstant(collection: UniqueNFTCollection | UniqueRFTCollection) {381 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))382 .to.be.fulfilled;383384 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {collectionAdmin: true}}]))385 .to.be.rejectedWith(/common\.NoPermission/);386387 const propertyRights = await collection.getPropertyPermissions(['skullduggery']);388 expect(propertyRights).to.deep.equal([389 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},390 ]);391 }392393 itSub('Prevents access rights to be modified if constant (NFT)', async ({helper}) => {394 await testPreventAccessRightsModifiedIfConstant(await helper.nft.mintCollection(alice));395 });396397 itSub.ifWithPallets('Prevents access rights to be modified if constant (ReFungible)', [Pallets.ReFungible], async ({helper}) => {398 await testPreventAccessRightsModifiedIfConstant(await helper.rft.mintCollection(alice));399 });400401 async function testPreventsAddingPropertiesWithInvalidNames(collection: UniqueNFTCollection | UniqueRFTCollection) {402 const invalidProperties = [403 [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],404 [{key: 'G#4', permission: {tokenOwner: true}}],405 [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],406 ];407408 for (let i = 0; i < invalidProperties.length; i++) {409 await expect(410 collection.setTokenPropertyPermissions(alice, invalidProperties[i]), 411 `on setting the new badly-named property #${i}`,412 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);413 }414415 await expect(416 collection.setTokenPropertyPermissions(alice, [{key: '', permission: {}}]), 417 'on rejecting an unnamed property',418 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);419420 const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string421 await expect(422 collection.setTokenPropertyPermissions(alice, [423 {key: correctKey, permission: {collectionAdmin: true}},424 ]), 425 'on setting the correctly-but-still-badly-named property',426 ).to.be.fulfilled;427428 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');429430 const propertyRights = await collection.getPropertyPermissions(keys);431 expect(propertyRights).to.be.deep.equal([432 {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},433 ]);434 }435436 itSub('Prevents adding properties with invalid names (NFT)', async ({helper}) => {437 await testPreventsAddingPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));438 });439440 itSub.ifWithPallets('Prevents adding properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {441 await testPreventsAddingPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));442 });443});444445// ---------- TOKEN PROPERTIES446447describe('Integration Test: Token Properties', () => {448 let alice: IKeyringPair; // collection owner449 let bob: IKeyringPair; // collection admin450 let charlie: IKeyringPair; // token owner451452 let permissions: {permission: any, signers: IKeyringPair[]}[];453454 before(async () => {455 await usingPlaygrounds(async (helper, privateKey) => {456 const donor = privateKey('//Alice');457 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);458 });459460 // todo:playgrounds probably separate these tests later461 permissions = [462 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},463 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob]},464 {permission: {mutable: true, tokenOwner: true}, signers: [charlie]},465 {permission: {mutable: false, tokenOwner: true}, signers: [charlie]},466 {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},467 {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},468 ];469 });470 471 async function testReadsYetEmptyProperties(token: UniqueNFToken | UniqueRFToken) {472 const properties = await token.getProperties();473 expect(properties).to.be.empty;474475 const tokenData = await token.getData();476 expect(tokenData!.properties).to.be.empty;477 }478479 itSub('Reads yet empty properties of a token (NFT)', async ({helper}) => {480 const collection = await helper.nft.mintCollection(alice);481 const token = await collection.mintToken(alice);482 await testReadsYetEmptyProperties(token);483 });484485 itSub.ifWithPallets('Reads yet empty properties of a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {486 const collection = await helper.rft.mintCollection(alice);487 const token = await collection.mintToken(alice);488 await testReadsYetEmptyProperties(token);489 });490491 async function testAssignPropertiesAccordingToPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {492 await token.collection.addAdmin(alice, {Substrate: bob.address});493 await token.transfer(alice, {Substrate: charlie.address}, pieces);494495 const propertyKeys: string[] = [];496 let i = 0;497 for (const permission of permissions) {498 i++;499 let j = 0;500 for (const signer of permission.signers) {501 j++;502 const key = i + '_' + signer.address;503 propertyKeys.push(key);504505 await expect(506 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 507 `on setting permission #${i} by alice`,508 ).to.be.fulfilled;509510 await expect(511 token.setProperties(signer, [{key: key, value: 'Serotonin increase'}]), 512 `on adding property #${i} by signer #${j}`,513 ).to.be.fulfilled;514 }515 }516517 const properties = await token.getProperties(propertyKeys);518 const tokenData = await token.getData();519 for (let i = 0; i < properties.length; i++) {520 expect(properties[i].value).to.be.equal('Serotonin increase');521 expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');522 }523 }524525 itSub('Assigns properties to a token according to permissions (NFT)', async ({helper}) => {526 const collection = await helper.nft.mintCollection(alice);527 const token = await collection.mintToken(alice);528 await testAssignPropertiesAccordingToPermissions(token, 1n);529 });530531 itSub.ifWithPallets('Assigns properties to a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {532 const collection = await helper.rft.mintCollection(alice);533 const token = await collection.mintToken(alice, 100n);534 await testAssignPropertiesAccordingToPermissions(token, 100n);535 });536537 async function testChangesPropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {538 await token.collection.addAdmin(alice, {Substrate: bob.address});539 await token.transfer(alice, {Substrate: charlie.address}, pieces);540541 const propertyKeys: string[] = [];542 let i = 0;543 for (const permission of permissions) {544 i++;545 if (!permission.permission.mutable) continue;546 547 let j = 0;548 for (const signer of permission.signers) {549 j++;550 const key = i + '_' + signer.address;551 propertyKeys.push(key);552553 await expect(554 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 555 `on setting permission #${i} by alice`,556 ).to.be.fulfilled;557558 await expect(559 token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 560 `on adding property #${i} by signer #${j}`,561 ).to.be.fulfilled;562563 await expect(564 token.setProperties(signer, [{key, value: 'Serotonin stable'}]), 565 `on changing property #${i} by signer #${j}`,566 ).to.be.fulfilled;567 }568 }569570 const properties = await token.getProperties(propertyKeys);571 const tokenData = await token.getData();572 for (let i = 0; i < properties.length; i++) {573 expect(properties[i].value).to.be.equal('Serotonin stable');574 expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');575 }576 }577578 itSub('Changes properties of a token according to permissions (NFT)', async ({helper}) => {579 const collection = await helper.nft.mintCollection(alice);580 const token = await collection.mintToken(alice);581 await testChangesPropertiesAccordingPermission(token, 1n);582 });583584 itSub.ifWithPallets('Changes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {585 const collection = await helper.rft.mintCollection(alice);586 const token = await collection.mintToken(alice, 100n);587 await testChangesPropertiesAccordingPermission(token, 100n);588 });589590 async function testDeletePropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {591 await token.collection.addAdmin(alice, {Substrate: bob.address});592 await token.transfer(alice, {Substrate: charlie.address}, pieces);593594 const propertyKeys: string[] = [];595 let i = 0;596597 for (const permission of permissions) {598 i++;599 if (!permission.permission.mutable) continue;600 601 let j = 0;602 for (const signer of permission.signers) {603 j++;604 const key = i + '_' + signer.address;605 propertyKeys.push(key);606607 await expect(608 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 609 `on setting permission #${i} by alice`,610 ).to.be.fulfilled;611612 await expect(613 token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 614 `on adding property #${i} by signer #${j}`,615 ).to.be.fulfilled;616617 await expect(618 token.deleteProperties(signer, [key]), 619 `on deleting property #${i} by signer #${j}`,620 ).to.be.fulfilled;621 }622 }623624 expect(await token.getProperties(propertyKeys)).to.be.empty;625 expect((await token.getData())!.properties).to.be.empty;626 }627 628 itSub('Deletes properties of a token according to permissions (NFT)', async ({helper}) => {629 const collection = await helper.nft.mintCollection(alice);630 const token = await collection.mintToken(alice);631 await testDeletePropertiesAccordingPermission(token, 1n);632 });633634 itSub.ifWithPallets('Deletes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {635 const collection = await helper.rft.mintCollection(alice);636 const token = await collection.mintToken(alice, 100n);637 await testDeletePropertiesAccordingPermission(token, 100n);638 });639640 itSub('Assigns properties to a nested token according to permissions', async ({helper}) => {641 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});642 const collectionB = await helper.nft.mintCollection(alice);643 const targetToken = await collectionA.mintToken(alice);644 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());645646 await collectionB.addAdmin(alice, {Substrate: bob.address});647 await targetToken.transfer(alice, {Substrate: charlie.address});648649 const propertyKeys: string[] = [];650 let i = 0;651 for (const permission of permissions) {652 i++;653 let j = 0;654 for (const signer of permission.signers) {655 j++;656 const key = i + '_' + signer.address;657 propertyKeys.push(key);658 659 await expect(660 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 661 `on setting permission #${i} by alice`,662 ).to.be.fulfilled;663664 await expect(665 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 666 `on adding property #${i} by signer #${j}`,667 ).to.be.fulfilled;668 }669670 }671672 const properties = await nestedToken.getProperties(propertyKeys);673 const tokenData = await nestedToken.getData();674 for (let i = 0; i < properties.length; i++) {675 expect(properties[i].value).to.be.equal('Serotonin increase');676 expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');677 }678 expect(await targetToken.getProperties()).to.be.empty;679 });680681 itSub('Changes properties of a nested token according to permissions', async ({helper}) => {682 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});683 const collectionB = await helper.nft.mintCollection(alice);684 const targetToken = await collectionA.mintToken(alice);685 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());686687 await collectionB.addAdmin(alice, {Substrate: bob.address});688 await targetToken.transfer(alice, {Substrate: charlie.address});689690 const propertyKeys: string[] = [];691 let i = 0;692 for (const permission of permissions) {693 i++;694 if (!permission.permission.mutable) continue;695 696 let j = 0;697 for (const signer of permission.signers) {698 j++;699 const key = i + '_' + signer.address;700 propertyKeys.push(key);701702 await expect(703 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 704 `on setting permission #${i} by alice`,705 ).to.be.fulfilled;706707 await expect(708 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 709 `on adding property #${i} by signer #${j}`,710 ).to.be.fulfilled;711712 await expect(713 nestedToken.setProperties(signer, [{key, value: 'Serotonin stable'}]), 714 `on changing property #${i} by signer #${j}`,715 ).to.be.fulfilled;716 }717 }718719 const properties = await nestedToken.getProperties(propertyKeys);720 const tokenData = await nestedToken.getData();721 for (let i = 0; i < properties.length; i++) {722 expect(properties[i].value).to.be.equal('Serotonin stable');723 expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');724 }725 expect(await targetToken.getProperties()).to.be.empty;726 });727728 itSub('Deletes properties of a nested token according to permissions', async ({helper}) => {729 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});730 const collectionB = await helper.nft.mintCollection(alice);731 const targetToken = await collectionA.mintToken(alice);732 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());733734 await collectionB.addAdmin(alice, {Substrate: bob.address});735 await targetToken.transfer(alice, {Substrate: charlie.address});736737 const propertyKeys: string[] = [];738 let i = 0;739 for (const permission of permissions) {740 i++;741 if (!permission.permission.mutable) continue;742 743 let j = 0;744 for (const signer of permission.signers) {745 j++;746 const key = i + '_' + signer.address;747 propertyKeys.push(key);748749 await expect(750 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 751 `on setting permission #${i} by alice`,752 ).to.be.fulfilled;753754 await expect(755 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 756 `on adding property #${i} by signer #${j}`,757 ).to.be.fulfilled;758759 await expect(760 nestedToken.deleteProperties(signer, [key]), 761 `on deleting property #${i} by signer #${j}`,762 ).to.be.fulfilled;763 }764 }765766 expect(await nestedToken.getProperties(propertyKeys)).to.be.empty;767 expect((await nestedToken.getData())!.properties).to.be.empty;768 expect(await targetToken.getProperties()).to.be.empty;769 });770});771772describe('Negative Integration Test: Token Properties', () => {773 let alice: IKeyringPair; // collection owner774 let bob: IKeyringPair; // collection admin775 let charlie: IKeyringPair; // token owner776777 let constitution: {permission: any, signers: IKeyringPair[], sinner: IKeyringPair}[];778779 before(async () => {780 await usingPlaygrounds(async (helper, privateKey) => {781 const donor = privateKey('//Alice');782 let dave: IKeyringPair;783 [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);784785 // todo:playgrounds probably separate these tests later786 constitution = [787 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},788 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},789 {permission: {mutable: true, tokenOwner: true}, signers: [charlie], sinner: alice},790 {permission: {mutable: false, tokenOwner: true}, signers: [charlie], sinner: alice},791 {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie], sinner: dave},792 {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie], sinner: dave},793 ];794 });795 });796797 async function getConsumedSpace(api: any, collectionId: number, tokenId: number, mode: 'NFT' | 'RFT'): Promise<number> {798 return (await (mode == 'NFT' ? api.query.nonfungible : api.query.refungible).tokenProperties(collectionId, tokenId)).toJSON().consumedSpace;799 }800801 async function prepare(token: UniqueNFToken | UniqueRFToken, pieces: bigint): Promise<number> {802 await token.collection.addAdmin(alice, {Substrate: bob.address});803 await token.transfer(alice, {Substrate: charlie.address}, pieces);804805 let i = 0;806 for (const passage of constitution) {807 i++;808 const signer = passage.signers[0];809 810 await expect(811 token.collection.setTokenPropertyPermissions(alice, [{key: `${i}`, permission: passage.permission}]), 812 `on setting permission ${i} by alice`,813 ).to.be.fulfilled;814815 await expect(816 token.setProperties(signer, [{key: `${i}`, value: 'Serotonin increase'}]), 817 `on adding property ${i} by ${signer.address}`,818 ).to.be.fulfilled;819 }820821 const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 822 return originalSpace;823 }824825 async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {826 const originalSpace = await prepare(token, pieces);827828 let i = 0;829 for (const forbiddance of constitution) {830 i++;831 if (!forbiddance.permission.mutable) continue;832833 await expect(834 token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]), 835 `on failing to change property ${i} by the malefactor`,836 ).to.be.rejectedWith(/common\.NoPermission/);837838 await expect(839 token.deleteProperties(forbiddance.sinner, [`${i}`]), 840 `on failing to delete property ${i} by the malefactor`,841 ).to.be.rejectedWith(/common\.NoPermission/);842 }843844 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 845 expect(consumedSpace).to.be.equal(originalSpace);846 }847848 itSub('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async ({helper}) => {849 const collection = await helper.nft.mintCollection(alice);850 const token = await collection.mintToken(alice);851 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 1n);852 });853854 itSub.ifWithPallets('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {855 const collection = await helper.rft.mintCollection(alice);856 const token = await collection.mintToken(alice, 100n);857 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 100n);858 });859860 async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {861 const originalSpace = await prepare(token, pieces);862863 let i = 0;864 for (const permission of constitution) {865 i++;866 if (permission.permission.mutable) continue;867868 await expect(869 token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]), 870 `on failing to change property ${i} by signer #0`,871 ).to.be.rejectedWith(/common\.NoPermission/);872873 await expect(874 token.deleteProperties(permission.signers[0], [i.toString()]), 875 `on failing to delete property ${i} by signer #0`,876 ).to.be.rejectedWith(/common\.NoPermission/);877 }878 879 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 880 expect(consumedSpace).to.be.equal(originalSpace);881 }882883 itSub('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async ({helper}) => {884 const collection = await helper.nft.mintCollection(alice);885 const token = await collection.mintToken(alice);886 await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 1n);887 });888889 itSub.ifWithPallets('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', [Pallets.ReFungible], async ({helper}) => {890 const collection = await helper.rft.mintCollection(alice);891 const token = await collection.mintToken(alice, 100n);892 await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 100n);893 });894895 async function testForbidsAddingPropertiesIfPropertyNotDeclared(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {896 const originalSpace = await prepare(token, pieces);897898 await expect(899 token.setProperties(alice, [{key: 'non-existent', value: 'I exist!'}]), 900 'on failing to add a previously non-existent property',901 ).to.be.rejectedWith(/common\.NoPermission/);902 903 await expect(904 token.collection.setTokenPropertyPermissions(alice, [{key: 'now-existent', permission: {}}]), 905 'on setting a new non-permitted property',906 ).to.be.fulfilled;907908 await expect(909 token.setProperties(alice, [{key: 'now-existent', value: 'I exist!'}]), 910 'on failing to add a property forbidden by the \'None\' permission',911 ).to.be.rejectedWith(/common\.NoPermission/);912913 expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;914 915 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 916 expect(consumedSpace).to.be.equal(originalSpace);917 }918919 itSub('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async ({helper}) => {920 const collection = await helper.nft.mintCollection(alice);921 const token = await collection.mintToken(alice);922 await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 1n);923 });924925 itSub.ifWithPallets('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', [Pallets.ReFungible], async ({helper}) => {926 const collection = await helper.rft.mintCollection(alice);927 const token = await collection.mintToken(alice, 100n);928 await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 100n);929 });930931 async function testForbidsAddingTooManyProperties(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {932 const originalSpace = await prepare(token, pieces);933934 await expect(935 token.collection.setTokenPropertyPermissions(alice, [936 {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 937 {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},938 ]), 939 'on setting new permissions for properties',940 ).to.be.fulfilled;941942 // Mute the general tx parsing error943 {944 console.error = () => {};945 await expect(token.setProperties(alice, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]))946 .to.be.rejected;947 }948949 await expect(token.setProperties(alice, [950 {key: 'a_holy_book', value: 'word '.repeat(3277)}, 951 {key: 'young_years', value: 'neverending'.repeat(1490)},952 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);953 954 expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;955 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 956 expect(consumedSpace).to.be.equal(originalSpace);957 }958959 itSub('Forbids adding too many properties to a token (NFT)', async ({helper}) => {960 const collection = await helper.nft.mintCollection(alice);961 const token = await collection.mintToken(alice);962 await testForbidsAddingTooManyProperties(token, 1n);963 });964965 itSub.ifWithPallets('Forbids adding too many properties to a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {966 const collection = await helper.rft.mintCollection(alice);967 const token = await collection.mintToken(alice, 100n);968 await testForbidsAddingTooManyProperties(token, 100n);969 });970});971972describe('ReFungible token properties permissions tests', () => {973 let alice: IKeyringPair;974 let bob: IKeyringPair;975 let charlie: IKeyringPair;976977 before(async function() {978 await usingPlaygrounds(async (helper, privateKey) => {979 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);980981 const donor = privateKey('//Alice');982 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);983 });984 });985986 async function prepare(helper: UniqueHelper): Promise<UniqueRFToken> {987 const collection = await helper.rft.mintCollection(alice);988 const token = await collection.mintToken(alice, 100n);989 990 await collection.addAdmin(alice, {Substrate: bob.address});991 await collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable: true, tokenOwner: true}}]);992 993 return token;994 }995996 itSub('Forbids adding token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) => {997 const token = await prepare(helper);998999 await token.transfer(alice, {Substrate: charlie.address}, 33n);10001001 await expect(token.setProperties(alice, [1002 {key: 'fractals', value: 'multiverse'}, 1003 ])).to.be.rejectedWith(/common\.NoPermission/);1004 });10051006 itSub('Forbids mutating token property with tokenOwher==true when signer doesn\'t have all pieces', async ({helper}) => {1007 const token = await prepare(helper);10081009 await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, tokenOwner: true}}]))1010 .to.be.fulfilled;10111012 await expect(token.setProperties(alice, [1013 {key: 'fractals', value: 'multiverse'}, 1014 ])).to.be.fulfilled;10151016 await token.transfer(alice, {Substrate: charlie.address}, 33n);10171018 await expect(token.setProperties(alice, [1019 {key: 'fractals', value: 'want to rule the world'}, 1020 ])).to.be.rejectedWith(/common\.NoPermission/);1021 });10221023 itSub('Forbids deleting token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) => {1024 const token = await prepare(helper);10251026 await expect(token.setProperties(alice, [1027 {key: 'fractals', value: 'one headline - why believe it'}, 1028 ])).to.be.fulfilled;10291030 await token.transfer(alice, {Substrate: charlie.address}, 33n);10311032 await expect(token.deleteProperties(alice, ['fractals'])).1033 to.be.rejectedWith(/common\.NoPermission/);1034 });10351036 itSub('Allows token property mutation with collectionOwner==true when admin doesn\'t have all pieces', async ({helper}) => {1037 const token = await prepare(helper);10381039 await token.transfer(alice, {Substrate: charlie.address}, 33n);10401041 await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, collectionAdmin: true}}]))1042 .to.be.fulfilled;10431044 await expect(token.setProperties(alice, [1045 {key: 'fractals', value: 'multiverse'}, 1046 ])).to.be.fulfilled;1047 });1048});tests/src/nesting/rules-smoke.test.tsdiffbeforeafterboth--- a/tests/src/nesting/rules-smoke.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, CrossAccountId, getCreateCollectionResult, requirePallets, Pallets} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-
-describe('nesting check', () => {
- let alice!: IKeyringPair;
- let nestTarget!: CrossAccountId;
- before(async() => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
- const events = await executeTransaction(api, alice, api.tx.unique.createCollectionEx({
- mode: 'NFT',
- permissions: {
- nesting: {tokenOwner: true, restricted: []},
- },
- }));
- const collection = getCreateCollectionResult(events).collectionId;
- const token = await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: bob.address});
- nestTarget = {Ethereum: tokenIdToAddress(collection, token)};
- });
- });
-
- it('called for fungible', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'Fungible',decimalPoints:0}});
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {Fungible: {Value: 1}})))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
- await createFungibleItemExpectSuccess(alice, collection, {Value:1n}, {Substrate: alice.address});
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, 0, 1n)))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
- });
- });
-
- it('called for nonfungible', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {NFT: {properties: []}})))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
- const token = await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: alice.address});
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, token, 1n)))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
- });
- });
-
- it('called for refungible', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
-
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {ReFungible: {}})))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
- const token = await createItemExpectSuccess(alice, collection, 'ReFungible', {Substrate: alice.address});
- await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, token, 1n)))
- .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
- });
- });
-});
tests/src/nesting/unnest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -1,162 +1,126 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- getBalance,
- getTokenOwner,
- normalizeAccountId,
- setCollectionPermissionsExpectSuccess,
- transferExpectSuccess,
- transferFromExpectSuccess,
- requirePallets,
- Pallets,
-} from '../util/helpers';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';
-let alice: IKeyringPair;
-let bob: IKeyringPair;
+describe('Integration Test: Unnesting', () => {
+ let alice: IKeyringPair;
-describe('Integration Test: Unnesting', () => {
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice] = await helper.arrange.createAccounts([50n], donor);
});
});
- it('NFT: allows the owner to successfully unnest a token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
-
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
+ itSub('NFT: allows the owner to successfully unnest a token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
+
+ // Create a nested token
+ const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
- // Unnest
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(alice), collection, nestedToken, 1),
- ), 'while unnesting').to.not.be.rejected;
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
+ // Unnest
+ await expect(nestedToken.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}), 'while unnesting').to.be.fulfilled;
+ expect(await nestedToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
- // Nest and burn
- await transferExpectSuccess(collection, nestedToken, alice, targetAddress);
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.burnFrom(collection, normalizeAccountId(targetAddress), nestedToken, 1),
- ), 'while burning').to.not.be.rejected;
- await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected;
- });
+ // Nest and burn
+ await nestedToken.nest(alice, targetToken);
+ await expect(nestedToken.burnFrom(alice, targetToken.nestingAccount()), 'while burning').to.be.fulfilled;
+ await expect(nestedToken.getOwner()).to.be.rejected;
});
- it('Fungible: allows the owner to successfully unnest a token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+ itSub('Fungible: allows the owner to successfully unnest a token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
- const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const nestedToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
+ const collectionFT = await helper.ft.mintCollection(alice);
+
+ // Nest and unnest
+ await collectionFT.mint(alice, 10n, targetToken.nestingAccount());
+ await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+ expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(9n);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
- // Nest and unnest
- await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
- await transferFromExpectSuccess(collectionFT, nestedToken, alice, targetAddress, alice, 1, 'Fungible');
-
- // Nest and burn
- await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
- const balanceBefore = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.burnFrom(collectionFT, normalizeAccountId(targetAddress), nestedToken, 1),
- ), 'while burning').to.not.be.rejected;
- const balanceAfter = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
- expect(balanceAfter + BigInt(1)).to.be.equal(balanceBefore);
- });
+ // Nest and burn
+ await collectionFT.transfer(alice, targetToken.nestingAccount(), 5n);
+ await expect(collectionFT.burnTokensFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+ expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(4n);
+ expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+ expect(await targetToken.getChildren()).to.be.length(0);
});
- it('ReFungible: allows the owner to successfully unnest a token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('ReFungible: allows the owner to successfully unnest a token', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
-
- const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const nestedToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-
- // Nest and unnest
- await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
- await transferFromExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, alice, 1, 'ReFungible');
+ const collectionRFT = await helper.rft.mintCollection(alice);
+
+ // Nest and unnest
+ const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
+ await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);
+ expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
- // Nest and burn
- await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.burnFrom(collectionRFT, normalizeAccountId(targetAddress), nestedToken, 1),
- ), 'while burning').to.not.be.rejected;
- const balance = await getBalance(api, collectionRFT, normalizeAccountId(targetAddress), nestedToken);
- expect(balance).to.be.equal(0n);
- });
+ // Nest and burn
+ await token.transfer(alice, targetToken.nestingAccount(), 5n);
+ await expect(token.burnFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);
+ expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+ expect(await targetToken.getChildren()).to.be.length(0);
});
});
describe('Negative Test: Unnesting', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
});
});
- it('Disallows a non-owner to unnest/burn a token', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
- const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+ itSub('Disallows a non-owner to unnest/burn a token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
- // Create a nested token
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
+ // Create a nested token
+ const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
- // Try to unnest
- await expect(executeTransaction(
- api,
- bob,
- api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),
- ), 'while unnesting').to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+ // Try to unnest
+ await expect(nestedToken.unnest(bob, targetToken, {Substrate: alice.address})).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
- // Try to burn
- await expect(executeTransaction(
- api,
- bob,
- api.tx.unique.burnFrom(collection, normalizeAccountId(bob.address), nestedToken, 1),
- ), 'while burning').to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
- expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
- });
+ // Try to burn
+ await expect(nestedToken.burnFrom(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
});
// todo another test for creating excessive depth matryoshka with Ethereum?
// Recursive nesting
- it('Prevents Ouroboros creation', async () => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
- const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ itSub('Prevents Ouroboros creation', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
- // Create a nested token ouroboros
- const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- await expect(transferExpectSuccess(collection, targetToken, alice, {Ethereum: tokenIdToAddress(collection, nestedToken)})).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
+ // Fail to create a nested token ouroboros
+ const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+ await expect(targetToken.nest(alice, nestedToken)).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
});
});
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -9,7 +9,6 @@
import '../../interfaces/augment-api-events';
import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
-
chai.use(chaiAsPromised);
export const expect = chai.expect;
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -94,15 +94,15 @@
export interface IProperty {
key: string;
- value: string;
+ value?: string;
}
export interface ITokenPropertyPermission {
key: string;
permission: {
- mutable: boolean;
- tokenOwner: boolean;
- collectionAdmin: boolean;
+ mutable?: boolean;
+ tokenOwner?: boolean;
+ collectionAdmin?: boolean;
}
}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -55,10 +55,18 @@
RPC: 'rpc',
};
- static getNestingTokenAddress(collectionId: number, tokenId: number) {
- return nesting.tokenIdToAddress(collectionId, tokenId);
+ static getTokenAccount(token: IToken): ICrossAccountId {
+ return {Ethereum: this.getTokenAddress(token)};
}
+ static getTokenAccountInLowerCase(token: IToken): ICrossAccountId {
+ return {Ethereum: this.getTokenAddress(token).toLowerCase()};
+ }
+
+ static getTokenAddress(token: IToken): string {
+ return nesting.tokenIdToAddress(token.collectionId, token.tokenId);
+ }
+
static getDefaultLogger(): ILogger {
return {
log(msg: any, level = 'INFO') {
@@ -592,11 +600,7 @@
const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();
return normalize
- ? admins.map((address: any) => {
- return address.Substrate
- ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
- : address;
- })
+ ? admins.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))
: admins;
}
@@ -610,11 +614,7 @@
async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {
const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();
return normalize
- ? allowListed.map((address: any) => {
- return address.Substrate
- ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
- : address;
- })
+ ? allowListed.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))
: allowListed;
}
@@ -897,6 +897,18 @@
}
/**
+ * Get collection properties.
+ *
+ * @param collectionId ID of collection
+ * @param propertyKeys optionally filter the returned properties to only these keys
+ * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);
+ * @returns array of key-value pairs
+ */
+ async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {
+ return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();
+ }
+
+ /**
* Deletes onchain properties from the collection.
*
* @param signer keyring of signer
@@ -988,13 +1000,13 @@
*
* @param signer keyring of signer
* @param collectionId ID of collection
+ * @param tokenId ID of token
* @param fromAddressObj address on behalf of which the token will be burnt
- * @param tokenId ID of token
* @param amount amount of tokens to be burned. For NFT must be set to 1n
* @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
- async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {
+ async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {
const burnResult = await this.helper.executeExtrinsic(
signer,
'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],
@@ -1106,7 +1118,7 @@
if (tokenData === null || tokenData.owner === null) return null;
const owner = {} as any;
for (const key of Object.keys(tokenData.owner)) {
- owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];
+ owner[key.toLocaleLowerCase()] = this.helper.address.normalizeCrossAccountIfSubstrate(tokenData.owner[key]);
}
tokenData.normalizedOwner = crossAccountIdFromLower(owner);
return tokenData;
@@ -1117,7 +1129,7 @@
*
* @param signer keyring of signer
* @param collectionId ID of collection
- * @param permissions permissions to change a property by the collection owner or admin
+ * @param permissions permissions to change a property by the collection admin or token owner
* @example setTokenPropertyPermissions(
* aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]
* )
@@ -1134,6 +1146,18 @@
}
/**
+ * Get token property permissions.
+ *
+ * @param collectionId ID of collection
+ * @param propertyKeys optionally filter the returned property permissions to only these keys
+ * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);
+ * @returns array of key-permission pairs
+ */
+ async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {
+ return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();
+ }
+
+ /**
* Set token properties
*
* @param signer keyring of signer
@@ -1154,6 +1178,19 @@
}
/**
+ * Get properties, metadata assigned to a token.
+ *
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param propertyKeys optionally filter the returned properties to only these keys
+ * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);
+ * @returns array of key-value pairs
+ */
+ async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {
+ return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();
+ }
+
+ /**
* Delete the provided properties of a token
* @param signer keyring of signer
* @param collectionId ID of collection
@@ -1181,7 +1218,7 @@
* @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")
* @returns object of the created collection
*/
- async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {
+ async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {
collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};
for (const key of ['name', 'description', 'tokenPrefix']) {
@@ -1223,8 +1260,8 @@
* @example getTokenObject(10, 5);
* @returns instance of UniqueNFTToken
*/
- getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {
- return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));
+ getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {
+ return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));
}
/**
@@ -1304,9 +1341,7 @@
if (owner === null) return null;
- owner = owner.toHuman();
-
- return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;
+ return owner.toHuman();
}
/**
@@ -1339,7 +1374,7 @@
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {
- const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};
+ const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);
const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);
if(!result) {
throw Error('Unable to nest token!');
@@ -1357,7 +1392,7 @@
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {
- const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};
+ const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);
const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);
if(!result) {
throw Error('Unable to unnest token!');
@@ -1377,7 +1412,7 @@
* })
* @returns object of the created collection
*/
- async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {
+ async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {
return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;
}
@@ -1387,7 +1422,7 @@
* @param data token data
* @returns created token object
*/
- async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {
+ async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {
const creationResult = await this.helper.executeExtrinsic(
signer,
'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {
@@ -1418,7 +1453,7 @@
* }]);
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
- async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {
+ async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {
const creationResult = await this.helper.executeExtrinsic(
signer,
'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],
@@ -1446,7 +1481,7 @@
* }]);
* @returns array of newly created tokens
*/
- async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {
+ async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {
const rawTokens = [];
for (const token of tokens) {
const raw = {NFT: {properties: token.properties}};
@@ -1495,8 +1530,8 @@
* @example getTokenObject(10, 5);
* @returns instance of UniqueNFTToken
*/
- getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {
- return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));
+ getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {
+ return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));
}
/**
@@ -1563,7 +1598,7 @@
* })
* @returns object of the created collection
*/
- async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {
+ async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {
return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;
}
@@ -1574,7 +1609,7 @@
* @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});
* @returns created token object
*/
- async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {
+ async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {
const creationResult = await this.helper.executeExtrinsic(
signer,
'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {
@@ -1591,7 +1626,7 @@
return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);
}
- async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {
+ async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {
throw Error('Not implemented');
const creationResult = await this.helper.executeExtrinsic(
signer,
@@ -1611,7 +1646,7 @@
* @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);
* @returns array of newly created RFT tokens
*/
- async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {
+ async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {
const rawTokens = [];
for (const token of tokens) {
const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};
@@ -1633,13 +1668,27 @@
* @param tokenId ID of token
* @param amount number of pieces to be burnt
* @example burnToken(aliceKeyring, 10, 5);
- * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```
+ * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```
*/
async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {
return await super.burnToken(signer, collectionId, tokenId, amount);
}
/**
+ * Destroys a concrete instance of RFT on behalf of the owner.
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param fromAddressObj address on behalf of which the token will be burnt
+ * @param amount number of pieces to be burnt
+ * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {
+ return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);
+ }
+
+ /**
* Set, change, or remove approved address to transfer the ownership of the RFT.
*
* @param signer keyring of signer
@@ -1711,7 +1760,7 @@
* }, 18)
* @returns newly created fungible collection
*/
- async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {
+ async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {
collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');
collectionOptions.mode = {fungible: decimalPoints};
@@ -1840,7 +1889,7 @@
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {
- return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);
+ return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);
}
/**
@@ -1936,7 +1985,7 @@
class BalanceGroup extends HelperGroup {
/**
- * Representation of the native token in the smallest unit
+ * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).
* @example getOneTokenNominal()
* @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.
*/
@@ -2017,6 +2066,19 @@
}
/**
+ * Normalizes the address of an account ONLY if it's Substrate to the specified ss58 format, by default ```42```.
+ * @param account account of either Substrate type or Ethereum, but only Substrate will be changed
+ * @param ss58Format format for address conversion, by default ```42```
+ * @example normalizeCrossAccountIfSubstrate({Substrate: "unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx"}) // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
+ * @returns untouched ethereum account or substrate account converted to normalized (i.e., starting with 5) or specified explicitly representation
+ */
+ normalizeCrossAccountIfSubstrate(account: ICrossAccountId, ss58Format = 42): ICrossAccountId {
+ return account.Substrate
+ ? {Substrate: this.normalizeSubstrate(account.Substrate, ss58Format)}
+ : account;
+ }
+
+ /**
* Get address in the connected chain format
* @param address substrate address
* @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network
@@ -2161,7 +2223,7 @@
}
-class UniqueCollectionBase {
+export class UniqueBaseCollection {
helper: UniqueHelper;
collectionId: number;
@@ -2194,6 +2256,14 @@
return await this.helper.collection.getEffectiveLimits(this.collectionId);
}
+ async getProperties(propertyKeys: string[] | null = null) {
+ return await this.helper.collection.getProperties(this.collectionId, propertyKeys);
+ }
+
+ async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {
+ return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
+ }
+
async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {
return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);
}
@@ -2238,10 +2308,6 @@
return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);
}
- async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {
- return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
- }
-
async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {
return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);
}
@@ -2260,9 +2326,9 @@
}
-class UniqueNFTCollection extends UniqueCollectionBase {
+export class UniqueNFTCollection extends UniqueBaseCollection {
getTokenObject(tokenId: number) {
- return new UniqueNFTToken(tokenId, this);
+ return new UniqueNFToken(tokenId, this);
}
async getTokensByAddress(addressObj: ICrossAccountId) {
@@ -2285,6 +2351,14 @@
return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);
}
+ async getPropertyPermissions(propertyKeys: string[] | null = null) {
+ return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);
+ }
+
+ async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {
+ return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);
+ }
+
async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {
return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);
}
@@ -2313,6 +2387,10 @@
return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);
}
+ async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {
+ return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);
+ }
+
async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {
return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);
}
@@ -2335,11 +2413,15 @@
}
-class UniqueRFTCollection extends UniqueCollectionBase {
+export class UniqueRFTCollection extends UniqueBaseCollection {
getTokenObject(tokenId: number) {
- return new UniqueRFTToken(tokenId, this);
+ return new UniqueRFToken(tokenId, this);
}
+ async getToken(tokenId: number, blockHashAt?: string) {
+ return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);
+ }
+
async getTokensByAddress(addressObj: ICrossAccountId) {
return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);
}
@@ -2356,6 +2438,18 @@
return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);
}
+ async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
+ return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);
+ }
+
+ async getPropertyPermissions(propertyKeys: string[] | null = null) {
+ return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);
+ }
+
+ async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {
+ return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);
+ }
+
async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {
return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);
}
@@ -2366,10 +2460,6 @@
async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);
- }
-
- async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
- return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);
}
async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {
@@ -2388,6 +2478,10 @@
return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);
}
+ async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {
+ return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);
+ }
+
async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {
return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);
}
@@ -2402,23 +2496,31 @@
}
-class UniqueFTCollection extends UniqueCollectionBase {
- async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {
- return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);
+export class UniqueFTCollection extends UniqueBaseCollection {
+ async getBalance(addressObj: ICrossAccountId) {
+ return await this.helper.ft.getBalance(this.collectionId, addressObj);
}
- async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {
- return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);
+ async getTotalPieces() {
+ return await this.helper.ft.getTotalPieces(this.collectionId);
}
- async getBalance(addressObj: ICrossAccountId) {
- return await this.helper.ft.getBalance(this.collectionId, addressObj);
+ async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
+ return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);
}
async getTop10Owners() {
return await this.helper.ft.getTop10Owners(this.collectionId);
}
+ async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {
+ return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);
+ }
+
+ async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {
+ return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);
+ }
+
async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);
}
@@ -2433,23 +2535,15 @@
async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);
- }
-
- async getTotalPieces() {
- return await this.helper.ft.getTotalPieces(this.collectionId);
}
async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);
- }
-
- async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
- return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);
}
}
-class UniqueTokenBase implements IToken {
+export class UniqueBaseToken {
collection: UniqueNFTCollection | UniqueRFTCollection;
collectionId: number;
tokenId: number;
@@ -2464,6 +2558,10 @@
return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);
}
+ async getProperties(propertyKeys: string[] | null = null) {
+ return await this.collection.getTokenProperties(this.tokenId, propertyKeys);
+ }
+
async setProperties(signer: TSigner, properties: IProperty[]) {
return await this.collection.setTokenProperties(signer, this.tokenId, properties);
}
@@ -2471,10 +2569,18 @@
async deleteProperties(signer: TSigner, propertyKeys: string[]) {
return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);
}
+
+ nestingAccount() {
+ return this.collection.helper.util.getTokenAccount(this);
+ }
+
+ nestingAccountInLowerCase() {
+ return this.collection.helper.util.getTokenAccountInLowerCase(this);
+ }
}
-class UniqueNFTToken extends UniqueTokenBase {
+export class UniqueNFToken extends UniqueBaseToken {
collection: UniqueNFTCollection;
constructor(tokenId: number, collection: UniqueNFTCollection) {
@@ -2525,9 +2631,13 @@
async burn(signer: TSigner) {
return await this.collection.burnToken(signer, this.tokenId);
}
+
+ async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {
+ return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);
+ }
}
-class UniqueRFTToken extends UniqueTokenBase {
+export class UniqueRFToken extends UniqueBaseToken {
collection: UniqueRFTCollection;
constructor(tokenId: number, collection: UniqueRFTCollection) {
@@ -2535,6 +2645,10 @@
this.collection = collection;
}
+ async getData(blockHashAt?: string) {
+ return await this.collection.getToken(this.tokenId, blockHashAt);
+ }
+
async getTop10Owners() {
return await this.collection.getTop10TokenOwners(this.tokenId);
}
@@ -2547,6 +2661,10 @@
return await this.collection.getTokenTotalPieces(this.tokenId);
}
+ async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {
+ return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);
+ }
+
async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {
return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);
}
@@ -2559,10 +2677,6 @@
return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);
}
- async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {
- return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);
- }
-
async repartition(signer: TSigner, amount: bigint) {
return await this.collection.repartitionToken(signer, this.tokenId, amount);
}
@@ -2570,4 +2684,8 @@
async burn(signer: TSigner, amount=1n) {
return await this.collection.burnToken(signer, this.tokenId, amount);
}
+
+ async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {
+ return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);
+ }
}