difftreelog
tests: upgrade part of them in ascending naming order to use playgrounds
in: master
24 files changed
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -17,119 +17,114 @@
import {IKeyringPair} from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {usingPlaygrounds} from './util/playgrounds';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
-let donor: IKeyringPair;
+describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
+ let donor: IKeyringPair;
-before(async () => {
- await usingPlaygrounds(async (_, privateKeyWrapper) => {
- donor = privateKeyWrapper('//Alice');
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKeyWrapper) => {
+ donor = privateKeyWrapper('//Alice');
+ });
});
-});
-describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
- it('Add collection admin.', async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, bob] = await helper.arrange.createAccounts([10n, 10n], donor);
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+ itSub('Add collection admin.', async ({helper}) => {
+ const [alice, bob] = await helper.arrange.createAccounts([10n, 10n], donor);
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const collection = await helper.collection.getData(collectionId);
- expect(collection!.normalizedOwner!).to.be.equal(alice.address);
+ const collection = await helper.collection.getData(collectionId);
+ expect(collection!.normalizedOwner!).to.be.equal(helper.address.normalizeSubstrate(alice.address));
- await helper.nft.addAdmin(alice, collectionId, {Substrate: bob.address});
+ await helper.nft.addAdmin(alice, collectionId, {Substrate: bob.address});
- const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
- });
+ const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
});
});
describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
- it("Not owner can't add collection admin.", async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+ let donor: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKeyWrapper) => {
+ donor = privateKeyWrapper('//Alice');
+ });
+ });
- const collection = await helper.collection.getData(collectionId);
- expect(collection?.normalizedOwner).to.be.equal(alice.address);
+ itSub("Not owner can't add collection admin.", async ({helper}) => {
+ const [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const changeAdminTxBob = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: bob.address});
- const changeAdminTxCharlie = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: charlie.address});
- await expect(changeAdminTxCharlie()).to.be.rejected;
- await expect(changeAdminTxBob()).to.be.rejected;
+ const collection = await helper.collection.getData(collectionId);
+ expect(collection?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(alice.address));
+
+ const changeAdminTxBob = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: bob.address});
+ const changeAdminTxCharlie = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: charlie.address});
+ await expect(changeAdminTxCharlie()).to.be.rejectedWith(/common\.NoPermission/);
+ await expect(changeAdminTxBob()).to.be.rejectedWith(/common\.NoPermission/);
- const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
- expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: charlie.address});
- expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: bob.address});
- });
+ const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
+ expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: charlie.address});
+ expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: bob.address});
});
- it("Admin can't add collection admin.", async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+ itSub("Admin can't add collection admin.", async ({helper}) => {
+ const [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
+ const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- await collection.addAdmin(alice, {Substrate: bob.address});
+ await collection.addAdmin(alice, {Substrate: bob.address});
- const adminListAfterAddAdmin = await collection.getAdmins();
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
+ const adminListAfterAddAdmin = await collection.getAdmins();
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
- const changeAdminTxCharlie = async () => collection.addAdmin(bob, {Substrate: charlie.address});
- await expect(changeAdminTxCharlie()).to.be.rejected;
+ const changeAdminTxCharlie = async () => collection.addAdmin(bob, {Substrate: charlie.address});
+ await expect(changeAdminTxCharlie()).to.be.rejectedWith(/common\.NoPermission/);
- const adminListAfterAddNewAdmin = await collection.getAdmins();
- expect(adminListAfterAddNewAdmin).to.be.deep.contains({Substrate: bob.address});
- expect(adminListAfterAddNewAdmin).to.be.not.deep.contains({Substrate: charlie.address});
- });
+ const adminListAfterAddNewAdmin = await collection.getAdmins();
+ expect(adminListAfterAddNewAdmin).to.be.deep.contains({Substrate: bob.address});
+ expect(adminListAfterAddNewAdmin).to.be.not.deep.contains({Substrate: charlie.address});
});
- it("Can't add collection admin of not existing collection.", async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, bob] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
- // tslint:disable-next-line: no-bitwise
- const collectionId = (1 << 32) - 1;
+ itSub("Can't add collection admin of not existing collection.", async ({helper}) => {
+ const [alice, bob] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
+ const collectionId = (1 << 32) - 1;
- const addAdminTx = async () => helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
- await expect(addAdminTx()).to.be.rejected;
+ const addAdminTx = async () => helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
+ await expect(addAdminTx()).to.be.rejectedWith(/common\.CollectionNotFound/);
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- });
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
});
- it("Can't add an admin to a destroyed collection.", async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, bob] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+ itSub("Can't add an admin to a destroyed collection.", async ({helper}) => {
+ const [alice, bob] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
+ const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- await collection.burn(alice);
- const addAdminTx = async () => collection.addAdmin(alice, {Substrate: bob.address});
- await expect(addAdminTx()).to.be.rejected;
+ await collection.burn(alice);
+ const addAdminTx = async () => collection.addAdmin(alice, {Substrate: bob.address});
+ await expect(addAdminTx()).to.be.rejectedWith(/common\.CollectionNotFound/);
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- });
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
});
- it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {
- await usingPlaygrounds(async (helper) => {
- const [alice, ...accounts] = await helper.arrange.createAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+ itSub('Add an admin to a collection that has reached the maximum number of admins limit', async ({helper}) => {
+ const [alice, ...accounts] = await helper.arrange.createAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
+ const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
- expect(chainAdminLimit).to.be.equal(5);
+ const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
+ expect(chainAdminLimit).to.be.equal(5);
- for (let i = 0; i < chainAdminLimit; i++) {
- await collection.addAdmin(alice, {Substrate: accounts[i].address});
- const adminListAfterAddAdmin = await collection.getAdmins();
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});
- }
+ for (let i = 0; i < chainAdminLimit; i++) {
+ await collection.addAdmin(alice, {Substrate: accounts[i].address});
+ const adminListAfterAddAdmin = await collection.getAdmins();
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});
+ }
- const addExtraAdminTx = async () => collection.addAdmin(alice, {Substrate: accounts[chainAdminLimit].address});
- await expect(addExtraAdminTx()).to.be.rejected;
- });
+ const addExtraAdminTx = async () => collection.addAdmin(alice, {Substrate: accounts[chainAdminLimit].address});
+ await expect(addExtraAdminTx()).to.be.rejectedWith(/common\.CollectionAdminCountExceeded/);
});
});
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -20,7 +20,7 @@
let donor: IKeyringPair;
before(async function() {
- await usingEthPlaygrounds(async (helper, privateKey) => {
+ await usingEthPlaygrounds(async (_, privateKey) => {
donor = privateKey('//Alice');
});
});
tests/src/eth/payable.test.tsdiffbeforeafterboth--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -22,7 +22,7 @@
let donor: IKeyringPair;
before(async function() {
- await usingEthPlaygrounds(async (helper, privateKey) => {
+ await usingEthPlaygrounds(async (_, privateKey) => {
donor = privateKey('//Alice');
});
});
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -16,11 +16,10 @@
import {IKeyringPair} from '@polkadot/types/types';
import {U128_MAX} from './util/helpers';
-
-import {usingPlaygrounds} from './util/playgrounds';
-
+import {itSub, usingPlaygrounds} from './util/playgrounds';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
+
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -35,131 +34,117 @@
});
});
- it('Create fungible collection and token', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'trest'});
- const defaultTokenId = await collection.getLastTokenId();
- expect(defaultTokenId).to.be.equal(0);
+ itSub('Create fungible collection and token', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'trest'});
+ const defaultTokenId = await collection.getLastTokenId();
+ expect(defaultTokenId).to.be.equal(0);
- await collection.mint(alice, {Substrate: alice.address}, U128_MAX);
- const aliceBalance = await collection.getBalance({Substrate: alice.address});
- const itemCountAfter = await collection.getLastTokenId();
+ await collection.mint(alice, {Substrate: alice.address}, U128_MAX);
+ const aliceBalance = await collection.getBalance({Substrate: alice.address});
+ const itemCountAfter = await collection.getLastTokenId();
- expect(itemCountAfter).to.be.equal(defaultTokenId);
- expect(aliceBalance).to.be.equal(U128_MAX);
- });
+ expect(itemCountAfter).to.be.equal(defaultTokenId);
+ expect(aliceBalance).to.be.equal(U128_MAX);
});
- it('RPC method tokenOnewrs for fungible collection and token', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));
+ itSub('RPC method tokenOnewrs for fungible collection and token', async ({helper, privateKey}) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- await collection.mint(alice, {Substrate: alice.address}, U128_MAX);
+ await collection.mint(alice, {Substrate: alice.address}, U128_MAX);
- await collection.transfer(alice, {Substrate: bob.address}, 1000n);
- await collection.transfer(alice, ethAcc, 900n);
-
- for (let i = 0; i < 7; i++) {
- await collection.transfer(alice, facelessCrowd[i], 1n);
- }
+ await collection.transfer(alice, {Substrate: bob.address}, 1000n);
+ await collection.transfer(alice, ethAcc, 900n);
+
+ for (let i = 0; i < 7; i++) {
+ await collection.transfer(alice, facelessCrowd[i], 1n);
+ }
- const owners = await collection.getTop10Owners();
+ const owners = await collection.getTop10Owners();
- // What to expect
- expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
- expect(owners.length).to.be.equal(10);
-
- const eleven = privateKey('//ALice+11');
- expect(await collection.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
- expect((await collection.getTop10Owners()).length).to.be.equal(10);
- });
+ // What to expect
+ expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
+ expect(owners.length).to.be.equal(10);
+
+ const eleven = privateKey('//ALice+11');
+ expect(await collection.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
+ expect((await collection.getTop10Owners()).length).to.be.equal(10);
});
- it('Transfer token', async () => {
- await usingPlaygrounds(async helper => {
- const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- await collection.mint(alice, {Substrate: alice.address}, 500n);
+ itSub('Transfer token', async ({helper}) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ await collection.mint(alice, {Substrate: alice.address}, 500n);
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(500n);
- expect(await collection.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
- expect(await collection.transfer(alice, ethAcc, 140n)).to.be.true;
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(500n);
+ expect(await collection.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
+ expect(await collection.transfer(alice, ethAcc, 140n)).to.be.true;
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(300n);
- expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(60n);
- expect(await collection.getBalance(ethAcc)).to.be.equal(140n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(300n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(60n);
+ expect(await collection.getBalance(ethAcc)).to.be.equal(140n);
- await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejected;
- });
+ await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejected;
});
- it('Tokens multiple creation', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ itSub('Tokens multiple creation', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- await collection.mintWithOneOwner(alice, {Substrate: alice.address}, [
- {value: 500n},
- {value: 400n},
- {value: 300n},
- ]);
+ await collection.mintWithOneOwner(alice, {Substrate: alice.address}, [
+ {value: 500n},
+ {value: 400n},
+ {value: 300n},
+ ]);
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1200n);
- });
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1200n);
});
- it('Burn some tokens ', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- await collection.mint(alice, {Substrate: alice.address}, 500n);
+ itSub('Burn some tokens ', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ await collection.mint(alice, {Substrate: alice.address}, 500n);
- expect(await collection.isTokenExists(0)).to.be.true;
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(500n);
- expect(await collection.burnTokens(alice, 499n)).to.be.true;
- expect(await collection.isTokenExists(0)).to.be.true;
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1n);
- });
+ expect(await collection.isTokenExists(0)).to.be.true;
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(500n);
+ expect(await collection.burnTokens(alice, 499n)).to.be.true;
+ expect(await collection.isTokenExists(0)).to.be.true;
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
- it('Burn all tokens ', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- await collection.mint(alice, {Substrate: alice.address}, 500n);
+ itSub('Burn all tokens ', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ await collection.mint(alice, {Substrate: alice.address}, 500n);
- expect(await collection.isTokenExists(0)).to.be.true;
- expect(await collection.burnTokens(alice, 500n)).to.be.true;
- expect(await collection.isTokenExists(0)).to.be.true;
+ expect(await collection.isTokenExists(0)).to.be.true;
+ expect(await collection.burnTokens(alice, 500n)).to.be.true;
+ expect(await collection.isTokenExists(0)).to.be.true;
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(0n);
- expect(await collection.getTotalPieces()).to.be.equal(0n);
- });
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(0n);
+ expect(await collection.getTotalPieces()).to.be.equal(0n);
});
- it('Set allowance for token', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- await collection.mint(alice, {Substrate: alice.address}, 100n);
+ itSub('Set allowance for token', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ await collection.mint(alice, {Substrate: alice.address}, 100n);
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(100n);
-
- expect(await collection.approveTokens(alice, {Substrate: bob.address}, 60n)).to.be.true;
- expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);
- expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(0n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(100n);
+
+ expect(await collection.approveTokens(alice, {Substrate: bob.address}, 60n)).to.be.true;
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(0n);
- expect(await collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(80n);
- expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(20n);
- expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);
+ expect(await collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(80n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(20n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);
- await collection.burnTokensFrom(bob, {Substrate: alice.address}, 10n);
+ await collection.burnTokensFrom(bob, {Substrate: alice.address}, 10n);
- expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(70n);
- expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(30n);
- expect(await collection.transferFrom(bob, {Substrate: alice.address}, ethAcc, 10n)).to.be.true;
- expect(await collection.getBalance(ethAcc)).to.be.equal(10n);
- });
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(70n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(30n);
+ expect(await collection.transferFrom(bob, {Substrate: alice.address}, ethAcc, 10n)).to.be.true;
+ expect(await collection.getBalance(ethAcc)).to.be.equal(10n);
});
});
tests/src/overflow.test.tsdiffbeforeafterboth--- a/tests/src/overflow.test.ts
+++ b/tests/src/overflow.test.ts
@@ -23,6 +23,7 @@
chai.use(chaiAsPromised);
const expect = chai.expect;
+// todo:playgrounds skipped ~ postponed
describe.skip('Integration Test fungible overflows', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -14,13 +14,8 @@
// 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 {ApiPromise} from '@polkadot/api';
import {expect} from 'chai';
-import usingApi from './substrate/substrate-api';
-
-function getModuleNames(api: ApiPromise): string[] {
- return api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
-}
+import {itSub, usingPlaygrounds} from './util/playgrounds';
// Pallets that must always be present
const requiredPallets = [
@@ -62,8 +57,8 @@
describe('Pallet presence', () => {
before(async () => {
- await usingApi(async api => {
- const chain = await api.rpc.system.chain();
+ await usingPlaygrounds(async helper => {
+ const chain = await helper.api!.rpc.system.chain();
const refungible = 'refungible';
const scheduler = 'scheduler';
@@ -80,23 +75,15 @@
});
});
- it('Required pallets are present', async () => {
- await usingApi(async api => {
- for (let i=0; i<requiredPallets.length; i++) {
- expect(getModuleNames(api)).to.include(requiredPallets[i]);
- }
- });
+ itSub('Required pallets are present', async ({helper}) => {
+ expect(helper.fetchAllPalletNames()).to.contain.members([...requiredPallets]);
});
- it('Governance and consensus pallets are present', async () => {
- await usingApi(async api => {
- for (let i=0; i<consensusPallets.length; i++) {
- expect(getModuleNames(api)).to.include(consensusPallets[i]);
- }
- });
+
+ itSub('Governance and consensus pallets are present', async ({helper}) => {
+ expect(helper.fetchAllPalletNames()).to.contain.members([...consensusPallets]);
});
- it('No extra pallets are included', async () => {
- await usingApi(async api => {
- expect(getModuleNames(api).sort()).to.be.deep.equal([...requiredPallets, ...consensusPallets].sort());
- });
+
+ itSub('No extra pallets are included', async ({helper}) => {
+ expect(helper.fetchAllPalletNames().sort()).to.be.deep.equal([...requiredPallets, ...consensusPallets].sort());
});
});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -15,13 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-
-import {usingPlaygrounds} from './util/playgrounds';
-import {
- getModuleNames,
- Pallets,
- requirePallets,
-} from './util/helpers';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util/playgrounds';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -34,255 +28,231 @@
describe('integration test: Refungible functionality:', async () => {
before(async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
- await usingPlaygrounds(async (helper, privateKey) => {
alice = privateKey('//Alice');
bob = privateKey('//Bob');
- if (!getModuleNames(helper.api!).includes(Pallets.ReFungible)) this.skip();
});
});
- it('Create refungible collection and token', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ itSub('Create refungible collection and token', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const itemCountBefore = await collection.getLastTokenId();
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
-
- const itemCountAfter = await collection.getLastTokenId();
-
- // What to expect
- expect(token?.tokenId).to.be.gte(itemCountBefore);
- expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
- expect(itemCountAfter.toString()).to.be.equal(token?.tokenId.toString());
- });
+ const itemCountBefore = await collection.getLastTokenId();
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+
+ const itemCountAfter = await collection.getLastTokenId();
+
+ // What to expect
+ expect(token?.tokenId).to.be.gte(itemCountBefore);
+ expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
+ expect(itemCountAfter.toString()).to.be.equal(token?.tokenId.toString());
});
- it('Checking RPC methods when interacting with maximum allowed values (MAX_REFUNGIBLE_PIECES)', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-
- const token = await collection.mintToken(alice, {Substrate: alice.address}, MAX_REFUNGIBLE_PIECES);
-
- expect(await collection.getTokenBalance(token.tokenId, {Substrate: alice.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
-
- await collection.transferToken(alice, token.tokenId, {Substrate: bob.address}, MAX_REFUNGIBLE_PIECES);
- expect(await collection.getTokenBalance(token.tokenId, {Substrate: bob.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
- expect(await token.getTotalPieces()).to.be.equal(MAX_REFUNGIBLE_PIECES);
-
- await expect(collection.mintToken(alice, {Substrate: alice.address}, MAX_REFUNGIBLE_PIECES + 1n)).to.eventually.be.rejected;
- });
+ itSub('Checking RPC methods when interacting with maximum allowed values (MAX_REFUNGIBLE_PIECES)', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, MAX_REFUNGIBLE_PIECES);
+
+ expect(await collection.getTokenBalance(token.tokenId, {Substrate: alice.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
+
+ await collection.transferToken(alice, token.tokenId, {Substrate: bob.address}, MAX_REFUNGIBLE_PIECES);
+ expect(await collection.getTokenBalance(token.tokenId, {Substrate: bob.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
+ expect(await token.getTotalPieces()).to.be.equal(MAX_REFUNGIBLE_PIECES);
+
+ await expect(collection.mintToken(alice, {Substrate: alice.address}, MAX_REFUNGIBLE_PIECES + 1n))
+ .to.eventually.be.rejectedWith(/refungible\.WrongRefungiblePieces/);
});
- it('RPC method tokenOnewrs for refungible collection and token', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));
+ itSub('RPC method tokenOnewrs for refungible collection and token', async ({helper, privateKey}) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 10_000n);
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 10_000n);
- await token.transfer(alice, {Substrate: bob.address}, 1000n);
- await token.transfer(alice, ethAcc, 900n);
-
- for (let i = 0; i < 7; i++) {
- await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));
- }
+ await token.transfer(alice, {Substrate: bob.address}, 1000n);
+ await token.transfer(alice, ethAcc, 900n);
+
+ for (let i = 0; i < 7; i++) {
+ await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));
+ }
- const owners = await token.getTop10Owners();
+ const owners = await token.getTop10Owners();
- // What to expect
- expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
- expect(owners.length).to.be.equal(10);
-
- const eleven = privateKey('//ALice+11');
- expect(await token.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
- expect((await token.getTop10Owners()).length).to.be.equal(10);
- });
+ // What to expect
+ expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
+ expect(owners.length).to.be.equal(10);
+
+ const eleven = privateKey('//ALice+11');
+ expect(await token.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
+ expect((await token.getTop10Owners()).length).to.be.equal(10);
});
- it('Transfer token pieces', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ itSub('Transfer token pieces', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
- expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
-
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
-
- await expect(token.transfer(alice, {Substrate: bob.address}, 41n)).to.eventually.be.rejected;
- });
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+ expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
+
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
+
+ await expect(token.transfer(alice, {Substrate: bob.address}, 41n))
+ .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('Create multiple tokens', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- // TODO: fix mintMultipleTokens
- // await collection.mintMultipleTokens(alice, [
- // {owner: {Substrate: alice.address}, pieces: 1n},
- // {owner: {Substrate: alice.address}, pieces: 2n},
- // {owner: {Substrate: alice.address}, pieces: 100n},
- // ]);
- await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, [
- {pieces: 1n},
- {pieces: 2n},
- {pieces: 100n},
- ]);
- const lastTokenId = await collection.getLastTokenId();
- expect(lastTokenId).to.be.equal(3);
- expect(await collection.getTokenBalance(lastTokenId, {Substrate: alice.address})).to.be.equal(100n);
- });
+ itSub('Create multiple tokens', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ // TODO: fix mintMultipleTokens
+ // await collection.mintMultipleTokens(alice, [
+ // {owner: {Substrate: alice.address}, pieces: 1n},
+ // {owner: {Substrate: alice.address}, pieces: 2n},
+ // {owner: {Substrate: alice.address}, pieces: 100n},
+ // ]);
+ await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, [
+ {pieces: 1n},
+ {pieces: 2n},
+ {pieces: 100n},
+ ]);
+ const lastTokenId = await collection.getLastTokenId();
+ expect(lastTokenId).to.be.equal(3);
+ expect(await collection.getTokenBalance(lastTokenId, {Substrate: alice.address})).to.be.equal(100n);
});
- it('Burn some pieces', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
- expect((await token.burn(alice, 99n)).success).to.be.true;
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);
- });
+ itSub('Burn some pieces', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+ expect((await token.burn(alice, 99n)).success).to.be.true;
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
- it('Burn all pieces', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
-
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+ itSub('Burn all pieces', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
- expect((await token.burn(alice, 100n)).success).to.be.true;
- expect(await collection.isTokenExists(token.tokenId)).to.be.false;
- });
+ expect((await token.burn(alice, 100n)).success).to.be.true;
+ expect(await collection.isTokenExists(token.tokenId)).to.be.false;
});
- it('Burn some pieces for multiple users', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ itSub('Burn some pieces for multiple users', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
-
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
- expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+ expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
- expect((await token.burn(alice, 40n)).success).to.be.true;
+ expect((await token.burn(alice, 40n)).success).to.be.true;
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
- expect((await token.burn(bob, 59n)).success).to.be.true;
+ expect((await token.burn(bob, 59n)).success).to.be.true;
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);
- expect(await collection.isTokenExists(token.tokenId)).to.be.true;
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);
+ expect(await collection.isTokenExists(token.tokenId)).to.be.true;
- expect((await token.burn(bob, 1n)).success).to.be.true;
+ expect((await token.burn(bob, 1n)).success).to.be.true;
- expect(await collection.isTokenExists(token.tokenId)).to.be.false;
- });
+ expect(await collection.isTokenExists(token.tokenId)).to.be.false;
});
- it('Set allowance for token', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
-
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
+ itSub('Set allowance for token', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
- expect(await token.approve(alice, {Substrate: bob.address}, 60n)).to.be.true;
- expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);
+ expect(await token.approve(alice, {Substrate: bob.address}, 60n)).to.be.true;
+ expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);
- expect(await token.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(80n);
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(20n);
- expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);
- });
+ expect(await token.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(80n);
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(20n);
+ expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);
});
- it('Repartition', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ itSub('Repartition', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- expect(await token.repartition(alice, 200n)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);
- expect(await token.getTotalPieces()).to.be.equal(200n);
-
- expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);
-
- await expect(token.repartition(alice, 80n)).to.eventually.be.rejected;
-
- expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;
- expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
- expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);
-
- expect(await token.repartition(bob, 150n)).to.be.true;
- await expect(token.transfer(bob, {Substrate: alice.address}, 160n)).to.eventually.be.rejected;
+ expect(await token.repartition(alice, 200n)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);
+ expect(await token.getTotalPieces()).to.be.equal(200n);
+
+ expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);
+
+ await expect(token.repartition(alice, 80n))
+ .to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);
+
+ expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
+ expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);
- });
+ expect(await token.repartition(bob, 150n)).to.be.true;
+ await expect(token.transfer(bob, {Substrate: alice.address}, 160n))
+ .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('Repartition with increased amount', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- await token.repartition(alice, 200n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
- method: 'ItemCreated',
- section: 'common',
- index: '0x4202',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '100',
- ],
- }]);
- });
+ itSub('Repartition with increased amount', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ await token.repartition(alice, 200n);
+ const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
+ expect(chainEvents).to.include.deep.members([{
+ method: 'ItemCreated',
+ section: 'common',
+ index: '0x4202',
+ data: [
+ helper.api!.createType('u32', collection.collectionId).toHuman(),
+ helper.api!.createType('u32', token.tokenId).toHuman(),
+ {Substrate: alice.address},
+ '100',
+ ],
+ }]);
});
- it('Repartition with decreased amount', async () => {
- await usingPlaygrounds(async helper => {
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
- await token.repartition(alice, 50n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
- method: 'ItemDestroyed',
- section: 'common',
- index: '0x4203',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '50',
- ],
- }]);
- });
+ itSub('Repartition with decreased amount', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address}, 100n);
+ await token.repartition(alice, 50n);
+ const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
+ expect(chainEvents).to.include.deep.members([{
+ method: 'ItemDestroyed',
+ section: 'common',
+ index: '0x4203',
+ data: [
+ helper.api!.createType('u32', collection.collectionId).toHuman(),
+ helper.api!.createType('u32', token.tokenId).toHuman(),
+ {Substrate: alice.address},
+ '50',
+ ],
+ }]);
});
- it('Create new collection with properties', async () => {
- await usingPlaygrounds(async helper => {
- const properties = [{key: 'key1', value: 'val1'}];
- const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];
- const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test', properties, tokenPropertyPermissions});
- const info = await collection.getData();
- expect(info?.raw.properties).to.be.deep.equal(properties);
- expect(info?.raw.tokenPropertyPermissions).to.be.deep.equal(tokenPropertyPermissions);
- });
+ itSub('Create new collection with properties', async ({helper}) => {
+ const properties = [{key: 'key1', value: 'val1'}];
+ const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test', properties, tokenPropertyPermissions});
+ const info = await collection.getData();
+ expect(info?.raw.properties).to.be.deep.equal(properties);
+ expect(info?.raw.tokenPropertyPermissions).to.be.deep.equal(tokenPropertyPermissions);
});
});
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -16,113 +16,102 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {usingPlaygrounds} from './util/playgrounds';
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('Integration Test removeCollectionAdmin(collection_id, account_id):', () => {
- it('Remove collection admin.', async () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- const collection = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-
- const collectionInfo = await collection.getData();
- expect(collectionInfo?.raw.owner.toString()).to.be.deep.eq(alice.address);
- // first - add collection admin Bob
- await collection.addAdmin(alice, {Substrate: bob.address});
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([20n, 10n], donor);
+ });
+ });
- const adminListAfterAddAdmin = await collection.getAdmins();
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(bob.address)});
+ itSub('Remove collection admin', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-1', tokenPrefix: 'RCA'});
+ const collectionInfo = await collection.getData();
+ expect(collectionInfo?.raw.owner.toString()).to.be.deep.eq(alice.address);
+ // first - add collection admin Bob
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ const adminListAfterAddAdmin = await collection.getAdmins();
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
- // then remove bob from admins of collection
- await collection.removeAdmin(alice, {Substrate: bob.address});
+ // then remove bob from admins of collection
+ await collection.removeAdmin(alice, {Substrate: bob.address});
- const adminListAfterRemoveAdmin = await collection.getAdmins();
- expect(adminListAfterRemoveAdmin).not.to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(bob.address)});
- });
+ const adminListAfterRemoveAdmin = await collection.getAdmins();
+ expect(adminListAfterRemoveAdmin).not.to.be.deep.contains({Substrate: bob.address});
});
- it('Remove admin from collection that has no admins', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const alice = privateKey('//Alice');
- const collection = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ itSub('Remove admin from collection that has no admins', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-2', tokenPrefix: 'RCA'});
- const adminListBeforeAddAdmin = await collection.getAdmins();
- expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
+ const adminListBeforeAddAdmin = await collection.getAdmins();
+ expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
- // await expect(collection.removeAdmin(alice, {Substrate: alice.address})).to.be.rejectedWith('Unable to remove collection admin');
- await collection.removeAdmin(alice, {Substrate: alice.address});
- });
+ await collection.removeAdmin(alice, {Substrate: alice.address});
});
});
describe('Negative Integration Test removeCollectionAdmin(collection_id, account_id):', () => {
- it('Can\'t remove collection admin from not existing collection', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = (1 << 32) - 1;
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
-
- await expect(helper.collection.removeAdmin(alice, collectionId, {Substrate: bob.address})).to.be.rejected;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob, charlie] = await helper.arrange.createAccounts([20n, 10n, 10n], donor);
});
});
- it('Can\'t remove collection admin from deleted collection', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- const collection = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ itSub('Can\'t remove collection admin from not existing collection', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
- expect(await collection.burn(alice)).to.be.true;
+ await expect(helper.collection.removeAdmin(alice, collectionId, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
+ });
- await expect(helper.collection.removeAdmin(alice, collection.collectionId, {Substrate: bob.address})).to.be.rejected;
+ itSub('Can\'t remove collection admin from deleted collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-Neg-2', tokenPrefix: 'RCA'});
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- });
- });
+ expect(await collection.burn(alice)).to.be.true;
- it('Regular user can\'t remove collection admin', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- const charlie = privateKey('//Charlie');
- const collection = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ await expect(helper.collection.removeAdmin(alice, collection.collectionId, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
+ });
- await collection.addAdmin(alice, {Substrate: bob.address});
+ itSub('Regular user can\'t remove collection admin', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-Neg-3', tokenPrefix: 'RCA'});
- await expect(collection.removeAdmin(charlie, {Substrate: bob.address})).to.be.rejected;
+ await collection.addAdmin(alice, {Substrate: bob.address});
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
- });
+ await expect(collection.removeAdmin(charlie, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.NoPermission/);
});
- it('Admin can\'t remove collection admin.', async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- const charlie = privateKey('//Charlie');
- const collection = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-
- await collection.addAdmin(alice, {Substrate: bob.address});
- await collection.addAdmin(alice, {Substrate: charlie.address});
+ itSub('Admin can\'t remove collection admin.', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-Neg-4', tokenPrefix: 'RCA'});
+
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ await collection.addAdmin(alice, {Substrate: charlie.address});
- const adminListAfterAddAdmin = await collection.getAdmins();
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(bob.address)});
- expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(charlie.address)});
+ const adminListAfterAddAdmin = await collection.getAdmins();
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
+ expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: charlie.address});
- await expect(collection.removeAdmin(charlie, {Substrate: bob.address})).to.be.rejected;
+ await expect(collection.removeAdmin(charlie, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.NoPermission/);
- const adminListAfterRemoveAdmin = await collection.getAdmins();
- expect(adminListAfterRemoveAdmin).to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(bob.address)});
- expect(adminListAfterRemoveAdmin).to.be.deep.contains({Substrate: helper.address.normalizeSubstrate(charlie.address)});
- });
+ const adminListAfterRemoveAdmin = await collection.getAdmins();
+ expect(adminListAfterRemoveAdmin).to.be.deep.contains({Substrate: bob.address});
+ expect(adminListAfterRemoveAdmin).to.be.deep.contains({Substrate: charlie.address});
});
});
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -16,136 +16,115 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- setCollectionSponsorExpectSuccess,
- destroyCollectionExpectSuccess,
- confirmSponsorshipExpectSuccess,
- confirmSponsorshipExpectFailure,
- createItemExpectSuccess,
- findUnusedAddress,
- removeCollectionSponsorExpectSuccess,
- removeCollectionSponsorExpectFailure,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
- getCreatedCollectionCount,
-} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-
describe('integration test: ext. removeCollectionSponsor():', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([10n, 10n], donor);
});
});
- it('Removing NFT collection sponsor stops sponsorship', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- await removeCollectionSponsorExpectSuccess(collectionId);
+ itSub('Removing NFT collection sponsor stops sponsorship', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-1', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.confirmSponsorship(bob);
+ await collection.removeSponsor(alice);
- await usingApi(async (api, privateKeyWrapper) => {
- // Find unused address
- const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ // Find unused address
+ const [zeroBalance] = await helper.arrange.createAccounts([0n], donor);
- // Mint token for unused address
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', zeroBalance.address);
+ // Mint token for unused address
+ const token = await collection.mintToken(alice, {Substrate: zeroBalance.address});
- // Transfer this tokens from unused address to Alice - should fail
- const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
- const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
- const badTransaction = async function () {
- await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
- };
- await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
- const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+ // Transfer this tokens from unused address to Alice - should fail
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(bob.address);
+ await expect(token.transfer(zeroBalance, {Substrate: alice.address}))
+ .to.be.rejectedWith('Inability to pay some fees');
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(bob.address);
- expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
- });
+ expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
});
- it('Remove a sponsor after it was already removed', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- await removeCollectionSponsorExpectSuccess(collectionId);
- await removeCollectionSponsorExpectSuccess(collectionId);
+ itSub('Remove a sponsor after it was already removed', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-2', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.confirmSponsorship(bob);
+ await expect(collection.removeSponsor(alice)).to.not.be.rejected;
+ await expect(collection.removeSponsor(alice)).to.not.be.rejected;
});
- it('Remove sponsor in a collection that never had the sponsor set', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await removeCollectionSponsorExpectSuccess(collectionId);
+ itSub('Remove sponsor in a collection that never had the sponsor set', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-3', tokenPrefix: 'RCS'});
+ await expect(collection.removeSponsor(alice)).to.not.be.rejected;
});
- it('Remove sponsor for a collection that had the sponsor set, but not confirmed', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await removeCollectionSponsorExpectSuccess(collectionId);
+ itSub('Remove sponsor for a collection that had the sponsor set, but not confirmed', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-4', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await expect(collection.removeSponsor(alice)).to.not.be.rejected;
});
});
describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: 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, charlie] = await helper.arrange.createAccounts([20n, 10n, 10n], donor);
});
});
- it('(!negative test!) Remove sponsor for a collection that never existed', async () => {
- // Find the collection that never existed
- let collectionId = 0;
- await usingApi(async (api) => {
- collectionId = await getCreatedCollectionCount(api) + 1;
- });
-
- await removeCollectionSponsorExpectFailure(collectionId);
+ itSub('(!negative test!) Remove sponsor for a collection that never existed', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.collection.removeSponsor(alice, collectionId)).to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('(!negative test!) Remove sponsor for a collection with collection admin permissions', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await removeCollectionSponsorExpectFailure(collectionId, '//Bob');
+ itSub('(!negative test!) Remove sponsor for a collection with collection admin permissions', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-1', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.addAdmin(alice, {Substrate: charlie.address});
+ await expect(collection.removeSponsor(charlie)).to.be.rejectedWith(/common\.NoPermission/);
});
- it('(!negative test!) Remove sponsor for a collection by regular user', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await removeCollectionSponsorExpectFailure(collectionId, '//Bob');
+ itSub('(!negative test!) Remove sponsor for a collection by regular user', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-2', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await expect(collection.removeSponsor(charlie)).to.be.rejectedWith(/common\.NoPermission/);
});
- it('(!negative test!) Remove sponsor in a destroyed collection', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await destroyCollectionExpectSuccess(collectionId);
- await removeCollectionSponsorExpectFailure(collectionId);
+ itSub('(!negative test!) Remove sponsor in a destroyed collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-3', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.burn(alice);
+ await expect(collection.removeSponsor(alice)).to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('Set - remove - confirm: fails', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await removeCollectionSponsorExpectSuccess(collectionId);
- await confirmSponsorshipExpectFailure(collectionId, '//Bob');
+ itSub('Set - remove - confirm: fails', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-4', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.removeSponsor(alice);
+ await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
});
- it('Set - confirm - remove - confirm: Sponsor cannot come back', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- await removeCollectionSponsorExpectSuccess(collectionId);
- await confirmSponsorshipExpectFailure(collectionId, '//Bob');
+ itSub('Set - confirm - remove - confirm: Sponsor cannot come back', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-5', tokenPrefix: 'RCS'});
+ await collection.setSponsor(alice, bob.address);
+ await collection.confirmSponsorship(bob);
+ await collection.removeSponsor(alice);
+ await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
});
-
});
tests/src/removeFromAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromAllowList.test.ts
+++ b/tests/src/removeFromAllowList.test.ts
@@ -16,21 +16,8 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- destroyCollectionExpectSuccess,
- enableAllowListExpectSuccess,
- addToAllowListExpectSuccess,
- removeFromAllowListExpectSuccess,
- isAllowlisted,
- findNotExistingCollection,
- removeFromAllowListExpectFailure,
- disableAllowListExpectSuccess,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
-} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -40,32 +27,37 @@
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([10n, 10n], donor);
});
});
- it('ensure bob is not in allowlist after removal', async () => {
- await usingApi(async api => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableAllowListExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ itSub('ensure bob is not in allowlist after removal', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-1', tokenPrefix: 'RFAL'});
- await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
- expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
- });
+ const collectionInfo = await collection.getData();
+ expect(collectionInfo!.raw.permissions.access).to.not.equal('AllowList');
+
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ expect(await collection.getAllowList()).to.deep.contains({Substrate: bob.address});
+
+ await collection.removeFromAllowList(alice, {Substrate: bob.address});
+ expect(await collection.getAllowList()).to.be.empty;
});
- it('allows removal from collection with unset allowlist status', async () => {
- await usingApi(async () => {
- const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
- await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, bob.address);
- await disableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+ itSub('allows removal from collection with unset allowlist status', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-2', tokenPrefix: 'RFAL'});
- await removeFromAllowListExpectSuccess(alice, collectionWithoutAllowlistId, normalizeAccountId(bob.address));
- });
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ expect(await collection.getAllowList()).to.deep.contains({Substrate: bob.address});
+
+ await collection.setPermissions(alice, {access: 'Normal'});
+
+ await collection.removeFromAllowList(alice, {Substrate: bob.address});
+ expect(await collection.getAllowList()).to.be.empty;
});
});
@@ -74,29 +66,26 @@
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([10n, 10n], donor);
});
});
- it('fails on removal from not existing collection', async () => {
- await usingApi(async (api) => {
- const collectionId = await findNotExistingCollection(api);
-
- await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
- });
+ itSub('fails on removal from not existing collection', async ({helper}) => {
+ const nonExistentCollectionId = (1 << 32) - 1;
+ await expect(helper.collection.removeFromAllowList(alice, nonExistentCollectionId, {Substrate: alice.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('fails on removal from removed collection', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
- await destroyCollectionExpectSuccess(collectionId);
+ itSub('fails on removal from removed collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-3', tokenPrefix: 'RFAL'});
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
- await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
- });
+ await collection.burn(alice);
+ await expect(collection.removeFromAllowList(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
});
@@ -106,41 +95,45 @@
let charlie: IKeyringPair;
before(async () => {
- await usingApi(async (api, 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([10n, 10n, 10n], donor);
});
});
- it('ensure address is not in allowlist after removal', async () => {
- await usingApi(async api => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableAllowListExpectSuccess(alice, collectionId);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
- await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
- expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;
- });
+ itSub('ensure address is not in allowlist after removal', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-4', tokenPrefix: 'RFAL'});
+
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ await collection.addToAllowList(bob, {Substrate: charlie.address});
+ await collection.removeFromAllowList(bob, {Substrate: charlie.address});
+
+ expect(await collection.getAllowList()).to.be.empty;
});
- it('Collection admin allowed to remove from allowlist with unset allowlist status', async () => {
- await usingApi(async () => {
- const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
- await addCollectionAdminExpectSuccess(alice, collectionWithoutAllowlistId, bob.address);
- await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, charlie.address);
- await disableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
- await removeFromAllowListExpectSuccess(bob, collectionWithoutAllowlistId, normalizeAccountId(charlie.address));
- });
+ itSub('Collection admin allowed to remove from allowlist with unset allowlist status', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-5', tokenPrefix: 'RFAL'});
+
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ await collection.addToAllowList(alice, {Substrate: charlie.address});
+
+ await collection.setPermissions(bob, {access: 'Normal'});
+ await collection.removeFromAllowList(bob, {Substrate: charlie.address});
+
+ expect(await collection.getAllowList()).to.be.empty;
});
- it('Regular user can`t remove from allowlist', async () => {
- await usingApi(async () => {
- const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
- await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, charlie.address);
- await removeFromAllowListExpectFailure(bob, collectionWithoutAllowlistId, normalizeAccountId(charlie.address));
- });
+ itSub('Regular user can`t remove from allowlist', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'RemoveFromAllowList-6', tokenPrefix: 'RFAL'});
+
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: charlie.address});
+
+ await expect(collection.removeFromAllowList(bob, {Substrate: charlie.address}))
+ .to.be.rejectedWith(/common\.NoPermission/);
+ expect(await collection.getAllowList()).to.deep.contain({Substrate: charlie.address});
});
});
tests/src/removeFromContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromContractAllowList.test.ts
+++ b/tests/src/removeFromContractAllowList.test.ts
@@ -20,6 +20,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
+// todo:playgrounds skipped again
describe.skip('Integration Test removeFromContractAllowList', () => {
let bob: IKeyringPair;
tests/src/rpc.test.tsdiffbeforeafterboth--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -1,57 +1,57 @@
import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-import usingApi from './substrate/substrate-api';
-import {createCollection, createCollectionExpectSuccess, createFungibleItemExpectSuccess, CrossAccountId, getTokenOwner, normalizeAccountId, transfer, U128_MAX} from './util/helpers';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {usingPlaygrounds, itSub} from './util/playgrounds';
+import {crossAccountIdFromLower} from './util/playgrounds/unique';
-let alice: IKeyringPair;
-let bob: IKeyringPair;
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+describe('integration test: RPC methods', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
-describe('integration test: RPC methods', () => {
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([20n, 10n], donor);
});
});
-
- it('returns None for fungible collection', async () => {
- await usingApi(async api => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await expect(getTokenOwner(api, collection, 0)).to.be.rejectedWith(/^owner == null$/);
- });
+ itSub('returns None for fungible collection', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'RPC-1', tokenPrefix: 'RPC'});
+ const owner = (await helper.callRpc('api.rpc.unique.tokenOwner', [collection.collectionId, 0])).toJSON() as any;
+ expect(owner).to.be.null;
});
- it('RPC method tokenOwners for fungible collection and token', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const facelessCrowd = Array.from(Array(7).keys()).map(i => normalizeAccountId(privateKeyWrapper(i.toString())));
-
- const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
- const collectionId = createCollectionResult.collectionId;
- const aliceTokenId = await createFungibleItemExpectSuccess(alice, collectionId, {Value: U128_MAX}, alice.address);
-
- await transfer(api, collectionId, aliceTokenId, alice, bob, 1000n);
- await transfer(api, collectionId, aliceTokenId, alice, ethAcc, 900n);
-
- for (let i = 0; i < 7; i++) {
- await transfer(api, collectionId, aliceTokenId, alice, facelessCrowd[i], 1);
- }
-
- const owners = await api.rpc.unique.tokenOwners(collectionId, aliceTokenId);
- const ids = (owners.toJSON() as CrossAccountId[]).map(s => normalizeAccountId(s));
- const aliceID = normalizeAccountId(alice);
- const bobId = normalizeAccountId(bob);
+ itSub('RPC method tokenOwners for fungible collection and token', async ({helper}) => {
+ // Set-up a few token owners of all stripes
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = (await helper.arrange.createAccounts([0n, 0n, 0n, 0n, 0n, 0n, 0n], donor))
+ .map(i => {return {Substrate: i.address};});
+
+ const collection = await helper.ft.mintCollection(alice, {name: 'RPC-2', tokenPrefix: 'RPC'});
+ // mint some maximum (u128) amounts of tokens possible
+ await collection.mint(alice, {Substrate: alice.address}, (1n << 128n) - 1n);
+
+ await collection.transfer(alice, {Substrate: bob.address}, 1000n);
+ await collection.transfer(alice, ethAcc, 900n);
+
+ for (let i = 0; i < facelessCrowd.length; i++) {
+ await collection.transfer(alice, facelessCrowd[i], 1n);
+ }
+ // Set-up over
+
+ const owners = await helper.callRpc('api.rpc.unique.tokenOwners', [collection.collectionId, 0]);
+ const ids = (owners.toJSON() as any[]).map(crossAccountIdFromLower);
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(ids).to.deep.include.members([aliceID, ethAcc, bobId, ...facelessCrowd]);
- expect(owners.length == 10).to.be.true;
-
- const eleven = privateKeyWrapper('11');
- expect(await transfer(api, collectionId, aliceTokenId, alice, eleven, 10n)).to.be.true;
- expect((await api.rpc.unique.tokenOwners(collectionId, aliceTokenId)).length).to.be.equal(10);
- });
+ expect(ids).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
+ expect(owners.length == 10).to.be.true;
+
+ // Make sure only 10 results are returned with this RPC
+ const [eleven] = await helper.arrange.createAccounts([0n], donor);
+ expect(await collection.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
+ expect((await helper.callRpc('api.rpc.unique.tokenOwners', [collection.collectionId, 0])).length).to.be.equal(10);
});
});
\ No newline at end of file
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -44,6 +44,7 @@
chai.use(chaiAsPromised);
+// todo:playgrounds skipped ~ postponed
describe.skip('Scheduling token and balance transfers', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
tests/src/setChainLimits.test.tsdiffbeforeafterboth--- a/tests/src/setChainLimits.test.ts
+++ b/tests/src/setChainLimits.test.ts
@@ -23,6 +23,7 @@
IChainLimits,
} from './util/helpers';
+// todo:playgrounds skipped ~ postponed
describe.skip('Negative Integration Test setChainLimits', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
tests/src/setCollectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -15,26 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
-import {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess, getCreatedCollectionCount,
- getCreateItemResult,
- setCollectionLimitsExpectFailure,
- setCollectionLimitsExpectSuccess,
- addCollectionAdminExpectSuccess,
- queryCollectionExpectSuccess,
-} from './util/helpers';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let collectionIdForTesting: number;
const accountTokenOwnershipLimit = 0;
const sponsoredDataSize = 0;
@@ -42,197 +29,177 @@
const tokenLimit = 10;
describe('setCollectionLimits positive', () => {
- let tx;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
- });
- });
- it('execute setCollectionLimits with predefined params ', async () => {
- await usingApi(async (api: ApiPromise) => {
- tx = api.tx.unique.setCollectionLimits(
- collectionIdForTesting,
- {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredDataSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
- sponsorTransferTimeout,
- ownerCanTransfer: true,
- ownerCanDestroy: true,
- },
- );
- const events = await submitTransactionAsync(alice, tx);
- const result = getCreateItemResult(events);
-
- // get collection limits defined previously
- const collectionInfo = await queryCollectionExpectSuccess(api, collectionIdForTesting);
-
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(collectionInfo.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.equal(accountTokenOwnershipLimit);
- expect(collectionInfo.limits.sponsoredDataSize.unwrap().toNumber()).to.be.equal(sponsoredDataSize);
- expect(collectionInfo.limits.tokenLimit.unwrap().toNumber()).to.be.equal(tokenLimit);
- expect(collectionInfo.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.equal(sponsorTransferTimeout);
- expect(collectionInfo.limits.ownerCanTransfer.unwrap().toJSON()).to.be.true;
- expect(collectionInfo.limits.ownerCanDestroy.unwrap().toJSON()).to.be.true;
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([20n, 10n], donor);
});
});
- it('Set the same token limit twice', async () => {
- await usingApi(async (api: ApiPromise) => {
+ itSub('execute setCollectionLimits with predefined params', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-1', tokenPrefix: 'SCL'});
- const collectionLimits = {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredMintSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
+ await collection.setLimits(
+ alice,
+ {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
sponsorTransferTimeout,
ownerCanTransfer: true,
ownerCanDestroy: true,
- };
+ },
+ );
- // The first time
- const tx1 = api.tx.unique.setCollectionLimits(
- collectionIdForTesting,
- collectionLimits,
- );
- const events1 = await submitTransactionAsync(alice, tx1);
- const result1 = getCreateItemResult(events1);
- expect(result1.success).to.be.true;
- const collectionInfo1 = await queryCollectionExpectSuccess(api, collectionIdForTesting);
- expect(collectionInfo1.limits.tokenLimit.unwrap().toNumber()).to.be.equal(tokenLimit);
+ // get collection limits defined previously
+ const collectionInfo = await collection.getEffectiveLimits();
- // The second time
- const tx2 = api.tx.unique.setCollectionLimits(
- collectionIdForTesting,
- collectionLimits,
- );
- const events2 = await submitTransactionAsync(alice, tx2);
- const result2 = getCreateItemResult(events2);
- expect(result2.success).to.be.true;
- const collectionInfo2 = await queryCollectionExpectSuccess(api, collectionIdForTesting);
- expect(collectionInfo2.limits.tokenLimit.unwrap().toNumber()).to.be.equal(tokenLimit);
- });
+ expect(collectionInfo.accountTokenOwnershipLimit).to.be.equal(accountTokenOwnershipLimit);
+ expect(collectionInfo.sponsoredDataSize).to.be.equal(sponsoredDataSize);
+ expect(collectionInfo.tokenLimit).to.be.equal(tokenLimit);
+ expect(collectionInfo.sponsorTransferTimeout).to.be.equal(sponsorTransferTimeout);
+ expect(collectionInfo.ownerCanTransfer).to.be.true;
+ expect(collectionInfo.ownerCanDestroy).to.be.true;
});
- it('execute setCollectionLimits from admin collection', async () => {
- await addCollectionAdminExpectSuccess(alice, collectionIdForTesting, bob.address);
- await usingApi(async (api: ApiPromise) => {
- tx = api.tx.unique.setCollectionLimits(
- collectionIdForTesting,
- {
- accountTokenOwnershipLimit,
- sponsoredDataSize,
- // sponsoredMintSize,
- tokenLimit,
- },
- );
- await expect(submitTransactionAsync(bob, tx)).to.be.not.rejected;
- });
+ itSub('Set the same token limit twice', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-2', tokenPrefix: 'SCL'});
+
+ const collectionLimits = {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
+ sponsorTransferTimeout,
+ ownerCanTransfer: true,
+ ownerCanDestroy: true,
+ };
+
+ await collection.setLimits(alice, collectionLimits);
+
+ const collectionInfo1 = await collection.getEffectiveLimits();
+
+ expect(collectionInfo1.tokenLimit).to.be.equal(tokenLimit);
+
+ await collection.setLimits(alice, collectionLimits);
+ const collectionInfo2 = await collection.getEffectiveLimits();
+ expect(collectionInfo2.tokenLimit).to.be.equal(tokenLimit);
});
+
+ itSub('execute setCollectionLimits from admin collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-3', tokenPrefix: 'SCL'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ const collectionLimits = {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ // sponsoredMintSize,
+ tokenLimit,
+ };
+
+ await expect(collection.setLimits(alice, collectionLimits)).to.not.be.rejected;
+ });
});
describe('setCollectionLimits negative', () => {
- let tx;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([20n, 10n], donor);
});
});
- it('execute setCollectionLimits for not exists collection', async () => {
- await usingApi(async (api: ApiPromise) => {
- const collectionCount = await getCreatedCollectionCount(api);
- const nonExistedCollectionId = collectionCount + 1;
- tx = api.tx.unique.setCollectionLimits(
- nonExistedCollectionId,
- {
- accountTokenOwnershipLimit,
- sponsoredDataSize,
- // sponsoredMintSize,
- tokenLimit,
- },
- );
- await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
- });
+
+ itSub('execute setCollectionLimits for not exists collection', async ({helper}) => {
+ const nonExistentCollectionId = (1 << 32) - 1;
+ await expect(helper.collection.setLimits(
+ alice,
+ nonExistentCollectionId,
+ {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ // sponsoredMintSize,
+ tokenLimit,
+ },
+ )).to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('execute setCollectionLimits from user who is not owner of this collection', async () => {
- await usingApi(async (api: ApiPromise) => {
- tx = api.tx.unique.setCollectionLimits(
- collectionIdForTesting,
- {
- accountTokenOwnershipLimit,
- sponsoredDataSize,
- // sponsoredMintSize,
- tokenLimit,
- },
- );
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
- });
+
+ itSub('execute setCollectionLimits from user who is not owner of this collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-Neg-1', tokenPrefix: 'SCL'});
+
+ await expect(collection.setLimits(bob, {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ // sponsoredMintSize,
+ tokenLimit,
+ })).to.be.rejectedWith(/common\.NoPermission/);
});
- it('fails when trying to enable OwnerCanTransfer after it was disabled', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionLimitsExpectSuccess(alice, collectionId, {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredMintSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
+ itSub('fails when trying to enable OwnerCanTransfer after it was disabled', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-Neg-2', tokenPrefix: 'SCL'});
+
+ await collection.setLimits(alice, {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
sponsorTransferTimeout,
ownerCanTransfer: false,
ownerCanDestroy: true,
});
- await setCollectionLimitsExpectFailure(alice, collectionId, {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredMintSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
+
+ await expect(collection.setLimits(alice, {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
sponsorTransferTimeout,
ownerCanTransfer: true,
ownerCanDestroy: true,
- });
+ })).to.be.rejectedWith(/common\.OwnerPermissionsCantBeReverted/);
});
- it('fails when trying to enable OwnerCanDestroy after it was disabled', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionLimitsExpectSuccess(alice, collectionId, {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredMintSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
+ itSub('fails when trying to enable OwnerCanDestroy after it was disabled', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-Neg-3', tokenPrefix: 'SCL'});
+
+ await collection.setLimits(alice, {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
sponsorTransferTimeout,
ownerCanTransfer: true,
ownerCanDestroy: false,
});
- await setCollectionLimitsExpectFailure(alice, collectionId, {
+
+ await expect(collection.setLimits(alice, {
+ accountTokenOwnershipLimit,
+ sponsoredDataSize,
+ tokenLimit,
+ sponsorTransferTimeout,
+ ownerCanTransfer: true,
+ ownerCanDestroy: true,
+ })).to.be.rejectedWith(/common\.OwnerPermissionsCantBeReverted/);
+ });
+
+ itSub('Setting the higher token limit fails', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-Neg-4', tokenPrefix: 'SCL'});
+
+ const collectionLimits = {
accountTokenOwnershipLimit: accountTokenOwnershipLimit,
sponsoredMintSize: sponsoredDataSize,
tokenLimit: tokenLimit,
sponsorTransferTimeout,
ownerCanTransfer: true,
ownerCanDestroy: true,
- });
- });
+ };
- it('Setting the higher token limit fails', async () => {
- await usingApi(async () => {
+ // The first time
+ await collection.setLimits(alice, collectionLimits);
- const collectionId = await createCollectionExpectSuccess();
- const collectionLimits = {
- accountTokenOwnershipLimit: accountTokenOwnershipLimit,
- sponsoredMintSize: sponsoredDataSize,
- tokenLimit: tokenLimit,
- sponsorTransferTimeout,
- ownerCanTransfer: true,
- ownerCanDestroy: true,
- };
-
- // The first time
- await setCollectionLimitsExpectSuccess(alice, collectionId, collectionLimits);
-
- // The second time - higher token limit
- collectionLimits.tokenLimit += 1;
- await setCollectionLimitsExpectFailure(alice, collectionId, collectionLimits);
- });
+ // The second time - higher token limit
+ collectionLimits.tokenLimit += 1;
+ await expect(collection.setLimits(alice, collectionLimits)).to.be.rejectedWith(/common\.CollectionTokenLimitExceeded/);
});
-
});
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -16,91 +16,109 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
-import {createCollectionExpectSuccess,
- setCollectionSponsorExpectSuccess,
- destroyCollectionExpectSuccess,
- setCollectionSponsorExpectFailure,
- addCollectionAdminExpectSuccess,
- getCreatedCollectionCount,
- requirePallets,
- Pallets,
-} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds, Pallets} from './util/playgrounds';
chai.use(chaiAsPromised);
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+const expect = chai.expect;
describe('integration test: ext. setCollectionSponsor():', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
before(async () => {
- await usingApi(async (api, 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([20n, 10n, 10n], donor);
});
});
- it('Set NFT collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ itSub('Set NFT collection sponsor', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-1-NFT', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: bob.address,
+ });
});
- it('Set Fungible collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+
+ itSub('Set Fungible collection sponsor', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'SetCollectionSponsor-1-FT', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: bob.address,
+ });
});
- it('Set ReFungible collection sponsor', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ itSub.ifWithPallets('Set ReFungible collection sponsor', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'SetCollectionSponsor-1-RFT', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: bob.address,
+ });
});
- it('Set the same sponsor repeatedly', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ itSub('Set the same sponsor repeatedly', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-2', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: bob.address,
+ });
});
- it('Replace collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await setCollectionSponsorExpectSuccess(collectionId, charlie.address);
+
+ itSub('Replace collection sponsor', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-3', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
+ await expect(collection.setSponsor(alice, charlie.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: charlie.address,
+ });
});
- it('Collection admin add sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await setCollectionSponsorExpectSuccess(collectionId, charlie.address, '//Bob');
+
+ itSub('Collection admin add sponsor', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-4', tokenPrefix: 'SCS'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ await expect(collection.setSponsor(bob, charlie.address)).to.be.not.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.deep.equal({
+ Unconfirmed: charlie.address,
+ });
});
});
describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- charlie = privateKeyWrapper('//Charlie');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([10n, 5n], donor);
});
});
- it('(!negative test!) Add sponsor with a non-owner', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectFailure(collectionId, bob.address, '//Bob');
+ itSub('(!negative test!) Add sponsor with a non-owner', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-Neg-1', tokenPrefix: 'SCS'});
+ await expect(collection.setSponsor(bob, bob.address))
+ .to.be.rejectedWith(/common\.NoPermission/);
});
- it('(!negative test!) Add sponsor to a collection that never existed', async () => {
- // Find the collection that never existed
- let collectionId = 0;
- await usingApi(async (api) => {
- collectionId = await getCreatedCollectionCount(api) + 1;
- });
- await setCollectionSponsorExpectFailure(collectionId, bob.address);
+ itSub('(!negative test!) Add sponsor to a collection that never existed', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.collection.setSponsor(alice, collectionId, bob.address))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('(!negative test!) Add sponsor to a collection that was destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId);
- await setCollectionSponsorExpectFailure(collectionId, bob.address);
+
+ itSub('(!negative test!) Add sponsor to a collection that was destroyed', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-Neg-2', tokenPrefix: 'SCS'});
+ await collection.burn(alice);
+ await expect(collection.setSponsor(alice, bob.address))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
});
tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- a/tests/src/setContractSponsoringRateLimit.test.ts
+++ b/tests/src/setContractSponsoringRateLimit.test.ts
@@ -25,6 +25,7 @@
setContractSponsoringRateLimitExpectSuccess,
} from './util/helpers';
+// todo:playgrounds postponed skipped test
describe.skip('Integration Test setContractSponsoringRateLimit', () => {
it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
await usingApi(async (api, privateKeyWrapper) => {
tests/src/setMintPermission.test.tsdiffbeforeafterboth--- a/tests/src/setMintPermission.test.ts
+++ b/tests/src/setMintPermission.test.ts
@@ -15,65 +15,62 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import usingApi from './substrate/substrate-api';
-import {
- addToAllowListExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectFailure,
- createItemExpectSuccess,
- destroyCollectionExpectSuccess,
- enableAllowListExpectSuccess,
- findNotExistingCollection,
- setMintPermissionExpectFailure,
- setMintPermissionExpectSuccess,
- addCollectionAdminExpectSuccess,
-} from './util/helpers';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
describe('Integration Test setMintPermission', () => {
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([10n, 10n], donor);
});
});
- it('ensure allow-listed non-privileged address can mint tokens', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableAllowListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ itSub('ensure allow-listed non-privileged address can mint tokens', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-1', description: '', tokenPrefix: 'SMP'});
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
- await createItemExpectSuccess(bob, collectionId, 'NFT');
- });
+ await expect(collection.mintToken(bob, {Substrate: bob.address})).to.not.be.rejected;
});
- it('can be enabled twice', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- });
+ itSub('can be enabled twice', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-2', description: '', tokenPrefix: 'SMP'});
+ expect((await collection.getData())?.raw.permissions.access).to.not.equal('AllowList');
+
+ await collection.setPermissions(alice, {mintMode: true});
+ await collection.setPermissions(alice, {mintMode: true});
+ expect((await collection.getData())?.raw.permissions.mintMode).to.be.true;
});
- it('can be disabled twice', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- });
+ itSub('can be disabled twice', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-3', description: '', tokenPrefix: 'SMP'});
+ expect((await collection.getData())?.raw.permissions.access).to.equal('Normal');
+
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ expect((await collection.getData())?.raw.permissions.access).to.equal('AllowList');
+ expect((await collection.getData())?.raw.permissions.mintMode).to.equal(true);
+
+ await collection.setPermissions(alice, {access: 'Normal', mintMode: false});
+ await collection.setPermissions(alice, {access: 'Normal', mintMode: false});
+ expect((await collection.getData())?.raw.permissions.access).to.equal('Normal');
+ expect((await collection.getData())?.raw.permissions.mintMode).to.equal(false);
});
- it('Collection admin success on set', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await setMintPermissionExpectSuccess(bob, collectionId, true);
- });
+ itSub('Collection admin success on set', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-4', description: '', tokenPrefix: 'SMP'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+ await collection.setPermissions(bob, {access: 'AllowList', mintMode: true});
+
+ expect((await collection.getData())?.raw.permissions.access).to.equal('AllowList');
+ expect((await collection.getData())?.raw.permissions.mintMode).to.equal(true);
});
});
@@ -82,41 +79,38 @@
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([10n, 10n], donor);
});
});
- it('fails on not existing collection', async () => {
- await usingApi(async (api) => {
- const nonExistingCollection = await findNotExistingCollection(api);
- await setMintPermissionExpectFailure(alice, nonExistingCollection, true);
- });
+ itSub('fails on not existing collection', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.collection.setPermissions(alice, collectionId, {mintMode: true}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('fails on removed collection', async () => {
- await usingApi(async () => {
- const removedCollectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await destroyCollectionExpectSuccess(removedCollectionId);
+ itSub('fails on removed collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-Neg-1', tokenPrefix: 'SMP'});
+ await collection.burn(alice);
- await setMintPermissionExpectFailure(alice, removedCollectionId, true);
- });
+ await expect(collection.setPermissions(alice, {mintMode: true}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('fails when not collection owner tries to set mint status', async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableAllowListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectFailure(bob, collectionId, true);
+ itSub('fails when non-owner tries to set mint status', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-Neg-2', tokenPrefix: 'SMP'});
+
+ await expect(collection.setPermissions(bob, {mintMode: true}))
+ .to.be.rejectedWith(/common\.NoPermission/);
});
- it('ensure non-allow-listed non-privileged address can\'t mint tokens', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableAllowListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
+ itSub('ensure non-allow-listed non-privileged address can\'t mint tokens', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'SetMintPermission-Neg-3', tokenPrefix: 'SMP'});
+ await collection.setPermissions(alice, {mintMode: true});
- await createItemExpectFailure(bob, collectionId, 'NFT');
- });
+ await expect(collection.mintToken(bob, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.AddressNotInAllowlist/);
});
});
tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -15,111 +15,84 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
-import {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- addToAllowListExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- destroyCollectionExpectSuccess,
- enablePublicMintingExpectSuccess,
- enableAllowListExpectSuccess,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
- getCreatedCollectionCount,
-} from './util/helpers';
+import {itSub, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
describe('Integration Test setPublicAccessMode(): ', () => {
+ 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([10n, 10n], donor);
});
});
- it('Run extrinsic with collection id parameters, set the allowlist mode for the collection', async () => {
- await usingApi(async () => {
- const collectionId: number = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionId);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
- await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
- });
+ itSub('Runs extrinsic with collection id parameters, sets the allowlist mode for the collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-1', tokenPrefix: 'TF'});
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+
+ await expect(collection.mintToken(bob, {Substrate: bob.address})).to.be.not.rejected;
+ });
+
+ itSub('Allowlisted collection limits', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-2', tokenPrefix: 'TF'});
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+
+ await expect(collection.mintToken(bob, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.AddressNotInAllowlist/);
});
- it('Allowlisted collection limits', async () => {
- await usingApi(async (api: ApiPromise) => {
- const collectionId = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionId);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(bob.address), 'NFT');
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
- });
+ itSub('setPublicAccessMode by collection admin', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-Neg-4', tokenPrefix: 'TF'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ await expect(collection.setPermissions(bob, {access: 'AllowList'})).to.be.not.rejected;
});
});
describe('Negative Integration Test ext. setPublicAccessMode(): ', () => {
- it('Set a non-existent collection', async () => {
- await usingApi(async (api: ApiPromise) => {
- // tslint:disable-next-line: radix
- const collectionId = await getCreatedCollectionCount(api) + 1;
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: 'AllowList'});
- await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([10n, 10n], donor);
});
});
- it('Set the collection that has been deleted', async () => {
- await usingApi(async (api: ApiPromise) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId);
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: 'AllowList'});
- await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
- });
+ itSub('Sets a non-existent collection', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.collection.setPermissions(alice, collectionId, {access: 'AllowList'}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('Re-set the list mode already set in quantity', async () => {
- await usingApi(async () => {
- const collectionId: number = await createCollectionExpectSuccess();
- await enableAllowListExpectSuccess(alice, collectionId);
- await enableAllowListExpectSuccess(alice, collectionId);
- });
+ itSub('Sets the collection that has been deleted', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-Neg-1', tokenPrefix: 'TF'});
+ await collection.burn(alice);
+
+ await expect(collection.setPermissions(alice, {access: 'AllowList'}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('Execute method not on behalf of the collection owner', async () => {
- await usingApi(async (api: ApiPromise) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = await createCollectionExpectSuccess();
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: 'AllowList'});
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
- });
+ itSub('Re-sets the list mode already set in quantity', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-Neg-2', tokenPrefix: 'TF'});
+ await collection.setPermissions(alice, {access: 'AllowList'});
+ await collection.setPermissions(alice, {access: 'AllowList'});
});
- it('setPublicAccessMode by collection admin', async () => {
- await usingApi(async (api: ApiPromise) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: 'AllowList'});
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.not.rejected;
- });
- });
-});
+ itSub('Executes method as a malefactor', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'PublicAccess-Neg-3', tokenPrefix: 'TF'});
-describe('Negative Integration Test ext. collection admin setPublicAccessMode(): ', () => {
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- });
+ await expect(collection.setPermissions(bob, {access: 'AllowList'}))
+ .to.be.rejectedWith(/common\.NoPermission/);
});
});
tests/src/toggleContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/toggleContractAllowList.test.ts
+++ b/tests/src/toggleContractAllowList.test.ts
@@ -31,6 +31,7 @@
const value = 0;
const gasLimit = 3000n * 1000000n;
+// todo:playgrounds skipped ~ postpone
describe.skip('Integration Test toggleContractAllowList', () => {
it('Enable allow list contract mode', async () => {
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -14,387 +14,319 @@
// 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 {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-import getBalance from './substrate/get-balance';
-import {default as usingApi, submitTransactionAsync} from './substrate/substrate-api';
-import {
- burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess,
- destroyCollectionExpectSuccess,
- findUnusedAddress,
- getCreateCollectionResult,
- getCreateItemResult,
- transferExpectFailure,
- transferExpectSuccess,
- addCollectionAdminExpectSuccess,
- getCreatedCollectionCount,
- toSubstrateAddress,
- getTokenOwner,
- normalizeAccountId,
- getBalance as getTokenBalance,
- transferFromExpectSuccess,
- transferFromExpectFail,
- requirePallets,
- Pallets,
-} from './util/helpers';
-import {
- subToEth,
- itWeb3,
-} from './eth/util/helpers';
-import {request} from 'https';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {itEth, usingEthPlaygrounds} from './eth/util/playgrounds';
+import {itSub, Pallets, usingPlaygrounds} from './util/playgrounds';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+describe.skip('Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
-describe('Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
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('Balance transfers and check balance', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alice.address, bob.address]);
+ itSub('Balance transfers and check balance', async ({helper}) => {
+ const alicesBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
- const transfer = api.tx.balances.transfer(bob.address, 1n);
- const events = await submitTransactionAsync(alice, transfer);
- const result = getCreateItemResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
+ expect(await helper.balance.transferToSubstrate(alice, bob.address, 1n)).to.be.true;
- const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alice.address, bob.address]);
+ const alicesBalanceAfter = await helper.balance.getSubstrate(alice.address);
+ const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);
- // tslint:disable-next-line:no-unused-expression
- expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
- // tslint:disable-next-line:no-unused-expression
- expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;
- });
+ expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
+ expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;
});
- it('Inability to pay fees error message is correct', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- // Find unused address
- const pk = await findUnusedAddress(api, privateKeyWrapper);
+ itSub('Inability to pay fees error message is correct', async ({helper, privateKey}) => {
+ const donor = privateKey('//Alice');
+ const [zero] = await helper.arrange.createAccounts([0n], donor);
- const badTransfer = api.tx.balances.transfer(bob.address, 1n);
- // const events = await submitTransactionAsync(pk, badTransfer);
- const badTransaction = async () => {
- const events = await submitTransactionAsync(pk, badTransfer);
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- };
- await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees , e.g. account balance too low');
- });
+ // console.error = () => {};
+ // The following operation throws an error into the console and the logs. Pay it no heed as long as the test succeeds.
+ await expect(helper.balance.transferToSubstrate(zero, donor.address, 1n))
+ .to.be.rejectedWith('Inability to pay some fees , e.g. account balance too low');
});
- it('[nft] User can transfer owned token', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await transferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 'NFT');
+ itSub('[nft] User can transfer owned token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-1-NFT', description: '', tokenPrefix: 'T'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await nft.transfer(alice, {Substrate: bob.address});
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- it('[fungible] User can transfer owned token', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await transferExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob, 1, 'Fungible');
+ itSub('[fungible] User can transfer owned token', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-1-FT', description: '', tokenPrefix: 'T'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+
+ await collection.transfer(alice, {Substrate: bob.address}, 9n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(9n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
- it('[refungible] User can transfer owned token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] User can transfer owned token', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-1-RFT', description: '', tokenPrefix: 'T'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await transferExpectSuccess(
- reFungibleCollectionId,
- newReFungibleTokenId,
- alice,
- bob,
- 100,
- 'ReFungible',
- );
+ await rft.transfer(alice, {Substrate: bob.address}, 9n);
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.equal(9n);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
- it('[nft] Collection admin can transfer owned token', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
- const newNftTokenId = await createItemExpectSuccess(bob, nftCollectionId, 'NFT', bob.address);
- await transferExpectSuccess(nftCollectionId, newNftTokenId, bob, alice, 1, 'NFT');
+ itSub('[nft] Collection admin can transfer owned token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-2-NFT', description: '', tokenPrefix: 'T'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ const nft = await collection.mintToken(bob, {Substrate: bob.address});
+ await nft.transfer(bob, {Substrate: alice.address});
+
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('[fungible] Collection admin can transfer owned token', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await addCollectionAdminExpectSuccess(alice, fungibleCollectionId, bob.address);
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible', bob.address);
- await transferExpectSuccess(fungibleCollectionId, newFungibleTokenId, bob, alice, 1, 'Fungible');
+ itSub('[fungible] Collection admin can transfer owned token', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-2-FT', description: '', tokenPrefix: 'T'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ await collection.mint(bob, {Substrate: bob.address}, 10n);
+ await collection.transfer(bob, {Substrate: alice.address}, 1n);
+
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(9n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
- it('[refungible] Collection admin can transfer owned token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] Collection admin can transfer owned token', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-2-RFT', description: '', tokenPrefix: 'T'});
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ const rft = await collection.mintToken(bob, {Substrate: bob.address}, 10n);
+ await rft.transfer(bob, {Substrate: alice.address}, 1n);
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await addCollectionAdminExpectSuccess(alice, reFungibleCollectionId, bob.address);
- const newReFungibleTokenId = await createItemExpectSuccess(bob, reFungibleCollectionId, 'ReFungible', bob.address);
- await transferExpectSuccess(
- reFungibleCollectionId,
- newReFungibleTokenId,
- bob,
- alice,
- 100,
- 'ReFungible',
- );
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.equal(9n);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
});
-describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
+describe.skip('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- charlie = privateKeyWrapper('//Charlie');
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
});
});
- it('[nft] Transfer with not existed collection_id', async () => {
- await usingApi(async (api) => {
- const nftCollectionCount = await getCreatedCollectionCount(api);
- await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);
- });
+ itSub('[nft] Transfer with not existed collection_id', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.nft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('[fungible] Transfer with not existed collection_id', async () => {
- await usingApi(async (api) => {
- const fungibleCollectionCount = await getCreatedCollectionCount(api);
- await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);
- });
+ itSub('[fungible] Transfer with not existed collection_id', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.ft.transfer(alice, collectionId, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('[refungible] Transfer with not existed collection_id', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] Transfer with not existed collection_id', [Pallets.ReFungible], async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.rft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
+ });
+
+ itSub('[nft] Transfer with deleted collection_id', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-1-NFT', description: '', tokenPrefix: 'T'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await nft.burn(alice);
+ await collection.burn(alice);
- await usingApi(async (api) => {
- const reFungibleCollectionCount = await getCreatedCollectionCount(api);
- await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);
- });
+ await expect(nft.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('[nft] Transfer with deleted collection_id', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await burnItemExpectSuccess(alice, nftCollectionId, newNftTokenId);
- await destroyCollectionExpectSuccess(nftCollectionId);
- await transferExpectFailure(nftCollectionId, newNftTokenId, alice, bob, 1);
+ itSub('[fungible] Transfer with deleted collection_id', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-Neg-1-FT', description: '', tokenPrefix: 'T'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+
+ await collection.burnTokens(alice, 10n);
+ await collection.burn(alice);
+
+ await expect(collection.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
+
+ itSub.ifWithPallets('[refungible] Transfer with deleted collection_id', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-Neg-1-RFT', description: '', tokenPrefix: 'T'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
+
+ await rft.burn(alice, 10n);
+ await collection.burn(alice);
- it('[fungible] Transfer with deleted collection_id', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await burnItemExpectSuccess(alice, fungibleCollectionId, newFungibleTokenId, 10);
- await destroyCollectionExpectSuccess(fungibleCollectionId);
- await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, alice, bob, 1);
+ await expect(rft.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
});
- it('[refungible] Transfer with deleted collection_id', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
-
- const reFungibleCollectionId = await
- createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await burnItemExpectSuccess(alice, reFungibleCollectionId, newReFungibleTokenId, 100);
- await destroyCollectionExpectSuccess(reFungibleCollectionId);
- await transferExpectFailure(
- reFungibleCollectionId,
- newReFungibleTokenId,
- alice,
- bob,
- 1,
- );
+ itSub('[nft] Transfer with not existed item_id', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-2-NFT', description: '', tokenPrefix: 'T'});
+ await expect(collection.transferToken(alice, 1, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenNotFound/);
});
- it('[nft] Transfer with not existed item_id', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- await transferExpectFailure(nftCollectionId, 2, alice, bob, 1);
+ itSub('[fungible] Transfer with not existed item_id', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-Neg-2-FT', description: '', tokenPrefix: 'T'});
+ await expect(collection.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('[fungible] Transfer with not existed item_id', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await transferExpectFailure(fungibleCollectionId, 2, alice, bob, 1);
+ itSub.ifWithPallets('[refungible] Transfer with not existed item_id', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-Neg-2-RFT', description: '', tokenPrefix: 'T'});
+ await expect(collection.transferToken(alice, 1, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('[refungible] Transfer with not existed item_id', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub('[nft] Transfer with deleted item_id', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await nft.burn(alice);
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await transferExpectFailure(
- reFungibleCollectionId,
- 2,
- alice,
- bob,
- 1,
- );
+ await expect(nft.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenNotFound/);
});
- it('[nft] Transfer with deleted item_id', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await burnItemExpectSuccess(alice, nftCollectionId, newNftTokenId, 1);
- await transferExpectFailure(nftCollectionId, newNftTokenId, alice, bob, 1);
- });
+ itSub('[fungible] Transfer with deleted item_id', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-Neg-3-FT', description: '', tokenPrefix: 'T'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+
+ await collection.burnTokens(alice, 10n);
- it('[fungible] Transfer with deleted item_id', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await burnItemExpectSuccess(alice, fungibleCollectionId, newFungibleTokenId, 10);
- await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, alice, bob, 1);
+ await expect(collection.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('[refungible] Transfer with deleted item_id', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] Transfer with deleted item_id', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-Neg-3-RFT', description: '', tokenPrefix: 'T'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
+
+ await rft.burn(alice, 10n);
- const reFungibleCollectionId = await
- createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await burnItemExpectSuccess(alice, reFungibleCollectionId, newReFungibleTokenId, 100);
- await transferExpectFailure(
- reFungibleCollectionId,
- newReFungibleTokenId,
- alice,
- bob,
- 1,
- );
+ await expect(rft.transfer(alice, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('[nft] Transfer with recipient that is not owner', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await transferExpectFailure(nftCollectionId, newNftTokenId, charlie, bob, 1);
+ itSub('[nft] Transfer with recipient that is not owner', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-4-NFT', description: '', tokenPrefix: 'T'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await expect(nft.transfer(bob, {Substrate: bob.address}))
+ .to.be.rejectedWith(/common\.NoPermission/);
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('[fungible] Transfer with recipient that is not owner', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, charlie, bob, 1);
+ itSub('[fungible] Transfer with recipient that is not owner', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'Transfer-Neg-4-FT', description: '', tokenPrefix: 'T'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+
+ await expect(collection.transfer(bob, {Substrate: bob.address}, 9n))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(0n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(10n);
});
- it('[refungible] Transfer with recipient that is not owner', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] Transfer with recipient that is not owner', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-1-RFT', description: '', tokenPrefix: 'T'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await transferExpectFailure(
- reFungibleCollectionId,
- newReFungibleTokenId,
- charlie,
- bob,
- 1,
- );
+ await expect(rft.transfer(bob, {Substrate: bob.address}, 9n))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.equal(0n);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.equal(10n);
});
});
-describe('Zero value transfer(From)', () => {
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
+describe('Transfers to self (potentially over substrate-evm boundary)', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_, privateKey) => {
+ donor = privateKey('//Alice');
});
});
+
+ itEth('Transfers to self. In case of same frontend', async ({helper}) => {
+ const [owner] = await helper.arrange.createAccounts([10n], donor);
+ const collection = await helper.ft.mintCollection(owner, {});
+ await collection.mint(owner, {Substrate: owner.address}, 100n);
- it('NFT', async () => {
- await usingApi(async (api: ApiPromise) => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
+ const ownerProxy = helper.address.substrateToEth(owner.address);
- const transferTx = api.tx.unique.transfer(normalizeAccountId(bob), nftCollectionId, newNftTokenId, 0);
- await submitTransactionAsync(alice, transferTx);
- const address = normalizeAccountId(await getTokenOwner(api, nftCollectionId, newNftTokenId));
+ // transfer to own proxy
+ await collection.transfer(owner, {Ethereum: ownerProxy}, 10n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(90n);
+ expect(await collection.getBalance({Ethereum: ownerProxy})).to.be.equal(10n);
- expect(toSubstrateAddress(address)).to.be.equal(alice.address);
- });
+ // transfer-from own proxy to own proxy again
+ await collection.transferFrom(owner, {Ethereum: ownerProxy}, {Ethereum: ownerProxy}, 5n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(90n);
+ expect(await collection.getBalance({Ethereum: ownerProxy})).to.be.equal(10n);
});
- it('RFT', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itEth('Transfers to self. In case of substrate-evm boundary', async ({helper}) => {
+ const [owner] = await helper.arrange.createAccounts([10n], donor);
+ const collection = await helper.ft.mintCollection(owner, {});
+ await collection.mint(owner, {Substrate: owner.address}, 100n);
- await usingApi(async (api: ApiPromise) => {
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- const balanceBeforeAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
- const balanceBeforeBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
-
- const transferTx = api.tx.unique.transfer(normalizeAccountId(bob), reFungibleCollectionId, newReFungibleTokenId, 0);
- await submitTransactionAsync(alice, transferTx);
+ const ownerProxy = helper.address.substrateToEth(owner.address);
- const balanceAfterAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
- const balanceAfterBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
+ // transfer to own proxy
+ await collection.transfer(owner, {Ethereum: ownerProxy}, 10n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(90n);
+ expect(await collection.getBalance({Ethereum: ownerProxy})).to.be.equal(10n);
- expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
- expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
- });
+ // transfer-from own proxy to self
+ await collection.transferFrom(owner, {Ethereum: ownerProxy}, {Substrate: owner.address}, 5n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(95n);
+ expect(await collection.getBalance({Ethereum: ownerProxy})).to.be.equal(5n);
});
-
- it('Fungible', async () => {
- await usingApi(async (api: ApiPromise) => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- const balanceBeforeAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
- const balanceBeforeBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
-
- const transferTx = api.tx.unique.transfer(normalizeAccountId(bob), fungibleCollectionId, newFungibleTokenId, 0);
- await submitTransactionAsync(alice, transferTx);
- const balanceAfterAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
- const balanceAfterBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
+ itEth('Transfers to self. In case of inside substrate-evm', async ({helper}) => {
+ const [owner] = await helper.arrange.createAccounts([10n], donor);
+ const collection = await helper.ft.mintCollection(owner, {});
+ await collection.mint(owner, {Substrate: owner.address}, 100n);
- expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
- expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
- });
- });
-});
+ // transfer to self again
+ await collection.transfer(owner, {Substrate: owner.address}, 10n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(100n);
-describe('Transfers to self (potentially over substrate-evm boundary)', () => {
- itWeb3('Transfers to self. In case of same frontend', async ({api, privateKeyWrapper}) => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const aliceProxy = subToEth(alice.address);
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
- await transferExpectSuccess(collectionId, tokenId, alice, {Ethereum: aliceProxy}, 10, 'Fungible');
- const balanceAliceBefore = await getTokenBalance(api, collectionId, {Ethereum: aliceProxy}, tokenId);
- await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: aliceProxy}, {Ethereum: aliceProxy}, 10, 'Fungible');
- const balanceAliceAfter = await getTokenBalance(api, collectionId, {Ethereum: aliceProxy}, tokenId);
- expect(balanceAliceBefore).to.be.eq(balanceAliceAfter);
+ // transfer-from self to self again
+ await collection.transferFrom(owner, {Substrate: owner.address}, {Substrate: owner.address}, 5n);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(100n);
});
- itWeb3('Transfers to self. In case of substrate-evm boundary', async ({api, privateKeyWrapper}) => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const aliceProxy = subToEth(alice.address);
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
- const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- await transferExpectSuccess(collectionId, tokenId, alice, {Ethereum: aliceProxy} , 10, 'Fungible');
- await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: aliceProxy}, alice, 10, 'Fungible');
- const balanceAliceAfter = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- expect(balanceAliceBefore).to.be.eq(balanceAliceAfter);
- });
+ itEth('Transfers to self. In case of inside substrate-evm when not enought "Fungibles"', async ({helper}) => {
+ const [owner] = await helper.arrange.createAccounts([10n], donor);
+ const collection = await helper.ft.mintCollection(owner, {});
+ await collection.mint(owner, {Substrate: owner.address}, 10n);
- itWeb3('Transfers to self. In case of inside substrate-evm', async ({api, privateKeyWrapper}) => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
- const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- await transferExpectSuccess(collectionId, tokenId, alice, alice , 10, 'Fungible');
- await transferFromExpectSuccess(collectionId, tokenId, alice, alice, alice, 10, 'Fungible');
- const balanceAliceAfter = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- expect(balanceAliceBefore).to.be.eq(balanceAliceAfter);
- });
+ // transfer to self again
+ await expect(collection.transfer(owner, {Substrate: owner.address}, 11n))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
- itWeb3('Transfers to self. In case of inside substrate-evm when not enought "Fungibles"', async ({api, privateKeyWrapper}) => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
- const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- await transferExpectFailure(collectionId, tokenId, alice, alice , 11);
- await transferFromExpectFail(collectionId, tokenId, alice, alice, alice, 11);
- const balanceAliceAfter = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
- expect(balanceAliceBefore).to.be.eq(balanceAliceAfter);
+ // transfer-from self to self again
+ await expect(collection.transferFrom(owner, {Substrate: owner.address}, {Substrate: owner.address}, 12n))
+ .to.be.rejectedWith(/common\.TokenValueTooLow/);
+ expect(await collection.getBalance({Substrate: owner.address})).to.be.equal(10n);
});
});
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -14,26 +14,10 @@
// 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 {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
-import {
- approveExpectFail,
- approveExpectSuccess,
- createCollectionExpectSuccess,
- createFungibleItemExpectSuccess,
- createItemExpectSuccess,
- getAllowance,
- transferFromExpectFail,
- transferFromExpectSuccess,
- burnItemExpectSuccess,
- setCollectionLimitsExpectSuccess,
- getCreatedCollectionCount,
- requirePallets,
- Pallets,
-} from './util/helpers';
+import {itSub, Pallets, usingPlaygrounds} from './util/playgrounds';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -44,67 +28,64 @@
let charlie: IKeyringPair;
before(async () => {
- await usingApi(async (api, 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([20n, 10n, 10n], donor);
});
});
- it('[nft] Execute the extrinsic and check nftItemList - owner of token', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await approveExpectSuccess(nftCollectionId, newNftTokenId, alice, bob.address);
+ itSub('[nft] Execute the extrinsic and check nftItemList - owner of token', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-1', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+ await nft.approve(alice, {Substrate: bob.address});
+ expect(await nft.isApproved({Substrate: bob.address})).to.be.true;
- await transferFromExpectSuccess(nftCollectionId, newNftTokenId, bob, alice, charlie, 1, 'NFT');
+ await nft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address});
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: charlie.address});
});
- it('[fungible] Execute the extrinsic and check nftItemList - owner of token', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address);
- await transferFromExpectSuccess(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 1, 'Fungible');
+ itSub('[fungible] Execute the extrinsic and check nftItemList - owner of token', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-2', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+ await collection.approveTokens(alice, {Substrate: bob.address}, 7n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(7n);
+
+ await collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 6n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.be.equal(6n);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(4n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(1n);
});
- it('[refungible] Execute the extrinsic and check nftItemList - owner of token', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
-
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address, 100);
- await transferFromExpectSuccess(
- reFungibleCollectionId,
- newReFungibleTokenId,
- bob,
- alice,
- charlie,
- 100,
- 'ReFungible',
- );
+ itSub.ifWithPallets('[refungible] Execute the extrinsic and check nftItemList - owner of token', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-3', description: '', tokenPrefix: 'TF'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
+ await rft.approve(alice, {Substrate: bob.address}, 7n);
+ expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(7n);
+
+ await rft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 6n);
+ expect(await rft.getBalance({Substrate: charlie.address})).to.be.equal(6n);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.equal(4n);
+ expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(1n);
});
- it('Should reduce allowance if value is big', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
- const charlie = privateKeyWrapper('//Charlie');
+ itSub('Should reduce allowance if value is big', async ({helper}) => {
+ // fungible
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-4', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 500000n);
- // fungible
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: 500000n});
-
- await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address, 500000n);
- await transferFromExpectSuccess(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 500000n, 'Fungible');
- expect(await getAllowance(api, fungibleCollectionId, alice.address, bob.address, newFungibleTokenId)).to.equal(0n);
- });
+ await collection.approveTokens(alice, {Substrate: bob.address}, 500000n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(500000n);
+ await collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 500000n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(0n);
});
- it('can be called by collection owner on non-owned item when OwnerCanTransfer == true', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionLimitsExpectSuccess(alice, collectionId, {ownerCanTransfer: true});
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ itSub('can be called by collection owner on non-owned item when OwnerCanTransfer == true', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-5', description: '', tokenPrefix: 'TF'});
+ await collection.setLimits(alice, {ownerCanTransfer: true});
- await transferFromExpectSuccess(collectionId, itemId, alice, bob, charlie);
+ const nft = await collection.mintToken(alice, {Substrate: bob.address});
+ await nft.transferFrom(alice, {Substrate: bob.address}, {Substrate: charlie.address});
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: charlie.address});
});
});
@@ -114,245 +95,263 @@
let charlie: IKeyringPair;
before(async () => {
- await usingApi(async (api, 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('[nft] transferFrom for a collection that does not exist', async () => {
- await usingApi(async (api: ApiPromise) => {
- const nftCollectionCount = await getCreatedCollectionCount(api);
- await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
+ itSub('transferFrom for a collection that does not exist', async ({helper}) => {
+ const collectionId = (1 << 32) - 1;
+ await expect(helper.collection.approveToken(alice, collectionId, 0, {Substrate: bob.address}, 1n))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
+ await expect(helper.collection.transferTokenFrom(bob, collectionId, 0, {Substrate: alice.address}, {Substrate: bob.address}, 1n))
+ .to.be.rejectedWith(/common\.CollectionNotFound/);
+ });
+
+ /* itSub('transferFrom for a collection that was destroyed', async ({helper}) => {
+ this test copies approve negative test
+ }); */
+
+ /* itSub('transferFrom a token that does not exist', async ({helper}) => {
+ this test copies approve negative test
+ }); */
+
+ /* itSub('transferFrom a token that was deleted', async ({helper}) => {
+ this test copies approve negative test
+ }); */
+
+ itSub('[nft] transferFrom for not approved address', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-1', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await expect(nft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
+ });
+
+ itSub('[fungible] transferFrom for not approved address', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-Neg-1', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
- await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
- });
+ await expect(collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 5n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.deep.equal(10n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
});
- it('[fungible] transferFrom for a collection that does not exist', async () => {
- await usingApi(async (api: ApiPromise) => {
- const fungibleCollectionCount = await getCreatedCollectionCount(api);
- await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
+ itSub.ifWithPallets('[refungible] transferFrom for not approved address', [Pallets.ReFungible], async({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-Neg-3', description: '', tokenPrefix: 'TF'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
- await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
- });
+ await expect(rft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.deep.equal(10n);
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await rft.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
});
- it('[refungible] transferFrom for a collection that does not exist', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub('[nft] transferFrom incorrect token count', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-4', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
- await usingApi(async (api: ApiPromise) => {
- const reFungibleCollectionCount = await getCreatedCollectionCount(api);
- await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
+ await nft.approve(alice, {Substrate: bob.address});
+ expect(await nft.isApproved({Substrate: bob.address})).to.be.true;
- await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
- });
+ await expect(helper.collection.transferTokenFrom(
+ bob,
+ collection.collectionId,
+ nft.tokenId,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ 2n,
+ )).to.be.rejectedWith(/nonfungible\.NonfungibleItemsHaveNoAmount/);
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- /* it('transferFrom for a collection that was destroyed', async () => {
- await usingApi(async (api: ApiPromise) => {
- this test copies approve negative test
- });
- }); */
+ itSub('[fungible] transferFrom incorrect token count', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-Neg-5', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
- /* it('transferFrom a token that does not exist', async () => {
- await usingApi(async (api: ApiPromise) => {
- this test copies approve negative test
- });
- }); */
+ await collection.approveTokens(alice, {Substrate: bob.address}, 2n);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(2n);
- /* it('transferFrom a token that was deleted', async () => {
- await usingApi(async (api: ApiPromise) => {
- this test copies approve negative test
- });
- }); */
+ await expect(collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 5n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.deep.equal(10n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
+ });
- it('[nft] transferFrom for not approved address', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
+ itSub.ifWithPallets('[refungible] transferFrom incorrect token count', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-Neg-6', description: '', tokenPrefix: 'TF'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, bob, alice, charlie, 1);
- });
+ await rft.approve(alice, {Substrate: bob.address}, 5n);
+ expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(5n);
- it('[fungible] transferFrom for not approved address', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 1);
+ await expect(rft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 7n))
+ .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.deep.equal(10n);
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await rft.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
});
- it('[refungible] transferFrom for not approved address', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub('[nft] execute transferFrom from account that is not owner of collection', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-7', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
- const reFungibleCollectionId = await
- createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await transferFromExpectFail(
- reFungibleCollectionId,
- newReFungibleTokenId,
- bob,
- alice,
+ await expect(nft.approve(charlie, {Substrate: bob.address})).to.be.rejectedWith(/common\.CantApproveMoreThanOwned/);
+ expect(await nft.isApproved({Substrate: bob.address})).to.be.false;
+
+ await expect(nft.transferFrom(
charlie,
- 1,
- );
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- it('[nft] transferFrom incorrect token count', async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await approveExpectSuccess(nftCollectionId, newNftTokenId, alice, bob.address);
+ itSub('[fungible] execute transferFrom from account that is not owner of collection', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-Neg-8', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 10000n);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, bob, alice, charlie, 2);
- });
+ await expect(collection.approveTokens(charlie, {Substrate: bob.address}, 1n)).to.be.rejectedWith(/common\.CantApproveMoreThanOwned/);
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(0n);
+ expect(await collection.getApprovedTokens({Substrate: charlie.address}, {Substrate: bob.address})).to.be.eq(0n);
- it('[fungible] transferFrom incorrect token count', async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address);
- await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 2);
+ await expect(collection.transferFrom(
+ charlie,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await collection.getBalance({Substrate: alice.address})).to.be.deep.equal(10000n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
});
- it('[refungible] transferFrom incorrect token count', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('[refungible] execute transferFrom from account that is not owner of collection', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-Neg-9', description: '', tokenPrefix: 'TF'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10000n);
+
+ await expect(rft.approve(charlie, {Substrate: bob.address}, 1n)).to.be.rejectedWith(/common\.CantApproveMoreThanOwned/);
+ expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(0n);
+ expect(await rft.getApprovedPieces({Substrate: charlie.address}, {Substrate: bob.address})).to.be.eq(0n);
- const reFungibleCollectionId = await
- createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address);
- await transferFromExpectFail(
- reFungibleCollectionId,
- newReFungibleTokenId,
- bob,
- alice,
+ await expect(rft.transferFrom(
charlie,
- 2,
- );
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+ expect(await rft.getBalance({Substrate: alice.address})).to.be.deep.equal(10000n);
+ expect(await rft.getBalance({Substrate: bob.address})).to.be.deep.equal(0n);
+ expect(await rft.getBalance({Substrate: charlie.address})).to.be.deep.equal(0n);
});
- it('[nft] execute transferFrom from account that is not owner of collection', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const dave = privateKeyWrapper('//Dave');
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- try {
- await approveExpectFail(nftCollectionId, newNftTokenId, dave, bob);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, dave, alice, charlie, 1);
- } catch (e) {
- // tslint:disable-next-line:no-unused-expression
- expect(e).to.be.exist;
- }
+ itSub('transferFrom burnt token before approve NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-10', description: '', tokenPrefix: 'TF'});
+ await collection.setLimits(alice, {ownerCanTransfer: true});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
+
+ await nft.burn(alice);
+ await expect(nft.approve(alice, {Substrate: bob.address})).to.be.rejectedWith(/common\.TokenNotFound/);
- // await transferFromExpectFail(nftCollectionId, newNftTokenId, Dave, Alice, Charlie, 1);
- });
+ await expect(nft.transferFrom(
+ bob,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
- it('[fungible] execute transferFrom from account that is not owner of collection', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const dave = privateKeyWrapper('//Dave');
+ itSub('transferFrom burnt token before approve Fungible', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-Neg-11', description: '', tokenPrefix: 'TF'});
+ await collection.setLimits(alice, {ownerCanTransfer: true});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- try {
- await approveExpectFail(fungibleCollectionId, newFungibleTokenId, dave, bob);
- await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, dave, alice, charlie, 1);
- } catch (e) {
- // tslint:disable-next-line:no-unused-expression
- expect(e).to.be.exist;
- }
- });
+ await collection.burnTokens(alice, 10n);
+ await expect(collection.approveTokens(alice, {Substrate: bob.address})).to.be.not.rejected;
+
+ await expect(collection.transferFrom(
+ alice,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('[refungible] execute transferFrom from account that is not owner of collection', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
+ itSub.ifWithPallets('transferFrom burnt token before approve ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-Neg-12', description: '', tokenPrefix: 'TF'});
+ await collection.setLimits(alice, {ownerCanTransfer: true});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
- await usingApi(async (api, privateKeyWrapper) => {
- const dave = privateKeyWrapper('//Dave');
- const reFungibleCollectionId = await
- createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- try {
- await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, dave, bob);
- await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, dave, alice, charlie, 1);
- } catch (e) {
- // tslint:disable-next-line:no-unused-expression
- expect(e).to.be.exist;
- }
- });
- });
- it('transferFrom burnt token before approve NFT', async () => {
- await usingApi(async () => {
- // nft
- const nftCollectionId = await createCollectionExpectSuccess();
- await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {ownerCanTransfer: true});
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await burnItemExpectSuccess(alice, nftCollectionId, newNftTokenId, 1);
- await approveExpectFail(nftCollectionId, newNftTokenId, alice, bob);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, bob, alice, charlie, 1);
- });
- });
- it('transferFrom burnt token before approve Fungible', async () => {
- await usingApi(async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await setCollectionLimitsExpectSuccess(alice, fungibleCollectionId, {ownerCanTransfer: true});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await burnItemExpectSuccess(alice, fungibleCollectionId, newFungibleTokenId, 10);
- await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address);
- await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 1);
+ await rft.burn(alice, 10n);
+ await expect(rft.approve(alice, {Substrate: bob.address})).to.be.rejectedWith(/common\.CantApproveMoreThanOwned/);
- });
+ await expect(rft.transferFrom(
+ alice,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('transferFrom burnt token before approve ReFungible', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
- await usingApi(async () => {
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await setCollectionLimitsExpectSuccess(alice, reFungibleCollectionId, {ownerCanTransfer: true});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await burnItemExpectSuccess(alice, reFungibleCollectionId, newReFungibleTokenId, 100);
- await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, alice, bob);
- await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, alice, charlie, 1);
+ itSub('transferFrom burnt token after approve NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-13', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: alice.address});
- });
- });
+ await nft.approve(alice, {Substrate: bob.address});
+ expect(await nft.isApproved({Substrate: bob.address})).to.be.true;
- it('transferFrom burnt token after approve NFT', async () => {
- await usingApi(async () => {
- // nft
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await approveExpectSuccess(nftCollectionId, newNftTokenId, alice, bob.address);
- await burnItemExpectSuccess(alice, nftCollectionId, newNftTokenId, 1);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, bob, alice, charlie, 1);
- });
+ await nft.burn(alice);
+
+ await expect(nft.transferFrom(
+ bob,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
- it('transferFrom burnt token after approve Fungible', async () => {
- await usingApi(async () => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
- await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address);
- await burnItemExpectSuccess(alice, fungibleCollectionId, newFungibleTokenId, 10);
- await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, alice, charlie, 1);
- });
+ itSub('transferFrom burnt token after approve Fungible', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'TransferFrom-Neg-14', description: '', tokenPrefix: 'TF'});
+ await collection.mint(alice, {Substrate: alice.address}, 10n);
+
+ await collection.approveTokens(alice, {Substrate: bob.address});
+ expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(1n);
+
+ await collection.burnTokens(alice, 10n);
+
+ await expect(collection.transferFrom(
+ bob,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
- it('transferFrom burnt token after approve ReFungible', async function() {
- await requirePallets(this, [Pallets.ReFungible]);
- await usingApi(async () => {
- const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
- await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address);
- await burnItemExpectSuccess(alice, reFungibleCollectionId, newReFungibleTokenId, 100);
- await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, alice, charlie, 1);
+ itSub.ifWithPallets('transferFrom burnt token after approve ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'TransferFrom-Neg-15', description: '', tokenPrefix: 'TF'});
+ const rft = await collection.mintToken(alice, {Substrate: alice.address}, 10n);
+
+ await rft.approve(alice, {Substrate: bob.address}, 10n);
+ expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.eq(10n);
+
+ await rft.burn(alice, 10n);
- });
+ await expect(rft.transferFrom(
+ bob,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
- it('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
- await setCollectionLimitsExpectSuccess(alice, collectionId, {ownerCanTransfer: false});
+ itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'TransferFrom-Neg-16', description: '', tokenPrefix: 'TF'});
+ const nft = await collection.mintToken(alice, {Substrate: bob.address});
- await transferFromExpectFail(collectionId, itemId, alice, bob, charlie);
+ await collection.setLimits(alice, {ownerCanTransfer: false});
+
+ await expect(nft.transferFrom(
+ alice,
+ {Substrate: bob.address},
+ {Substrate: charlie.address},
+ )).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
});
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 // If ith character is 8 to f then make it uppercase33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getNestingTokenAddress(collectionId: number, tokenId: number) {59 return nesting.tokenIdToAddress(collectionId, tokenId);60 }6162 static getDefaultLogger(): ILogger {63 return {64 log(msg: any, level = 'INFO') {65 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66 },67 level: {68 ERROR: 'ERROR',69 WARNING: 'WARNING',70 INFO: 'INFO',71 },72 };73 }7475 static vec2str(arr: string[] | number[]) {76 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77 }7879 static str2vec(string: string) {80 if (typeof string !== 'string') return string;81 return Array.from(string).map(x => x.charCodeAt(0));82 }8384 static fromSeed(seed: string, ss58Format = 42) {85 const keyring = new Keyring({type: 'sr25519', ss58Format});86 return keyring.addFromUri(seed);87 }8889 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');96 }9798 let collectionId = null;99 creationResult.result.events.forEach(({event: {data, method, section}}) => {100 if ((section === 'common') && (method === 'CollectionCreated')) {101 collectionId = parseInt(data[0].toString(), 10);102 }103 });104105 if (collectionId === null) {106 throw Error('No CollectionCreated event was found!');107 }108109 return collectionId;110 }111112 static extractTokensFromCreationResult(creationResult: ITransactionResult) {113 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 throw Error('Unable to create tokens!');115 }116 let success = false;117 const tokens = [] as any;118 creationResult.result.events.forEach(({event: {data, method, section}}) => {119 if (method === 'ExtrinsicSuccess') {120 success = true;121 } else if ((section === 'common') && (method === 'ItemCreated')) {122 tokens.push({123 collectionId: parseInt(data[0].toString(), 10),124 tokenId: parseInt(data[1].toString(), 10),125 owner: data[2].toJSON(),126 });127 }128 });129 return {success, tokens};130 }131132 static extractTokensFromBurnResult(burnResult: ITransactionResult) {133 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 throw Error('Unable to burn tokens!');135 }136 let success = false;137 const tokens = [] as any;138 burnResult.result.events.forEach(({event: {data, method, section}}) => {139 if (method === 'ExtrinsicSuccess') {140 success = true;141 } else if ((section === 'common') && (method === 'ItemDestroyed')) {142 tokens.push({143 collectionId: parseInt(data[0].toString(), 10),144 tokenId: parseInt(data[1].toString(), 10),145 owner: data[2].toJSON(),146 });147 }148 });149 return {success, tokens};150 }151152 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153 let eventId = null;154 events.forEach(({event: {data, method, section}}) => {155 if ((section === expectedSection) && (method === expectedMethod)) {156 eventId = parseInt(data[0].toString(), 10);157 }158 });159160 if (eventId === null) {161 throw Error(`No ${expectedMethod} event was found!`);162 }163 return eventId === collectionId;164 }165166 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167 const normalizeAddress = (address: string | ICrossAccountId) => {168 if(typeof address === 'string') return address;169 const obj = {} as any;170 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175 return address;176 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178 events.forEach(({event: {data, method, section}}) => {179 if ((section === 'common') && (method === 'Transfer')) {180 const hData = (data as any).toJSON();181 transfer = {182 collectionId: hData[0],183 tokenId: hData[1],184 from: normalizeAddress(hData[2]),185 to: normalizeAddress(hData[3]),186 amount: BigInt(hData[4]),187 };188 }189 });190 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193 isSuccess = isSuccess && amount === transfer.amount;194 return isSuccess;195 }196}197198199class ChainHelperBase {200 transactionStatus = UniqueUtil.transactionStatus;201 chainLogType = UniqueUtil.chainLogType;202 util: typeof UniqueUtil;203 logger: ILogger;204 api: ApiPromise | null;205 forcedNetwork: TUniqueNetworks | null;206 network: TUniqueNetworks | null;207 chainLog: IUniqueHelperLog[];208209 constructor(logger?: ILogger) {210 this.util = UniqueUtil;211 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();212 this.logger = logger;213 this.api = null;214 this.forcedNetwork = null;215 this.network = null;216 this.chainLog = [];217 }218219 clearChainLog(): void {220 this.chainLog = [];221 }222223 forceNetwork(value: TUniqueNetworks): void {224 this.forcedNetwork = value;225 }226227 async connect(wsEndpoint: string, listeners?: IApiListeners) {228 if (this.api !== null) throw Error('Already connected');229 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);230 this.api = api;231 this.network = network;232 }233234 async disconnect() {235 if (this.api === null) return;236 await this.api.disconnect();237 this.api = null;238 this.network = null;239 }240241 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {242 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;243 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;244 return 'opal';245 }246247 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {248 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});249 await api.isReady;250251 const network = await this.detectNetwork(api);252253 await api.disconnect();254255 return network;256 }257258 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 259 api: ApiPromise; 260 network: TUniqueNetworks; 261 }> {262 if(typeof network === 'undefined' || network === null) network = 'opal';263 const supportedRPC = {264 opal: {265 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,266 },267 quartz: {268 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,269 },270 unique: {271 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,272 },273 };274 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);275 const rpc = supportedRPC[network];276277 // TODO: investigate how to replace rpc in runtime278 // api._rpcCore.addUserInterfaces(rpc);279280 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});281282 await api.isReadyOrError;283284 if (typeof listeners === 'undefined') listeners = {};285 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {286 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;287 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);288 }289290 return {api, network};291 }292293 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {294 const {events, status} = data;295 if (status.isReady) {296 return this.transactionStatus.NOT_READY;297 }298 if (status.isBroadcast) {299 return this.transactionStatus.NOT_READY;300 }301 if (status.isInBlock || status.isFinalized) {302 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');303 if (errors.length > 0) {304 return this.transactionStatus.FAIL;305 }306 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {307 return this.transactionStatus.SUCCESS;308 }309 }310311 return this.transactionStatus.FAIL;312 }313314 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {315 const sign = (callback: any) => {316 if(options !== null) return transaction.signAndSend(sender, options, callback);317 return transaction.signAndSend(sender, callback);318 };319 // eslint-disable-next-line no-async-promise-executor320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 signer: this.getSignerAddress(sender),392 params,393 } as IUniqueHelperLog;394395 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;396 if(events.length > 0) log.events = events;397398 this.chainLog.push(log);399400 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);401 return result;402 }403404 async callRpc(rpc: string, params?: any[]) {405 if(typeof params === 'undefined') params = [];406 if(this.api === null) throw Error('API not initialized');407 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);408409 const startTime = (new Date()).getTime();410 let result;411 let error = null;412 const log = {413 type: this.chainLogType.RPC,414 call: rpc,415 params,416 } as IUniqueHelperLog;417418 try {419 result = await this.constructApiCall(rpc, params);420 }421 catch(e) {422 error = e;423 }424425 const endTime = (new Date()).getTime();426427 log.executedAt = endTime;428 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';429 log.executionTime = endTime - startTime;430431 this.chainLog.push(log);432433 if(error !== null) throw error;434435 return result;436 }437438 getSignerAddress(signer: IKeyringPair | string): string {439 if(typeof signer === 'string') return signer;440 return signer.address;441 }442443 fetchAllPalletNames(): string[] {444 if(this.api === null) throw Error('API not initialized');445 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());446 }447 448 fetchMissingPalletNames(requiredPallets: string[]): string[] {449 const palletNames = this.fetchAllPalletNames();450 return requiredPallets.filter(p => !palletNames.includes(p));451 }452}453454455class HelperGroup {456 helper: UniqueHelper;457458 constructor(uniqueHelper: UniqueHelper) {459 this.helper = uniqueHelper;460 }461}462463464class CollectionGroup extends HelperGroup {465 /**466 * Get number of blocks when sponsored transaction is available.467 *468 * @param collectionId ID of collection469 * @param tokenId ID of token470 * @param addressObj address for which the sponsorship is checked471 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});472 * @returns number of blocks or null if sponsorship hasn't been set473 */474 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {475 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();476 }477478 /**479 * Get the number of created collections.480 * 481 * @returns number of created collections482 */483 async getTotalCount(): Promise<number> {484 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();485 }486487 /**488 * Get information about the collection with additional data, 489 * including the number of tokens it contains, its administrators, 490 * the normalized address of the collection's owner, and decoded name and description.491 * 492 * @param collectionId ID of collection493 * @example await getData(2)494 * @returns collection information object495 */496 async getData(collectionId: number): Promise<{497 id: number;498 name: string;499 description: string;500 tokensCount: number;501 admins: ICrossAccountId[];502 normalizedOwner: TSubstrateAccount;503 raw: any504 } | null> {505 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);506 const humanCollection = collection.toHuman(), collectionData = {507 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],508 raw: humanCollection,509 } as any, jsonCollection = collection.toJSON();510 if (humanCollection === null) return null;511 collectionData.raw.limits = jsonCollection.limits;512 collectionData.raw.permissions = jsonCollection.permissions;513 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);514 for (const key of ['name', 'description']) {515 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);516 }517518 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) 519 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) 520 : 0;521 collectionData.admins = await this.getAdmins(collectionId);522523 return collectionData;524 }525526 /**527 * Get the addresses of the collection's administrators, optionally normalized.528 * 529 * @param collectionId ID of collection530 * @param normalize whether to normalize the addresses to the default ss58 format531 * @example await getAdmins(1)532 * @returns array of administrators533 */534 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {535 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();536537 return normalize538 ? admins.map((address: any) => {539 return address.Substrate540 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}541 : address;542 }) 543 : admins;544 }545546 /**547 * Get the addresses added to the collection allow-list, optionally normalized.548 * @param collectionId ID of collection549 * @param normalize whether to normalize the addresses to the default ss58 format550 * @example await getAllowList(1)551 * @returns array of allow-listed addresses552 */553 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {554 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();555 return normalize556 ? allowListed.map((address: any) => {557 return address.Substrate558 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}559 : address;560 }) 561 : allowListed;562 }563564 /**565 * Get the effective limits of the collection instead of null for default values566 * 567 * @param collectionId ID of collection568 * @example await getEffectiveLimits(2)569 * @returns object of collection limits570 */571 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {572 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();573 }574575 /**576 * Burns the collection if the signer has sufficient permissions and collection is empty.577 * 578 * @param signer keyring of signer579 * @param collectionId ID of collection580 * @example await helper.collection.burn(aliceKeyring, 3);581 * @returns ```true``` if extrinsic success, otherwise ```false```582 */583 async burn(signer: TSigner, collectionId: number): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.destroyCollection', [collectionId],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');591 }592593 /**594 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.595 * 596 * @param signer keyring of signer597 * @param collectionId ID of collection598 * @param sponsorAddress Sponsor substrate address599 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")600 * @returns ```true``` if extrinsic success, otherwise ```false```601 */602 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {603 const result = await this.helper.executeExtrinsic(604 signer,605 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],606 true,607 );608609 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');610 }611612 /**613 * Confirms consent to sponsor the collection on behalf of the signer.614 * 615 * @param signer keyring of signer616 * @param collectionId ID of collection617 * @example confirmSponsorship(aliceKeyring, 10)618 * @returns ```true``` if extrinsic success, otherwise ```false```619 */620 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {621 const result = await this.helper.executeExtrinsic(622 signer,623 'api.tx.unique.confirmSponsorship', [collectionId],624 true,625 );626627 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');628 }629630 /**631 * Removes the sponsor of a collection, regardless if it consented or not.632 * 633 * @param signer keyring of signer634 * @param collectionId ID of collection635 * @example removeSponsor(aliceKeyring, 10)636 * @returns ```true``` if extrinsic success, otherwise ```false```637 */638 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {639 const result = await this.helper.executeExtrinsic(640 signer,641 'api.tx.unique.removeCollectionSponsor', [collectionId],642 true,643 );644645 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');646 }647648 /**649 * Sets the limits of the collection. At least one limit must be specified for a correct call.650 * 651 * @param signer keyring of signer652 * @param collectionId ID of collection653 * @param limits collection limits object654 * @example655 * await setLimits(656 * aliceKeyring,657 * 10,658 * {659 * sponsorTransferTimeout: 0,660 * ownerCanDestroy: false661 * }662 * )663 * @returns ```true``` if extrinsic success, otherwise ```false```664 */665 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {666 const result = await this.helper.executeExtrinsic(667 signer,668 'api.tx.unique.setCollectionLimits', [collectionId, limits],669 true,670 );671672 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');673 }674675 /**676 * Changes the owner of the collection to the new Substrate address.677 * 678 * @param signer keyring of signer679 * @param collectionId ID of collection680 * @param ownerAddress substrate address of new owner681 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")682 * @returns ```true``` if extrinsic success, otherwise ```false```683 */684 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {685 const result = await this.helper.executeExtrinsic(686 signer,687 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],688 true,689 );690691 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');692 }693694 /**695 * Adds a collection administrator. 696 * 697 * @param signer keyring of signer698 * @param collectionId ID of collection699 * @param adminAddressObj Administrator address (substrate or ethereum)700 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})701 * @returns ```true``` if extrinsic success, otherwise ```false```702 */703 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {704 const result = await this.helper.executeExtrinsic(705 signer,706 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],707 true,708 );709710 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');711 }712713 /**714 * Removes a collection administrator.715 * 716 * @param signer keyring of signer717 * @param collectionId ID of collection718 * @param adminAddressObj Administrator address (substrate or ethereum)719 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})720 * @returns ```true``` if extrinsic success, otherwise ```false```721 */722 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');730 }731732 /**733 * Adds an address to allow list 734 * @param signer keyring of signer735 * @param collectionId ID of collection736 * @param addressObj address to add to the allow list737 * @returns ```true``` if extrinsic success, otherwise ```false```738 */739 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.addToAllowList', [collectionId, addressObj],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');747 }748749 /**750 * Removes an address from allow list 751 * 752 * @param signer keyring of signer753 * @param collectionId ID of collection754 * @param addressObj address to remove from the allow list755 * @returns ```true``` if extrinsic success, otherwise ```false```756 */757 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {758 const result = await this.helper.executeExtrinsic(759 signer,760 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],761 true,762 );763764 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');765 }766767 /**768 * Sets onchain permissions for selected collection.769 * 770 * @param signer keyring of signer771 * @param collectionId ID of collection772 * @param permissions collection permissions object773 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});774 * @returns ```true``` if extrinsic success, otherwise ```false```775 */776 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {777 const result = await this.helper.executeExtrinsic(778 signer,779 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],780 true,781 );782783 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');784 }785786 /**787 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.788 * 789 * @param signer keyring of signer790 * @param collectionId ID of collection791 * @param permissions nesting permissions object792 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});793 * @returns ```true``` if extrinsic success, otherwise ```false```794 */795 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {796 return await this.setPermissions(signer, collectionId, {nesting: permissions});797 }798799 /**800 * Disables nesting for selected collection.801 * 802 * @param signer keyring of signer803 * @param collectionId ID of collection804 * @example disableNesting(aliceKeyring, 10);805 * @returns ```true``` if extrinsic success, otherwise ```false```806 */807 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {808 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});809 }810811 /**812 * Sets onchain properties to the collection.813 * 814 * @param signer keyring of signer815 * @param collectionId ID of collection816 * @param properties array of property objects817 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);818 * @returns ```true``` if extrinsic success, otherwise ```false```819 */820 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {821 const result = await this.helper.executeExtrinsic(822 signer,823 'api.tx.unique.setCollectionProperties', [collectionId, properties],824 true,825 );826827 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');828 }829830 /**831 * Deletes onchain properties from the collection.832 * 833 * @param signer keyring of signer834 * @param collectionId ID of collection835 * @param propertyKeys array of property keys to delete836 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);837 * @returns ```true``` if extrinsic success, otherwise ```false```838 */839 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {840 const result = await this.helper.executeExtrinsic(841 signer,842 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],843 true,844 );845846 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');847 }848849 /**850 * Changes the owner of the token.851 * 852 * @param signer keyring of signer853 * @param collectionId ID of collection854 * @param tokenId ID of token855 * @param addressObj address of a new owner856 * @param amount amount of tokens to be transfered. For NFT must be set to 1n857 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})858 * @returns true if the token success, otherwise false859 */860 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],864 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,865 );866867 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);868 }869870 /**871 * 872 * Change ownership of a token(s) on behalf of the owner. 873 * 874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param tokenId ID of token877 * @param fromAddressObj address on behalf of which the token will be sent878 * @param toAddressObj new token owner879 * @param amount amount of tokens to be transfered. For NFT must be set to 1n880 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})881 * @returns true if the token success, otherwise false882 */883 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {884 const result = await this.helper.executeExtrinsic(885 signer,886 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],887 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,888 );889 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);890 }891892 /**893 * 894 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.895 * 896 * @param signer keyring of signer897 * @param collectionId ID of collection898 * @param tokenId ID of token899 * @param amount amount of tokens to be burned. For NFT must be set to 1n900 * @example burnToken(aliceKeyring, 10, 5);901 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```902 */903 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{904 success: boolean,905 token: number | null906 }> {907 const burnResult = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.burnItem', [collectionId, tokenId, amount],910 true, // `Unable to burn token for ${label}`,911 );912 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);913 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');914 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};915 }916917 /**918 * Destroys a concrete instance of NFT on behalf of the owner919 * 920 * @param signer keyring of signer921 * @param collectionId ID of collection922 * @param fromAddressObj address on behalf of which the token will be burnt923 * @param tokenId ID of token924 * @param amount amount of tokens to be burned. For NFT must be set to 1n925 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})926 * @returns ```true``` if extrinsic success, otherwise ```false```927 */928 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {929 const burnResult = await this.helper.executeExtrinsic(930 signer,931 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],932 true, // `Unable to burn token from for ${label}`,933 );934 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);935 return burnedTokens.success && burnedTokens.tokens.length > 0;936 }937938 /**939 * Set, change, or remove approved address to transfer the ownership of the NFT.940 * 941 * @param signer keyring of signer942 * @param collectionId ID of collection943 * @param tokenId ID of token944 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens945 * @param amount amount of token to be approved. For NFT must be set to 1n946 * @returns ```true``` if extrinsic success, otherwise ```false```947 */948 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {949 const approveResult = await this.helper.executeExtrinsic(950 signer, 951 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],952 true, // `Unable to approve token for ${label}`,953 );954955 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');956 }957958 /**959 * Get the amount of token pieces approved to transfer or burn. Normally 0.960 * 961 * @param collectionId ID of collection962 * @param tokenId ID of token963 * @param toAccountObj address which is approved to use token pieces964 * @param fromAccountObj address which may have allowed the use of its owned tokens965 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})966 * @returns number of approved to transfer pieces967 */968 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {969 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();970 }971972 /**973 * Get the last created token ID in a collection974 * 975 * @param collectionId ID of collection976 * @example getLastTokenId(10);977 * @returns id of the last created token978 */979 async getLastTokenId(collectionId: number): Promise<number> {980 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();981 }982983 /**984 * Check if token exists985 * 986 * @param collectionId ID of collection987 * @param tokenId ID of token988 * @example isTokenExists(10, 20);989 * @returns true if the token exists, otherwise false990 */991 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {992 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();993 }994}995996class NFTnRFT extends CollectionGroup {997 /**998 * Get tokens owned by account999 * 1000 * @param collectionId ID of collection1001 * @param addressObj tokens owner1002 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1003 * @returns array of token ids owned by account1004 */1005 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1006 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1007 }10081009 /**1010 * Get token data1011 * 1012 * @param collectionId ID of collection1013 * @param tokenId ID of token1014 * @param propertyKeys optionally filter the token properties to only these keys1015 * @param blockHashAt optionally query the data at some block with this hash1016 * @example getToken(10, 5);1017 * @returns human readable token data 1018 */1019 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1020 properties: IProperty[];1021 owner: ICrossAccountId;1022 normalizedOwner: ICrossAccountId;1023 }| null> {1024 let tokenData;1025 if(typeof blockHashAt === 'undefined') {1026 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1027 }1028 else {1029 if(propertyKeys.length == 0) {1030 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 if(!collection) return null;1032 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1033 }1034 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1035 }1036 tokenData = tokenData.toHuman();1037 if (tokenData === null || tokenData.owner === null) return null;1038 const owner = {} as any;1039 for (const key of Object.keys(tokenData.owner)) {1040 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1041 }1042 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1043 return tokenData;1044 }10451046 /**1047 * Set permissions to change token properties1048 * 1049 * @param signer keyring of signer1050 * @param collectionId ID of collection1051 * @param permissions permissions to change a property by the collection owner or admin1052 * @example setTokenPropertyPermissions(1053 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1054 * )1055 * @returns true if extrinsic success otherwise false1056 */1057 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1058 const result = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1061 true,1062 );10631064 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1065 }10661067 /**1068 * Set token properties1069 * 1070 * @param signer keyring of signer1071 * @param collectionId ID of collection1072 * @param tokenId ID of token1073 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1074 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1075 * @returns ```true``` if extrinsic success, otherwise ```false```1076 */1077 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1078 const result = await this.helper.executeExtrinsic(1079 signer,1080 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1081 true,1082 );10831084 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1085 }10861087 /**1088 * Delete the provided properties of a token1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @param tokenId ID of token1092 * @param propertyKeys property keys to be deleted 1093 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1094 * @returns ```true``` if extrinsic success, otherwise ```false```1095 */1096 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1097 const result = await this.helper.executeExtrinsic(1098 signer,1099 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1100 true,1101 );11021103 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1104 }11051106 /**1107 * Mint new collection1108 * 1109 * @param signer keyring of signer1110 * @param collectionOptions basic collection options and properties 1111 * @param mode NFT or RFT type of a collection1112 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1113 * @returns object of the created collection1114 */1115 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1116 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1117 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1118 for (const key of ['name', 'description', 'tokenPrefix']) {1119 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1120 }1121 const creationResult = await this.helper.executeExtrinsic(1122 signer,1123 'api.tx.unique.createCollectionEx', [collectionOptions],1124 true, // errorLabel,1125 );1126 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1127 }11281129 getCollectionObject(_collectionId: number): any {1130 return null;1131 }11321133 getTokenObject(_collectionId: number, _tokenId: number): any {1134 return null;1135 }1136}113711381139class NFTGroup extends NFTnRFT {1140 /**1141 * Get collection object1142 * @param collectionId ID of collection1143 * @example getCollectionObject(2);1144 * @returns instance of UniqueNFTCollection1145 */1146 getCollectionObject(collectionId: number): UniqueNFTCollection {1147 return new UniqueNFTCollection(collectionId, this.helper);1148 }11491150 /**1151 * Get token object1152 * @param collectionId ID of collection1153 * @param tokenId ID of token1154 * @example getTokenObject(10, 5);1155 * @returns instance of UniqueNFTToken1156 */1157 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1158 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1159 }11601161 /**1162 * Get token's owner1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param blockHashAt optionally query the data at the block with this hash1166 * @example getTokenOwner(10, 5);1167 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1168 */1169 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1170 let owner;1171 if (typeof blockHashAt === 'undefined') {1172 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1173 } else {1174 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1175 }1176 return crossAccountIdFromLower(owner.toJSON());1177 }11781179 /**1180 * Is token approved to transfer1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param toAccountObj address to be approved1184 * @returns ```true``` if extrinsic success, otherwise ```false```1185 */1186 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1187 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1188 }11891190 /**1191 * Changes the owner of the token.1192 * 1193 * @param signer keyring of signer1194 * @param collectionId ID of collection1195 * @param tokenId ID of token1196 * @param addressObj address of a new owner1197 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1198 * @returns ```true``` if extrinsic success, otherwise ```false```1199 */1200 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1201 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1202 }12031204 /**1205 * 1206 * Change ownership of a NFT on behalf of the owner. 1207 * 1208 * @param signer keyring of signer1209 * @param collectionId ID of collection1210 * @param tokenId ID of token1211 * @param fromAddressObj address on behalf of which the token will be sent1212 * @param toAddressObj new token owner1213 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1214 * @returns ```true``` if extrinsic success, otherwise ```false```1215 */1216 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1217 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1218 }12191220 /**1221 * Recursively find the address that owns the token1222 * @param collectionId ID of collection1223 * @param tokenId ID of token1224 * @param blockHashAt 1225 * @example getTokenTopmostOwner(10, 5);1226 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1227 */1228 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1229 let owner;1230 if (typeof blockHashAt === 'undefined') {1231 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1232 } else {1233 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1234 }12351236 if (owner === null) return null;12371238 owner = owner.toHuman();12391240 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1241 }12421243 /**1244 * Get tokens nested in the provided token1245 * @param collectionId ID of collection1246 * @param tokenId ID of token1247 * @param blockHashAt optionally query the data at the block with this hash1248 * @example getTokenChildren(10, 5);1249 * @returns tokens whose depth of nesting is <= 5 1250 */1251 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1252 let children;1253 if(typeof blockHashAt === 'undefined') {1254 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1255 } else {1256 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1257 }12581259 return children.toJSON().map((x: any) => {1260 return {collectionId: x.collection, tokenId: x.token};1261 });1262 }12631264 /**1265 * Nest one token into another1266 * @param signer keyring of signer1267 * @param tokenObj token to be nested1268 * @param rootTokenObj token to be parent1269 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1270 * @returns ```true``` if extrinsic success, otherwise ```false```1271 */1272 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1273 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1274 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1275 if(!result) {1276 throw Error('Unable to nest token!');1277 }1278 return result;1279 }12801281 /**1282 * Remove token from nested state1283 * @param signer keyring of signer1284 * @param tokenObj token to unnest1285 * @param rootTokenObj parent of a token1286 * @param toAddressObj address of a new token owner 1287 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1288 * @returns ```true``` if extrinsic success, otherwise ```false```1289 */1290 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1291 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1292 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1293 if(!result) {1294 throw Error('Unable to unnest token!');1295 }1296 return result;1297 }12981299 /**1300 * Mint new collection1301 * @param signer keyring of signer1302 * @param collectionOptions Collection options1303 * @example 1304 * mintCollection(aliceKeyring, {1305 * name: 'New',1306 * description: 'New collection',1307 * tokenPrefix: 'NEW',1308 * })1309 * @returns object of the created collection1310 */1311 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1312 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1313 }13141315 /**1316 * Mint new token1317 * @param signer keyring of signer1318 * @param data token data1319 * @returns created token object1320 */1321 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1322 const creationResult = await this.helper.executeExtrinsic(1323 signer,1324 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1325 nft: {1326 properties: data.properties,1327 },1328 }],1329 true,1330 );1331 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1332 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1333 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1334 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1335 }13361337 /**1338 * Mint multiple NFT tokens1339 * @param signer keyring of signer1340 * @param collectionId ID of collection1341 * @param tokens array of tokens with owner and properties1342 * @example 1343 * mintMultipleTokens(aliceKeyring, 10, [{1344 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1345 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1346 * },{1347 * owner: {Ethereum: "0x9F0583DbB855d..."},1348 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1349 * }]);1350 * @returns ```true``` if extrinsic success, otherwise ```false```1351 */1352 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1353 const creationResult = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1356 true,1357 );1358 const collection = this.getCollectionObject(collectionId);1359 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1360 }13611362 /**1363 * Mint multiple NFT tokens with one owner1364 * @param signer keyring of signer1365 * @param collectionId ID of collection1366 * @param owner tokens owner1367 * @param tokens array of tokens with owner and properties1368 * @example1369 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1370 * properties: [{1371 * key: "gender",1372 * value: "female",1373 * },{1374 * key: "age",1375 * value: "33",1376 * }],1377 * }]);1378 * @returns array of newly created tokens1379 */1380 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1381 const rawTokens = [];1382 for (const token of tokens) {1383 const raw = {NFT: {properties: token.properties}};1384 rawTokens.push(raw);1385 }1386 const creationResult = await this.helper.executeExtrinsic(1387 signer,1388 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1389 true,1390 );1391 const collection = this.getCollectionObject(collectionId);1392 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1393 }13941395 /**1396 * Destroys a concrete instance of NFT.1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param tokenId ID of token1400 * @example burnToken(aliceKeyring, 10, 5);1401 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1402 */1403 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1404 return await super.burnToken(signer, collectionId, tokenId, 1n);1405 }14061407 /**1408 * Set, change, or remove approved address to transfer the ownership of the NFT.1409 * 1410 * @param signer keyring of signer1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param toAddressObj address to approve1414 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1415 * @returns ```true``` if extrinsic success, otherwise ```false```1416 */1417 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1418 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1419 }1420}142114221423class RFTGroup extends NFTnRFT {1424 /**1425 * Get collection object1426 * @param collectionId ID of collection1427 * @example getCollectionObject(2);1428 * @returns instance of UniqueRFTCollection1429 */1430 getCollectionObject(collectionId: number): UniqueRFTCollection {1431 return new UniqueRFTCollection(collectionId, this.helper);1432 }14331434 /**1435 * Get token object1436 * @param collectionId ID of collection1437 * @param tokenId ID of token1438 * @example getTokenObject(10, 5);1439 * @returns instance of UniqueNFTToken1440 */1441 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1442 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1443 }14441445 /**1446 * Get top 10 token owners with the largest number of pieces 1447 * @param collectionId ID of collection1448 * @param tokenId ID of token1449 * @example getTokenTop10Owners(10, 5);1450 * @returns array of top 10 owners1451 */1452 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1453 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1454 }14551456 /**1457 * Get number of pieces owned by address1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param addressObj address token owner1461 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1462 * @returns number of pieces ownerd by address1463 */1464 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1465 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1466 }14671468 /**1469 * Transfer pieces of token to another address1470 * @param signer keyring of signer1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param addressObj address of a new owner1474 * @param amount number of pieces to be transfered1475 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1476 * @returns ```true``` if extrinsic success, otherwise ```false```1477 */1478 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1479 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1480 }14811482 /**1483 * Change ownership of some pieces of RFT on behalf of the owner. 1484 * @param signer keyring of signer1485 * @param collectionId ID of collection1486 * @param tokenId ID of token1487 * @param fromAddressObj address on behalf of which the token will be sent1488 * @param toAddressObj new token owner1489 * @param amount number of pieces to be transfered1490 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1491 * @returns ```true``` if extrinsic success, otherwise ```false```1492 */1493 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1494 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1495 }14961497 /**1498 * Mint new collection1499 * @param signer keyring of signer1500 * @param collectionOptions Collection options1501 * @example1502 * mintCollection(aliceKeyring, {1503 * name: 'New',1504 * description: 'New collection',1505 * tokenPrefix: 'NEW',1506 * })1507 * @returns object of the created collection1508 */1509 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1510 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1511 }15121513 /**1514 * Mint new token1515 * @param signer keyring of signer1516 * @param data token data1517 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1518 * @returns created token object1519 */1520 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1521 const creationResult = await this.helper.executeExtrinsic(1522 signer,1523 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1524 refungible: {1525 pieces: data.pieces,1526 properties: data.properties,1527 },1528 }],1529 true,1530 );1531 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1532 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1533 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1534 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1535 }15361537 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1538 throw Error('Not implemented');1539 const creationResult = await this.helper.executeExtrinsic(1540 signer,1541 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1542 true, // `Unable to mint RFT tokens for ${label}`,1543 );1544 const collection = this.getCollectionObject(collectionId);1545 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1546 }15471548 /**1549 * Mint multiple RFT tokens with one owner1550 * @param signer keyring of signer1551 * @param collectionId ID of collection1552 * @param owner tokens owner1553 * @param tokens array of tokens with properties and pieces1554 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1555 * @returns array of newly created RFT tokens1556 */1557 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1558 const rawTokens = [];1559 for (const token of tokens) {1560 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1561 rawTokens.push(raw);1562 }1563 const creationResult = await this.helper.executeExtrinsic(1564 signer,1565 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1566 true,1567 );1568 const collection = this.getCollectionObject(collectionId);1569 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1570 }15711572 /**1573 * Destroys a concrete instance of RFT.1574 * @param signer keyring of signer1575 * @param collectionId ID of collection1576 * @param tokenId ID of token1577 * @param amount number of pieces to be burnt1578 * @example burnToken(aliceKeyring, 10, 5);1579 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1580 */1581 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1582 return await super.burnToken(signer, collectionId, tokenId, amount);1583 }15841585 /**1586 * Set, change, or remove approved address to transfer the ownership of the RFT.1587 * 1588 * @param signer keyring of signer1589 * @param collectionId ID of collection1590 * @param tokenId ID of token1591 * @param toAddressObj address to approve1592 * @param amount number of pieces to be approved1593 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1594 * @returns true if the token success, otherwise false1595 */1596 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1597 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1598 }15991600 /**1601 * Get total number of pieces1602 * @param collectionId ID of collection1603 * @param tokenId ID of token1604 * @example getTokenTotalPieces(10, 5);1605 * @returns number of pieces1606 */1607 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1608 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1609 }16101611 /**1612 * Change number of token pieces. Signer must be the owner of all token pieces.1613 * @param signer keyring of signer1614 * @param collectionId ID of collection1615 * @param tokenId ID of token1616 * @param amount new number of pieces1617 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1618 * @returns true if the repartion was success, otherwise false1619 */1620 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1621 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1622 const repartitionResult = await this.helper.executeExtrinsic(1623 signer,1624 'api.tx.unique.repartition', [collectionId, tokenId, amount],1625 true,1626 );1627 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1628 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1629 }1630}163116321633class FTGroup extends CollectionGroup {1634 /**1635 * Get collection object1636 * @param collectionId ID of collection1637 * @example getCollectionObject(2);1638 * @returns instance of UniqueFTCollection1639 */1640 getCollectionObject(collectionId: number): UniqueFTCollection {1641 return new UniqueFTCollection(collectionId, this.helper);1642 }16431644 /**1645 * Mint new fungible collection1646 * @param signer keyring of signer1647 * @param collectionOptions Collection options1648 * @param decimalPoints number of token decimals 1649 * @example1650 * mintCollection(aliceKeyring, {1651 * name: 'New',1652 * description: 'New collection',1653 * tokenPrefix: 'NEW',1654 * }, 18)1655 * @returns newly created fungible collection1656 */1657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1658 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1659 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1660 collectionOptions.mode = {fungible: decimalPoints};1661 for (const key of ['name', 'description', 'tokenPrefix']) {1662 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createCollectionEx', [collectionOptions],1667 true,1668 );1669 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1670 }16711672 /**1673 * Mint tokens1674 * @param signer keyring of signer1675 * @param collectionId ID of collection1676 * @param owner address owner of new tokens1677 * @param amount amount of tokens to be meanted1678 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1679 * @returns ```true``` if extrinsic success, otherwise ```false``` 1680 */1681 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1682 const creationResult = await this.helper.executeExtrinsic(1683 signer,1684 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1685 fungible: {1686 value: amount,1687 },1688 }],1689 true, // `Unable to mint fungible tokens for ${label}`,1690 );1691 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1692 }16931694 /**1695 * Mint multiple Fungible tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with properties and pieces1700 * @returns ```true``` if extrinsic success, otherwise ```false``` 1701 */1702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1703 const rawTokens = [];1704 for (const token of tokens) {1705 const raw = {Fungible: {Value: token.value}};1706 rawTokens.push(raw);1707 }1708 const creationResult = await this.helper.executeExtrinsic(1709 signer,1710 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1711 true,1712 );1713 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1714 }17151716 /**1717 * Get the top 10 owners with the largest balance for the Fungible collection 1718 * @param collectionId ID of collection1719 * @example getTop10Owners(10);1720 * @returns array of ```ICrossAccountId```1721 */1722 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724 }17251726 /**1727 * Get account balance1728 * @param collectionId ID of collection1729 * @param addressObj address of owner1730 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1731 * @returns amount of fungible tokens owned by address1732 */1733 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735 }17361737 /**1738 * Transfer tokens to address1739 * @param signer keyring of signer1740 * @param collectionId ID of collection1741 * @param toAddressObj address recipient1742 * @param amount amount of tokens to be sent1743 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1744 * @returns ```true``` if extrinsic success, otherwise ```false``` 1745 */1746 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1747 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748 }17491750 /**1751 * Transfer some tokens on behalf of the owner.1752 * @param signer keyring of signer1753 * @param collectionId ID of collection1754 * @param fromAddressObj address on behalf of which tokens will be sent1755 * @param toAddressObj address where token to be sent1756 * @param amount number of tokens to be sent1757 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1758 * @returns ```true``` if extrinsic success, otherwise ```false``` 1759 */1760 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1761 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1762 }17631764 /**1765 * Destroy some amount of tokens1766 * @param signer keyring of signer1767 * @param collectionId ID of collection1768 * @param amount amount of tokens to be destroyed1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1783 * @returns ```true``` if extrinsic success, otherwise ```false``` 1784 */1785 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1786 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1787 }17881789 /**1790 * Get total collection supply1791 * @param collectionId 1792 * @returns 1793 */1794 async getTotalPieces(collectionId: number): Promise<bigint> {1795 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1796 }17971798 /**1799 * Set, change, or remove approved address to transfer tokens.1800 * 1801 * @param signer keyring of signer1802 * @param collectionId ID of collection1803 * @param toAddressObj address to be approved1804 * @param amount amount of tokens to be approved1805 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1806 * @returns ```true``` if extrinsic success, otherwise ```false``` 1807 */1808 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1809 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1810 }18111812 /**1813 * Get amount of fungible tokens approved to transfer1814 * @param collectionId ID of collection1815 * @param fromAddressObj owner of tokens1816 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1817 * @returns number of tokens approved for the transfer1818 */1819 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1820 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1821 }1822}182318241825class ChainGroup extends HelperGroup {1826 /**1827 * Get system properties of a chain1828 * @example getChainProperties();1829 * @returns ss58Format, token decimals, and token symbol1830 */1831 getChainProperties(): IChainProperties {1832 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1833 return {1834 ss58Format: properties.ss58Format.toJSON(),1835 tokenDecimals: properties.tokenDecimals.toJSON(),1836 tokenSymbol: properties.tokenSymbol.toJSON(),1837 };1838 }18391840 /**1841 * Get chain header1842 * @example getLatestBlockNumber();1843 * @returns the number of the last block1844 */1845 async getLatestBlockNumber(): Promise<number> {1846 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1847 }18481849 /**1850 * Get block hash by block number1851 * @param blockNumber number of block1852 * @example getBlockHashByNumber(12345);1853 * @returns hash of a block1854 */1855 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1856 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1857 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1858 return blockHash;1859 }18601861 // TODO add docs1862 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1863 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1864 if (!blockHash) return null;1865 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1866 }18671868 /**1869 * Get account nonce1870 * @param address substrate address1871 * @example getNonce("5GrwvaEF5zXb26Fz...");1872 * @returns number, account's nonce1873 */1874 async getNonce(address: TSubstrateAccount): Promise<number> {1875 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1876 }1877}187818791880class BalanceGroup extends HelperGroup {1881 /**1882 * Representation of the native token in the smallest unit1883 * @example getOneTokenNominal()1884 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1885 */1886 getOneTokenNominal(): bigint {1887 const chainProperties = this.helper.chain.getChainProperties();1888 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1889 }18901891 /**1892 * Get substrate address balance1893 * @param address substrate address1894 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1895 * @returns amount of tokens on address1896 */1897 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1898 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1899 }19001901 /**1902 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1903 * @param address substrate address1904 * @returns 1905 */1906 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1907 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1908 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1909 }19101911 /**1912 * Get ethereum address balance1913 * @param address ethereum address1914 * @example getEthereum("0x9F0583DbB855d...")1915 * @returns amount of tokens on address1916 */1917 async getEthereum(address: TEthereumAccount): Promise<bigint> {1918 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1919 }19201921 /**1922 * Transfer tokens to substrate address1923 * @param signer keyring of signer1924 * @param address substrate address of a recipient1925 * @param amount amount of tokens to be transfered1926 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1930 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);19311932 let transfer = {from: null, to: null, amount: 0n} as any;1933 result.result.events.forEach(({event: {data, method, section}}) => {1934 if ((section === 'balances') && (method === 'Transfer')) {1935 transfer = {1936 from: this.helper.address.normalizeSubstrate(data[0]),1937 to: this.helper.address.normalizeSubstrate(data[1]),1938 amount: BigInt(data[2]),1939 };1940 }1941 });1942 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1943 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1944 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1945 return isSuccess;1946 }1947}194819491950class AddressGroup extends HelperGroup {1951 /**1952 * Normalizes the address to the specified ss58 format, by default ```42```.1953 * @param address substrate address1954 * @param ss58Format format for address conversion, by default ```42```1955 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1956 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1957 */1958 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1959 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1960 }19611962 /**1963 * Get address in the connected chain format1964 * @param address substrate address1965 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1966 * @returns address in chain format1967 */1968 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1969 const info = this.helper.chain.getChainProperties();1970 return encodeAddress(decodeAddress(address), info.ss58Format);1971 }19721973 /**1974 * Get substrate mirror of an ethereum address1975 * @param ethAddress ethereum address1976 * @param toChainFormat false for normalized account1977 * @example ethToSubstrate('0x9F0583DbB855d...')1978 * @returns substrate mirror of a provided ethereum address1979 */1980 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1981 if(!toChainFormat) return evmToAddress(ethAddress);1982 const info = this.helper.chain.getChainProperties();1983 return evmToAddress(ethAddress, info.ss58Format);1984 }19851986 /**1987 * Get ethereum mirror of a substrate address1988 * @param subAddress substrate account1989 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1990 * @returns ethereum mirror of a provided substrate address1991 */1992 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1993 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1994 }1995}19961997class StakingGroup extends HelperGroup {1998 /**1999 * Stake tokens for App Promotion2000 * @param signer keyring of signer2001 * @param amountToStake amount of tokens to stake2002 * @param label extra label for log2003 * @returns2004 */2005 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2006 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2007 const stakeResult = await this.helper.executeExtrinsic(2008 signer, 'api.tx.appPromotion.stake',2009 [amountToStake], true,2010 );2011 // TODO extract info from stakeResult2012 return true;2013 }20142015 /**2016 * Unstake tokens for App Promotion2017 * @param signer keyring of signer2018 * @param amountToUnstake amount of tokens to unstake2019 * @param label extra label for log2020 * @returns block number where balances will be unlocked2021 */2022 async unstake(signer: TSigner, label?: string): Promise<number> {2023 if(typeof label === 'undefined') label = `${signer.address}`;2024 const unstakeResult = await this.helper.executeExtrinsic(2025 signer, 'api.tx.appPromotion.unstake', 2026 [], true,2027 );2028 // TODO extract block number fron events2029 return 1;2030 }20312032 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2033 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2034 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2035 }20362037 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2038 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2039 }20402041 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2042 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2043 }2044 2045 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2046 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2047 }2048}20492050export class UniqueHelper extends ChainHelperBase {2051 chain: ChainGroup;2052 balance: BalanceGroup;2053 address: AddressGroup;2054 collection: CollectionGroup;2055 nft: NFTGroup;2056 rft: RFTGroup;2057 ft: FTGroup;2058 staking: StakingGroup;20592060 constructor(logger?: ILogger) {2061 super(logger);2062 this.chain = new ChainGroup(this);2063 this.balance = new BalanceGroup(this);2064 this.address = new AddressGroup(this);2065 this.collection = new CollectionGroup(this);2066 this.nft = new NFTGroup(this);2067 this.rft = new RFTGroup(this);2068 this.ft = new FTGroup(this);2069 this.staking = new StakingGroup(this);2070 } 2071}207220732074class UniqueCollectionBase {2075 helper: UniqueHelper;2076 collectionId: number;20772078 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2079 this.collectionId = collectionId;2080 this.helper = uniqueHelper;2081 }20822083 async getData() {2084 return await this.helper.collection.getData(this.collectionId);2085 }20862087 async getLastTokenId() {2088 return await this.helper.collection.getLastTokenId(this.collectionId);2089 }20902091 async isTokenExists(tokenId: number) {2092 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2093 }20942095 async getAdmins() {2096 return await this.helper.collection.getAdmins(this.collectionId);2097 }20982099 async getAllowList() {2100 return await this.helper.collection.getAllowList(this.collectionId);2101 }21022103 async getEffectiveLimits() {2104 return await this.helper.collection.getEffectiveLimits(this.collectionId);2105 }21062107 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2108 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2109 }21102111 async confirmSponsorship(signer: TSigner) {2112 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2113 }21142115 async removeSponsor(signer: TSigner) {2116 return await this.helper.collection.removeSponsor(signer, this.collectionId);2117 }21182119 async setLimits(signer: TSigner, limits: ICollectionLimits) {2120 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2121 }21222123 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2124 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2125 }21262127 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2128 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2129 }21302131 async enableCertainPermissions(signer: TSigner, accessMode: 'AllowList' | 'Normal' | undefined = 'AllowList', mintMode: boolean | undefined = true) {2132 return await this.setPermissions(signer, {access: accessMode, mintMode: mintMode});2133 }21342135 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2136 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2137 }21382139 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2140 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2141 }21422143 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2144 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2145 }21462147 async setProperties(signer: TSigner, properties: IProperty[]) {2148 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2149 }21502151 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2152 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2153 }21542155 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2156 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2157 }21582159 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2160 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2161 }21622163 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2164 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2165 }21662167 async disableNesting(signer: TSigner) {2168 return await this.helper.collection.disableNesting(signer, this.collectionId);2169 }21702171 async burn(signer: TSigner) {2172 return await this.helper.collection.burn(signer, this.collectionId);2173 }2174}217521762177class UniqueNFTCollection extends UniqueCollectionBase {2178 getTokenObject(tokenId: number) {2179 return new UniqueNFTToken(tokenId, this);2180 }21812182 async getTokensByAddress(addressObj: ICrossAccountId) {2183 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2184 }21852186 async getToken(tokenId: number, blockHashAt?: string) {2187 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2188 }21892190 async getTokenOwner(tokenId: number, blockHashAt?: string) {2191 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2192 }21932194 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2195 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2196 }21972198 async getTokenChildren(tokenId: number, blockHashAt?: string) {2199 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2200 }22012202 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2203 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2204 }22052206 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2207 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2208 }22092210 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2211 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2212 }22132214 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2215 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2216 }22172218 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2219 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2220 }22212222 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2223 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2224 }22252226 async burnToken(signer: TSigner, tokenId: number) {2227 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2228 }22292230 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2231 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2232 }22332234 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2235 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2236 }22372238 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2239 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2240 }22412242 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2243 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2244 }22452246 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2247 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2248 }2249}225022512252class UniqueRFTCollection extends UniqueCollectionBase {2253 getTokenObject(tokenId: number) {2254 return new UniqueRFTToken(tokenId, this);2255 }22562257 async getTokensByAddress(addressObj: ICrossAccountId) {2258 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2259 }22602261 async getTop10TokenOwners(tokenId: number) {2262 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2263 }22642265 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2266 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2267 }22682269 async getTokenTotalPieces(tokenId: number) {2270 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2271 }22722273 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2274 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2275 }22762277 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2278 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2279 }22802281 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2282 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2283 }22842285 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2286 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2287 }22882289 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2290 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2291 }22922293 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2294 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2295 }22962297 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2298 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2299 }23002301 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2302 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2303 }23042305 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2306 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2307 }23082309 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2310 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2311 }23122313 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2314 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2315 }2316}231723182319class UniqueFTCollection extends UniqueCollectionBase {2320 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2321 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2322 }23232324 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2325 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2326 }23272328 async getBalance(addressObj: ICrossAccountId) {2329 return await this.helper.ft.getBalance(this.collectionId, addressObj);2330 }23312332 async getTop10Owners() {2333 return await this.helper.ft.getTop10Owners(this.collectionId);2334 }23352336 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2337 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2338 }23392340 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2341 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2342 }23432344 async burnTokens(signer: TSigner, amount=1n) {2345 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2346 }23472348 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2349 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2350 }23512352 async getTotalPieces() {2353 return await this.helper.ft.getTotalPieces(this.collectionId);2354 }23552356 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2357 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2358 }23592360 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2361 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2362 }2363}236423652366class UniqueTokenBase implements IToken {2367 collection: UniqueNFTCollection | UniqueRFTCollection;2368 collectionId: number;2369 tokenId: number;23702371 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2372 this.collection = collection;2373 this.collectionId = collection.collectionId;2374 this.tokenId = tokenId;2375 }23762377 async getNextSponsored(addressObj: ICrossAccountId) {2378 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2379 }23802381 async setProperties(signer: TSigner, properties: IProperty[]) {2382 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2383 }23842385 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2386 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2387 }2388}238923902391class UniqueNFTToken extends UniqueTokenBase {2392 collection: UniqueNFTCollection;23932394 constructor(tokenId: number, collection: UniqueNFTCollection) {2395 super(tokenId, collection);2396 this.collection = collection;2397 }23982399 async getData(blockHashAt?: string) {2400 return await this.collection.getToken(this.tokenId, blockHashAt);2401 }24022403 async getOwner(blockHashAt?: string) {2404 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2405 }24062407 async getTopmostOwner(blockHashAt?: string) {2408 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2409 }24102411 async getChildren(blockHashAt?: string) {2412 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2413 }24142415 async nest(signer: TSigner, toTokenObj: IToken) {2416 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2417 }24182419 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2420 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2421 }24222423 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2424 return await this.collection.transferToken(signer, this.tokenId, addressObj);2425 }24262427 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2428 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2429 }24302431 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2432 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2433 }24342435 async isApproved(toAddressObj: ICrossAccountId) {2436 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2437 }24382439 async burn(signer: TSigner) {2440 return await this.collection.burnToken(signer, this.tokenId);2441 }2442}24432444class UniqueRFTToken extends UniqueTokenBase {2445 collection: UniqueRFTCollection;24462447 constructor(tokenId: number, collection: UniqueRFTCollection) {2448 super(tokenId, collection);2449 this.collection = collection;2450 }24512452 async getTop10Owners() {2453 return await this.collection.getTop10TokenOwners(this.tokenId);2454 }24552456 async getBalance(addressObj: ICrossAccountId) {2457 return await this.collection.getTokenBalance(this.tokenId, addressObj);2458 }24592460 async getTotalPieces() {2461 return await this.collection.getTokenTotalPieces(this.tokenId);2462 }24632464 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2465 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2466 }24672468 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2469 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2470 }24712472 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2473 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2474 }24752476 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2477 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2478 }24792480 async repartition(signer: TSigner, amount: bigint) {2481 return await this.collection.repartitionToken(signer, this.tokenId, amount);2482 }24832484 async burn(signer: TSigner, amount=1n) {2485 return await this.collection.burnToken(signer, this.tokenId, amount);2486 }2487}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 // If ith character is 8 to f then make it uppercase33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getNestingTokenAddress(collectionId: number, tokenId: number) {59 return nesting.tokenIdToAddress(collectionId, tokenId);60 }6162 static getDefaultLogger(): ILogger {63 return {64 log(msg: any, level = 'INFO') {65 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66 },67 level: {68 ERROR: 'ERROR',69 WARNING: 'WARNING',70 INFO: 'INFO',71 },72 };73 }7475 static vec2str(arr: string[] | number[]) {76 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77 }7879 static str2vec(string: string) {80 if (typeof string !== 'string') return string;81 return Array.from(string).map(x => x.charCodeAt(0));82 }8384 static fromSeed(seed: string, ss58Format = 42) {85 const keyring = new Keyring({type: 'sr25519', ss58Format});86 return keyring.addFromUri(seed);87 }8889 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');96 }9798 let collectionId = null;99 creationResult.result.events.forEach(({event: {data, method, section}}) => {100 if ((section === 'common') && (method === 'CollectionCreated')) {101 collectionId = parseInt(data[0].toString(), 10);102 }103 });104105 if (collectionId === null) {106 throw Error('No CollectionCreated event was found!');107 }108109 return collectionId;110 }111112 static extractTokensFromCreationResult(creationResult: ITransactionResult) {113 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 throw Error('Unable to create tokens!');115 }116 let success = false;117 const tokens = [] as any;118 creationResult.result.events.forEach(({event: {data, method, section}}) => {119 if (method === 'ExtrinsicSuccess') {120 success = true;121 } else if ((section === 'common') && (method === 'ItemCreated')) {122 tokens.push({123 collectionId: parseInt(data[0].toString(), 10),124 tokenId: parseInt(data[1].toString(), 10),125 owner: data[2].toJSON(),126 });127 }128 });129 return {success, tokens};130 }131132 static extractTokensFromBurnResult(burnResult: ITransactionResult) {133 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 throw Error('Unable to burn tokens!');135 }136 let success = false;137 const tokens = [] as any;138 burnResult.result.events.forEach(({event: {data, method, section}}) => {139 if (method === 'ExtrinsicSuccess') {140 success = true;141 } else if ((section === 'common') && (method === 'ItemDestroyed')) {142 tokens.push({143 collectionId: parseInt(data[0].toString(), 10),144 tokenId: parseInt(data[1].toString(), 10),145 owner: data[2].toJSON(),146 });147 }148 });149 return {success, tokens};150 }151152 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153 let eventId = null;154 events.forEach(({event: {data, method, section}}) => {155 if ((section === expectedSection) && (method === expectedMethod)) {156 eventId = parseInt(data[0].toString(), 10);157 }158 });159160 if (eventId === null) {161 throw Error(`No ${expectedMethod} event was found!`);162 }163 return eventId === collectionId;164 }165166 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167 const normalizeAddress = (address: string | ICrossAccountId) => {168 if(typeof address === 'string') return address;169 const obj = {} as any;170 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175 return address;176 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178 events.forEach(({event: {data, method, section}}) => {179 if ((section === 'common') && (method === 'Transfer')) {180 const hData = (data as any).toJSON();181 transfer = {182 collectionId: hData[0],183 tokenId: hData[1],184 from: normalizeAddress(hData[2]),185 to: normalizeAddress(hData[3]),186 amount: BigInt(hData[4]),187 };188 }189 });190 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193 isSuccess = isSuccess && amount === transfer.amount;194 return isSuccess;195 }196}197198199class ChainHelperBase {200 transactionStatus = UniqueUtil.transactionStatus;201 chainLogType = UniqueUtil.chainLogType;202 util: typeof UniqueUtil;203 logger: ILogger;204 api: ApiPromise | null;205 forcedNetwork: TUniqueNetworks | null;206 network: TUniqueNetworks | null;207 chainLog: IUniqueHelperLog[];208209 constructor(logger?: ILogger) {210 this.util = UniqueUtil;211 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();212 this.logger = logger;213 this.api = null;214 this.forcedNetwork = null;215 this.network = null;216 this.chainLog = [];217 }218219 clearChainLog(): void {220 this.chainLog = [];221 }222223 forceNetwork(value: TUniqueNetworks): void {224 this.forcedNetwork = value;225 }226227 async connect(wsEndpoint: string, listeners?: IApiListeners) {228 if (this.api !== null) throw Error('Already connected');229 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);230 this.api = api;231 this.network = network;232 }233234 async disconnect() {235 if (this.api === null) return;236 await this.api.disconnect();237 this.api = null;238 this.network = null;239 }240241 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {242 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;243 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;244 return 'opal';245 }246247 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {248 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});249 await api.isReady;250251 const network = await this.detectNetwork(api);252253 await api.disconnect();254255 return network;256 }257258 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 259 api: ApiPromise; 260 network: TUniqueNetworks; 261 }> {262 if(typeof network === 'undefined' || network === null) network = 'opal';263 const supportedRPC = {264 opal: {265 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,266 },267 quartz: {268 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,269 },270 unique: {271 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,272 },273 };274 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);275 const rpc = supportedRPC[network];276277 // TODO: investigate how to replace rpc in runtime278 // api._rpcCore.addUserInterfaces(rpc);279280 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});281282 await api.isReadyOrError;283284 if (typeof listeners === 'undefined') listeners = {};285 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {286 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;287 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);288 }289290 return {api, network};291 }292293 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {294 const {events, status} = data;295 if (status.isReady) {296 return this.transactionStatus.NOT_READY;297 }298 if (status.isBroadcast) {299 return this.transactionStatus.NOT_READY;300 }301 if (status.isInBlock || status.isFinalized) {302 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');303 if (errors.length > 0) {304 return this.transactionStatus.FAIL;305 }306 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {307 return this.transactionStatus.SUCCESS;308 }309 }310311 return this.transactionStatus.FAIL;312 }313314 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {315 const sign = (callback: any) => {316 if(options !== null) return transaction.signAndSend(sender, options, callback);317 return transaction.signAndSend(sender, callback);318 };319 // eslint-disable-next-line no-async-promise-executor320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 signer: this.getSignerAddress(sender),392 params,393 } as IUniqueHelperLog;394395 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;396 if(events.length > 0) log.events = events;397398 this.chainLog.push(log);399400 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);401 return result;402 }403404 async callRpc(rpc: string, params?: any[]) {405 if(typeof params === 'undefined') params = [];406 if(this.api === null) throw Error('API not initialized');407 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);408409 const startTime = (new Date()).getTime();410 let result;411 let error = null;412 const log = {413 type: this.chainLogType.RPC,414 call: rpc,415 params,416 } as IUniqueHelperLog;417418 try {419 result = await this.constructApiCall(rpc, params);420 }421 catch(e) {422 error = e;423 }424425 const endTime = (new Date()).getTime();426427 log.executedAt = endTime;428 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';429 log.executionTime = endTime - startTime;430431 this.chainLog.push(log);432433 if(error !== null) throw error;434435 return result;436 }437438 getSignerAddress(signer: IKeyringPair | string): string {439 if(typeof signer === 'string') return signer;440 return signer.address;441 }442443 fetchAllPalletNames(): string[] {444 if(this.api === null) throw Error('API not initialized');445 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());446 }447 448 fetchMissingPalletNames(requiredPallets: string[]): string[] {449 const palletNames = this.fetchAllPalletNames();450 return requiredPallets.filter(p => !palletNames.includes(p));451 }452}453454455class HelperGroup {456 helper: UniqueHelper;457458 constructor(uniqueHelper: UniqueHelper) {459 this.helper = uniqueHelper;460 }461}462463464class CollectionGroup extends HelperGroup {465 /**466 * Get number of blocks when sponsored transaction is available.467 *468 * @param collectionId ID of collection469 * @param tokenId ID of token470 * @param addressObj address for which the sponsorship is checked471 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});472 * @returns number of blocks or null if sponsorship hasn't been set473 */474 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {475 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();476 }477478 /**479 * Get the number of created collections.480 * 481 * @returns number of created collections482 */483 async getTotalCount(): Promise<number> {484 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();485 }486487 /**488 * Get information about the collection with additional data, 489 * including the number of tokens it contains, its administrators, 490 * the normalized address of the collection's owner, and decoded name and description.491 * 492 * @param collectionId ID of collection493 * @example await getData(2)494 * @returns collection information object495 */496 async getData(collectionId: number): Promise<{497 id: number;498 name: string;499 description: string;500 tokensCount: number;501 admins: ICrossAccountId[];502 normalizedOwner: TSubstrateAccount;503 raw: any504 } | null> {505 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);506 const humanCollection = collection.toHuman(), collectionData = {507 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],508 raw: humanCollection,509 } as any, jsonCollection = collection.toJSON();510 if (humanCollection === null) return null;511 collectionData.raw.limits = jsonCollection.limits;512 collectionData.raw.permissions = jsonCollection.permissions;513 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);514 for (const key of ['name', 'description']) {515 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);516 }517518 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) 519 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) 520 : 0;521 collectionData.admins = await this.getAdmins(collectionId);522523 return collectionData;524 }525526 /**527 * Get the addresses of the collection's administrators, optionally normalized.528 * 529 * @param collectionId ID of collection530 * @param normalize whether to normalize the addresses to the default ss58 format531 * @example await getAdmins(1)532 * @returns array of administrators533 */534 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {535 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();536537 return normalize538 ? admins.map((address: any) => {539 return address.Substrate540 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}541 : address;542 }) 543 : admins;544 }545546 /**547 * Get the addresses added to the collection allow-list, optionally normalized.548 * @param collectionId ID of collection549 * @param normalize whether to normalize the addresses to the default ss58 format550 * @example await getAllowList(1)551 * @returns array of allow-listed addresses552 */553 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {554 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();555 return normalize556 ? allowListed.map((address: any) => {557 return address.Substrate558 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}559 : address;560 }) 561 : allowListed;562 }563564 /**565 * Get the effective limits of the collection instead of null for default values566 * 567 * @param collectionId ID of collection568 * @example await getEffectiveLimits(2)569 * @returns object of collection limits570 */571 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {572 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();573 }574575 /**576 * Burns the collection if the signer has sufficient permissions and collection is empty.577 * 578 * @param signer keyring of signer579 * @param collectionId ID of collection580 * @example await helper.collection.burn(aliceKeyring, 3);581 * @returns ```true``` if extrinsic success, otherwise ```false```582 */583 async burn(signer: TSigner, collectionId: number): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.destroyCollection', [collectionId],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');591 }592593 /**594 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.595 * 596 * @param signer keyring of signer597 * @param collectionId ID of collection598 * @param sponsorAddress Sponsor substrate address599 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")600 * @returns ```true``` if extrinsic success, otherwise ```false```601 */602 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {603 const result = await this.helper.executeExtrinsic(604 signer,605 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],606 true,607 );608609 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');610 }611612 /**613 * Confirms consent to sponsor the collection on behalf of the signer.614 * 615 * @param signer keyring of signer616 * @param collectionId ID of collection617 * @example confirmSponsorship(aliceKeyring, 10)618 * @returns ```true``` if extrinsic success, otherwise ```false```619 */620 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {621 const result = await this.helper.executeExtrinsic(622 signer,623 'api.tx.unique.confirmSponsorship', [collectionId],624 true,625 );626627 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');628 }629630 /**631 * Removes the sponsor of a collection, regardless if it consented or not.632 * 633 * @param signer keyring of signer634 * @param collectionId ID of collection635 * @example removeSponsor(aliceKeyring, 10)636 * @returns ```true``` if extrinsic success, otherwise ```false```637 */638 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {639 const result = await this.helper.executeExtrinsic(640 signer,641 'api.tx.unique.removeCollectionSponsor', [collectionId],642 true,643 );644645 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');646 }647648 /**649 * Sets the limits of the collection. At least one limit must be specified for a correct call.650 * 651 * @param signer keyring of signer652 * @param collectionId ID of collection653 * @param limits collection limits object654 * @example655 * await setLimits(656 * aliceKeyring,657 * 10,658 * {659 * sponsorTransferTimeout: 0,660 * ownerCanDestroy: false661 * }662 * )663 * @returns ```true``` if extrinsic success, otherwise ```false```664 */665 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {666 const result = await this.helper.executeExtrinsic(667 signer,668 'api.tx.unique.setCollectionLimits', [collectionId, limits],669 true,670 );671672 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');673 }674675 /**676 * Changes the owner of the collection to the new Substrate address.677 * 678 * @param signer keyring of signer679 * @param collectionId ID of collection680 * @param ownerAddress substrate address of new owner681 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")682 * @returns ```true``` if extrinsic success, otherwise ```false```683 */684 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {685 const result = await this.helper.executeExtrinsic(686 signer,687 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],688 true,689 );690691 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');692 }693694 /**695 * Adds a collection administrator. 696 * 697 * @param signer keyring of signer698 * @param collectionId ID of collection699 * @param adminAddressObj Administrator address (substrate or ethereum)700 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})701 * @returns ```true``` if extrinsic success, otherwise ```false```702 */703 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {704 const result = await this.helper.executeExtrinsic(705 signer,706 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],707 true,708 );709710 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');711 }712713 /**714 * Removes a collection administrator.715 * 716 * @param signer keyring of signer717 * @param collectionId ID of collection718 * @param adminAddressObj Administrator address (substrate or ethereum)719 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})720 * @returns ```true``` if extrinsic success, otherwise ```false```721 */722 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');730 }731732 /**733 * Adds an address to allow list 734 * @param signer keyring of signer735 * @param collectionId ID of collection736 * @param addressObj address to add to the allow list737 * @returns ```true``` if extrinsic success, otherwise ```false```738 */739 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.addToAllowList', [collectionId, addressObj],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');747 }748749 /**750 * Removes an address from allow list 751 * 752 * @param signer keyring of signer753 * @param collectionId ID of collection754 * @param addressObj address to remove from the allow list755 * @returns ```true``` if extrinsic success, otherwise ```false```756 */757 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {758 const result = await this.helper.executeExtrinsic(759 signer,760 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],761 true,762 );763764 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');765 }766767 /**768 * Sets onchain permissions for selected collection.769 * 770 * @param signer keyring of signer771 * @param collectionId ID of collection772 * @param permissions collection permissions object773 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});774 * @returns ```true``` if extrinsic success, otherwise ```false```775 */776 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {777 const result = await this.helper.executeExtrinsic(778 signer,779 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],780 true,781 );782783 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');784 }785786 /**787 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.788 * 789 * @param signer keyring of signer790 * @param collectionId ID of collection791 * @param permissions nesting permissions object792 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});793 * @returns ```true``` if extrinsic success, otherwise ```false```794 */795 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {796 return await this.setPermissions(signer, collectionId, {nesting: permissions});797 }798799 /**800 * Disables nesting for selected collection.801 * 802 * @param signer keyring of signer803 * @param collectionId ID of collection804 * @example disableNesting(aliceKeyring, 10);805 * @returns ```true``` if extrinsic success, otherwise ```false```806 */807 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {808 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});809 }810811 /**812 * Sets onchain properties to the collection.813 * 814 * @param signer keyring of signer815 * @param collectionId ID of collection816 * @param properties array of property objects817 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);818 * @returns ```true``` if extrinsic success, otherwise ```false```819 */820 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {821 const result = await this.helper.executeExtrinsic(822 signer,823 'api.tx.unique.setCollectionProperties', [collectionId, properties],824 true,825 );826827 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');828 }829830 /**831 * Deletes onchain properties from the collection.832 * 833 * @param signer keyring of signer834 * @param collectionId ID of collection835 * @param propertyKeys array of property keys to delete836 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);837 * @returns ```true``` if extrinsic success, otherwise ```false```838 */839 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {840 const result = await this.helper.executeExtrinsic(841 signer,842 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],843 true,844 );845846 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');847 }848849 /**850 * Changes the owner of the token.851 * 852 * @param signer keyring of signer853 * @param collectionId ID of collection854 * @param tokenId ID of token855 * @param addressObj address of a new owner856 * @param amount amount of tokens to be transfered. For NFT must be set to 1n857 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})858 * @returns true if the token success, otherwise false859 */860 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],864 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,865 );866867 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);868 }869870 /**871 * 872 * Change ownership of a token(s) on behalf of the owner. 873 * 874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param tokenId ID of token877 * @param fromAddressObj address on behalf of which the token will be sent878 * @param toAddressObj new token owner879 * @param amount amount of tokens to be transfered. For NFT must be set to 1n880 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})881 * @returns true if the token success, otherwise false882 */883 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {884 const result = await this.helper.executeExtrinsic(885 signer,886 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],887 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,888 );889 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);890 }891892 /**893 * 894 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.895 * 896 * @param signer keyring of signer897 * @param collectionId ID of collection898 * @param tokenId ID of token899 * @param amount amount of tokens to be burned. For NFT must be set to 1n900 * @example burnToken(aliceKeyring, 10, 5);901 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```902 */903 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{904 success: boolean,905 token: number | null906 }> {907 const burnResult = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.burnItem', [collectionId, tokenId, amount],910 true, // `Unable to burn token for ${label}`,911 );912 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);913 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');914 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};915 }916917 /**918 * Destroys a concrete instance of NFT on behalf of the owner919 * 920 * @param signer keyring of signer921 * @param collectionId ID of collection922 * @param fromAddressObj address on behalf of which the token will be burnt923 * @param tokenId ID of token924 * @param amount amount of tokens to be burned. For NFT must be set to 1n925 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})926 * @returns ```true``` if extrinsic success, otherwise ```false```927 */928 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {929 const burnResult = await this.helper.executeExtrinsic(930 signer,931 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],932 true, // `Unable to burn token from for ${label}`,933 );934 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);935 return burnedTokens.success && burnedTokens.tokens.length > 0;936 }937938 /**939 * Set, change, or remove approved address to transfer the ownership of the NFT.940 * 941 * @param signer keyring of signer942 * @param collectionId ID of collection943 * @param tokenId ID of token944 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens945 * @param amount amount of token to be approved. For NFT must be set to 1n946 * @returns ```true``` if extrinsic success, otherwise ```false```947 */948 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {949 const approveResult = await this.helper.executeExtrinsic(950 signer, 951 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],952 true, // `Unable to approve token for ${label}`,953 );954955 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');956 }957958 /**959 * Get the amount of token pieces approved to transfer or burn. Normally 0.960 * 961 * @param collectionId ID of collection962 * @param tokenId ID of token963 * @param toAccountObj address which is approved to use token pieces964 * @param fromAccountObj address which may have allowed the use of its owned tokens965 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})966 * @returns number of approved to transfer pieces967 */968 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {969 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();970 }971972 /**973 * Get the last created token ID in a collection974 * 975 * @param collectionId ID of collection976 * @example getLastTokenId(10);977 * @returns id of the last created token978 */979 async getLastTokenId(collectionId: number): Promise<number> {980 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();981 }982983 /**984 * Check if token exists985 * 986 * @param collectionId ID of collection987 * @param tokenId ID of token988 * @example isTokenExists(10, 20);989 * @returns true if the token exists, otherwise false990 */991 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {992 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();993 }994}995996class NFTnRFT extends CollectionGroup {997 /**998 * Get tokens owned by account999 * 1000 * @param collectionId ID of collection1001 * @param addressObj tokens owner1002 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1003 * @returns array of token ids owned by account1004 */1005 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1006 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1007 }10081009 /**1010 * Get token data1011 * 1012 * @param collectionId ID of collection1013 * @param tokenId ID of token1014 * @param propertyKeys optionally filter the token properties to only these keys1015 * @param blockHashAt optionally query the data at some block with this hash1016 * @example getToken(10, 5);1017 * @returns human readable token data 1018 */1019 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1020 properties: IProperty[];1021 owner: ICrossAccountId;1022 normalizedOwner: ICrossAccountId;1023 }| null> {1024 let tokenData;1025 if(typeof blockHashAt === 'undefined') {1026 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1027 }1028 else {1029 if(propertyKeys.length == 0) {1030 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 if(!collection) return null;1032 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1033 }1034 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1035 }1036 tokenData = tokenData.toHuman();1037 if (tokenData === null || tokenData.owner === null) return null;1038 const owner = {} as any;1039 for (const key of Object.keys(tokenData.owner)) {1040 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1041 }1042 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1043 return tokenData;1044 }10451046 /**1047 * Set permissions to change token properties1048 * 1049 * @param signer keyring of signer1050 * @param collectionId ID of collection1051 * @param permissions permissions to change a property by the collection owner or admin1052 * @example setTokenPropertyPermissions(1053 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1054 * )1055 * @returns true if extrinsic success otherwise false1056 */1057 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1058 const result = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1061 true,1062 );10631064 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1065 }10661067 /**1068 * Set token properties1069 * 1070 * @param signer keyring of signer1071 * @param collectionId ID of collection1072 * @param tokenId ID of token1073 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1074 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1075 * @returns ```true``` if extrinsic success, otherwise ```false```1076 */1077 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1078 const result = await this.helper.executeExtrinsic(1079 signer,1080 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1081 true,1082 );10831084 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1085 }10861087 /**1088 * Delete the provided properties of a token1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @param tokenId ID of token1092 * @param propertyKeys property keys to be deleted 1093 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1094 * @returns ```true``` if extrinsic success, otherwise ```false```1095 */1096 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1097 const result = await this.helper.executeExtrinsic(1098 signer,1099 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1100 true,1101 );11021103 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1104 }11051106 /**1107 * Mint new collection1108 * 1109 * @param signer keyring of signer1110 * @param collectionOptions basic collection options and properties 1111 * @param mode NFT or RFT type of a collection1112 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1113 * @returns object of the created collection1114 */1115 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1116 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1117 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1118 for (const key of ['name', 'description', 'tokenPrefix']) {1119 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1120 }1121 const creationResult = await this.helper.executeExtrinsic(1122 signer,1123 'api.tx.unique.createCollectionEx', [collectionOptions],1124 true, // errorLabel,1125 );1126 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1127 }11281129 getCollectionObject(_collectionId: number): any {1130 return null;1131 }11321133 getTokenObject(_collectionId: number, _tokenId: number): any {1134 return null;1135 }1136}113711381139class NFTGroup extends NFTnRFT {1140 /**1141 * Get collection object1142 * @param collectionId ID of collection1143 * @example getCollectionObject(2);1144 * @returns instance of UniqueNFTCollection1145 */1146 getCollectionObject(collectionId: number): UniqueNFTCollection {1147 return new UniqueNFTCollection(collectionId, this.helper);1148 }11491150 /**1151 * Get token object1152 * @param collectionId ID of collection1153 * @param tokenId ID of token1154 * @example getTokenObject(10, 5);1155 * @returns instance of UniqueNFTToken1156 */1157 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1158 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1159 }11601161 /**1162 * Get token's owner1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param blockHashAt optionally query the data at the block with this hash1166 * @example getTokenOwner(10, 5);1167 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1168 */1169 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1170 let owner;1171 if (typeof blockHashAt === 'undefined') {1172 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1173 } else {1174 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1175 }1176 return crossAccountIdFromLower(owner.toJSON());1177 }11781179 /**1180 * Is token approved to transfer1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param toAccountObj address to be approved1184 * @returns ```true``` if extrinsic success, otherwise ```false```1185 */1186 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1187 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1188 }11891190 /**1191 * Changes the owner of the token.1192 * 1193 * @param signer keyring of signer1194 * @param collectionId ID of collection1195 * @param tokenId ID of token1196 * @param addressObj address of a new owner1197 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1198 * @returns ```true``` if extrinsic success, otherwise ```false```1199 */1200 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1201 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1202 }12031204 /**1205 * 1206 * Change ownership of a NFT on behalf of the owner. 1207 * 1208 * @param signer keyring of signer1209 * @param collectionId ID of collection1210 * @param tokenId ID of token1211 * @param fromAddressObj address on behalf of which the token will be sent1212 * @param toAddressObj new token owner1213 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1214 * @returns ```true``` if extrinsic success, otherwise ```false```1215 */1216 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1217 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1218 }12191220 /**1221 * Recursively find the address that owns the token1222 * @param collectionId ID of collection1223 * @param tokenId ID of token1224 * @param blockHashAt 1225 * @example getTokenTopmostOwner(10, 5);1226 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1227 */1228 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1229 let owner;1230 if (typeof blockHashAt === 'undefined') {1231 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1232 } else {1233 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1234 }12351236 if (owner === null) return null;12371238 owner = owner.toHuman();12391240 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1241 }12421243 /**1244 * Get tokens nested in the provided token1245 * @param collectionId ID of collection1246 * @param tokenId ID of token1247 * @param blockHashAt optionally query the data at the block with this hash1248 * @example getTokenChildren(10, 5);1249 * @returns tokens whose depth of nesting is <= 5 1250 */1251 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1252 let children;1253 if(typeof blockHashAt === 'undefined') {1254 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1255 } else {1256 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1257 }12581259 return children.toJSON().map((x: any) => {1260 return {collectionId: x.collection, tokenId: x.token};1261 });1262 }12631264 /**1265 * Nest one token into another1266 * @param signer keyring of signer1267 * @param tokenObj token to be nested1268 * @param rootTokenObj token to be parent1269 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1270 * @returns ```true``` if extrinsic success, otherwise ```false```1271 */1272 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1273 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1274 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1275 if(!result) {1276 throw Error('Unable to nest token!');1277 }1278 return result;1279 }12801281 /**1282 * Remove token from nested state1283 * @param signer keyring of signer1284 * @param tokenObj token to unnest1285 * @param rootTokenObj parent of a token1286 * @param toAddressObj address of a new token owner 1287 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1288 * @returns ```true``` if extrinsic success, otherwise ```false```1289 */1290 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1291 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1292 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1293 if(!result) {1294 throw Error('Unable to unnest token!');1295 }1296 return result;1297 }12981299 /**1300 * Mint new collection1301 * @param signer keyring of signer1302 * @param collectionOptions Collection options1303 * @example 1304 * mintCollection(aliceKeyring, {1305 * name: 'New',1306 * description: 'New collection',1307 * tokenPrefix: 'NEW',1308 * })1309 * @returns object of the created collection1310 */1311 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1312 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1313 }13141315 /**1316 * Mint new token1317 * @param signer keyring of signer1318 * @param data token data1319 * @returns created token object1320 */1321 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1322 const creationResult = await this.helper.executeExtrinsic(1323 signer,1324 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1325 nft: {1326 properties: data.properties,1327 },1328 }],1329 true,1330 );1331 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1332 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1333 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1334 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1335 }13361337 /**1338 * Mint multiple NFT tokens1339 * @param signer keyring of signer1340 * @param collectionId ID of collection1341 * @param tokens array of tokens with owner and properties1342 * @example 1343 * mintMultipleTokens(aliceKeyring, 10, [{1344 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1345 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1346 * },{1347 * owner: {Ethereum: "0x9F0583DbB855d..."},1348 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1349 * }]);1350 * @returns ```true``` if extrinsic success, otherwise ```false```1351 */1352 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1353 const creationResult = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1356 true,1357 );1358 const collection = this.getCollectionObject(collectionId);1359 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1360 }13611362 /**1363 * Mint multiple NFT tokens with one owner1364 * @param signer keyring of signer1365 * @param collectionId ID of collection1366 * @param owner tokens owner1367 * @param tokens array of tokens with owner and properties1368 * @example1369 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1370 * properties: [{1371 * key: "gender",1372 * value: "female",1373 * },{1374 * key: "age",1375 * value: "33",1376 * }],1377 * }]);1378 * @returns array of newly created tokens1379 */1380 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1381 const rawTokens = [];1382 for (const token of tokens) {1383 const raw = {NFT: {properties: token.properties}};1384 rawTokens.push(raw);1385 }1386 const creationResult = await this.helper.executeExtrinsic(1387 signer,1388 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1389 true,1390 );1391 const collection = this.getCollectionObject(collectionId);1392 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1393 }13941395 /**1396 * Destroys a concrete instance of NFT.1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param tokenId ID of token1400 * @example burnToken(aliceKeyring, 10, 5);1401 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1402 */1403 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1404 return await super.burnToken(signer, collectionId, tokenId, 1n);1405 }14061407 /**1408 * Set, change, or remove approved address to transfer the ownership of the NFT.1409 * 1410 * @param signer keyring of signer1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param toAddressObj address to approve1414 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1415 * @returns ```true``` if extrinsic success, otherwise ```false```1416 */1417 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1418 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1419 }1420}142114221423class RFTGroup extends NFTnRFT {1424 /**1425 * Get collection object1426 * @param collectionId ID of collection1427 * @example getCollectionObject(2);1428 * @returns instance of UniqueRFTCollection1429 */1430 getCollectionObject(collectionId: number): UniqueRFTCollection {1431 return new UniqueRFTCollection(collectionId, this.helper);1432 }14331434 /**1435 * Get token object1436 * @param collectionId ID of collection1437 * @param tokenId ID of token1438 * @example getTokenObject(10, 5);1439 * @returns instance of UniqueNFTToken1440 */1441 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1442 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1443 }14441445 /**1446 * Get top 10 token owners with the largest number of pieces 1447 * @param collectionId ID of collection1448 * @param tokenId ID of token1449 * @example getTokenTop10Owners(10, 5);1450 * @returns array of top 10 owners1451 */1452 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1453 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1454 }14551456 /**1457 * Get number of pieces owned by address1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param addressObj address token owner1461 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1462 * @returns number of pieces ownerd by address1463 */1464 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1465 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1466 }14671468 /**1469 * Transfer pieces of token to another address1470 * @param signer keyring of signer1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param addressObj address of a new owner1474 * @param amount number of pieces to be transfered1475 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1476 * @returns ```true``` if extrinsic success, otherwise ```false```1477 */1478 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1479 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1480 }14811482 /**1483 * Change ownership of some pieces of RFT on behalf of the owner. 1484 * @param signer keyring of signer1485 * @param collectionId ID of collection1486 * @param tokenId ID of token1487 * @param fromAddressObj address on behalf of which the token will be sent1488 * @param toAddressObj new token owner1489 * @param amount number of pieces to be transfered1490 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1491 * @returns ```true``` if extrinsic success, otherwise ```false```1492 */1493 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1494 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1495 }14961497 /**1498 * Mint new collection1499 * @param signer keyring of signer1500 * @param collectionOptions Collection options1501 * @example1502 * mintCollection(aliceKeyring, {1503 * name: 'New',1504 * description: 'New collection',1505 * tokenPrefix: 'NEW',1506 * })1507 * @returns object of the created collection1508 */1509 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1510 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1511 }15121513 /**1514 * Mint new token1515 * @param signer keyring of signer1516 * @param data token data1517 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1518 * @returns created token object1519 */1520 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1521 const creationResult = await this.helper.executeExtrinsic(1522 signer,1523 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1524 refungible: {1525 pieces: data.pieces,1526 properties: data.properties,1527 },1528 }],1529 true,1530 );1531 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1532 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1533 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1534 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1535 }15361537 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1538 throw Error('Not implemented');1539 const creationResult = await this.helper.executeExtrinsic(1540 signer,1541 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1542 true, // `Unable to mint RFT tokens for ${label}`,1543 );1544 const collection = this.getCollectionObject(collectionId);1545 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1546 }15471548 /**1549 * Mint multiple RFT tokens with one owner1550 * @param signer keyring of signer1551 * @param collectionId ID of collection1552 * @param owner tokens owner1553 * @param tokens array of tokens with properties and pieces1554 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1555 * @returns array of newly created RFT tokens1556 */1557 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1558 const rawTokens = [];1559 for (const token of tokens) {1560 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1561 rawTokens.push(raw);1562 }1563 const creationResult = await this.helper.executeExtrinsic(1564 signer,1565 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1566 true,1567 );1568 const collection = this.getCollectionObject(collectionId);1569 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1570 }15711572 /**1573 * Destroys a concrete instance of RFT.1574 * @param signer keyring of signer1575 * @param collectionId ID of collection1576 * @param tokenId ID of token1577 * @param amount number of pieces to be burnt1578 * @example burnToken(aliceKeyring, 10, 5);1579 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1580 */1581 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1582 return await super.burnToken(signer, collectionId, tokenId, amount);1583 }15841585 /**1586 * Set, change, or remove approved address to transfer the ownership of the RFT.1587 * 1588 * @param signer keyring of signer1589 * @param collectionId ID of collection1590 * @param tokenId ID of token1591 * @param toAddressObj address to approve1592 * @param amount number of pieces to be approved1593 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1594 * @returns true if the token success, otherwise false1595 */1596 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1597 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1598 }15991600 /**1601 * Get total number of pieces1602 * @param collectionId ID of collection1603 * @param tokenId ID of token1604 * @example getTokenTotalPieces(10, 5);1605 * @returns number of pieces1606 */1607 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1608 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1609 }16101611 /**1612 * Change number of token pieces. Signer must be the owner of all token pieces.1613 * @param signer keyring of signer1614 * @param collectionId ID of collection1615 * @param tokenId ID of token1616 * @param amount new number of pieces1617 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1618 * @returns true if the repartion was success, otherwise false1619 */1620 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1621 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1622 const repartitionResult = await this.helper.executeExtrinsic(1623 signer,1624 'api.tx.unique.repartition', [collectionId, tokenId, amount],1625 true,1626 );1627 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1628 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1629 }1630}163116321633class FTGroup extends CollectionGroup {1634 /**1635 * Get collection object1636 * @param collectionId ID of collection1637 * @example getCollectionObject(2);1638 * @returns instance of UniqueFTCollection1639 */1640 getCollectionObject(collectionId: number): UniqueFTCollection {1641 return new UniqueFTCollection(collectionId, this.helper);1642 }16431644 /**1645 * Mint new fungible collection1646 * @param signer keyring of signer1647 * @param collectionOptions Collection options1648 * @param decimalPoints number of token decimals 1649 * @example1650 * mintCollection(aliceKeyring, {1651 * name: 'New',1652 * description: 'New collection',1653 * tokenPrefix: 'NEW',1654 * }, 18)1655 * @returns newly created fungible collection1656 */1657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1658 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1659 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1660 collectionOptions.mode = {fungible: decimalPoints};1661 for (const key of ['name', 'description', 'tokenPrefix']) {1662 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createCollectionEx', [collectionOptions],1667 true,1668 );1669 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1670 }16711672 /**1673 * Mint tokens1674 * @param signer keyring of signer1675 * @param collectionId ID of collection1676 * @param owner address owner of new tokens1677 * @param amount amount of tokens to be meanted1678 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1679 * @returns ```true``` if extrinsic success, otherwise ```false``` 1680 */1681 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1682 const creationResult = await this.helper.executeExtrinsic(1683 signer,1684 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1685 fungible: {1686 value: amount,1687 },1688 }],1689 true, // `Unable to mint fungible tokens for ${label}`,1690 );1691 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1692 }16931694 /**1695 * Mint multiple Fungible tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with properties and pieces1700 * @returns ```true``` if extrinsic success, otherwise ```false``` 1701 */1702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1703 const rawTokens = [];1704 for (const token of tokens) {1705 const raw = {Fungible: {Value: token.value}};1706 rawTokens.push(raw);1707 }1708 const creationResult = await this.helper.executeExtrinsic(1709 signer,1710 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1711 true,1712 );1713 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1714 }17151716 /**1717 * Get the top 10 owners with the largest balance for the Fungible collection 1718 * @param collectionId ID of collection1719 * @example getTop10Owners(10);1720 * @returns array of ```ICrossAccountId```1721 */1722 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724 }17251726 /**1727 * Get account balance1728 * @param collectionId ID of collection1729 * @param addressObj address of owner1730 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1731 * @returns amount of fungible tokens owned by address1732 */1733 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735 }17361737 /**1738 * Transfer tokens to address1739 * @param signer keyring of signer1740 * @param collectionId ID of collection1741 * @param toAddressObj address recipient1742 * @param amount amount of tokens to be sent1743 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1744 * @returns ```true``` if extrinsic success, otherwise ```false``` 1745 */1746 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1747 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748 }17491750 /**1751 * Transfer some tokens on behalf of the owner.1752 * @param signer keyring of signer1753 * @param collectionId ID of collection1754 * @param fromAddressObj address on behalf of which tokens will be sent1755 * @param toAddressObj address where token to be sent1756 * @param amount number of tokens to be sent1757 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1758 * @returns ```true``` if extrinsic success, otherwise ```false``` 1759 */1760 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1761 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1762 }17631764 /**1765 * Destroy some amount of tokens1766 * @param signer keyring of signer1767 * @param collectionId ID of collection1768 * @param amount amount of tokens to be destroyed1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1783 * @returns ```true``` if extrinsic success, otherwise ```false``` 1784 */1785 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1786 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1787 }17881789 /**1790 * Get total collection supply1791 * @param collectionId 1792 * @returns 1793 */1794 async getTotalPieces(collectionId: number): Promise<bigint> {1795 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1796 }17971798 /**1799 * Set, change, or remove approved address to transfer tokens.1800 * 1801 * @param signer keyring of signer1802 * @param collectionId ID of collection1803 * @param toAddressObj address to be approved1804 * @param amount amount of tokens to be approved1805 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1806 * @returns ```true``` if extrinsic success, otherwise ```false``` 1807 */1808 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1809 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1810 }18111812 /**1813 * Get amount of fungible tokens approved to transfer1814 * @param collectionId ID of collection1815 * @param fromAddressObj owner of tokens1816 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1817 * @returns number of tokens approved for the transfer1818 */1819 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1820 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1821 }1822}182318241825class ChainGroup extends HelperGroup {1826 /**1827 * Get system properties of a chain1828 * @example getChainProperties();1829 * @returns ss58Format, token decimals, and token symbol1830 */1831 getChainProperties(): IChainProperties {1832 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1833 return {1834 ss58Format: properties.ss58Format.toJSON(),1835 tokenDecimals: properties.tokenDecimals.toJSON(),1836 tokenSymbol: properties.tokenSymbol.toJSON(),1837 };1838 }18391840 /**1841 * Get chain header1842 * @example getLatestBlockNumber();1843 * @returns the number of the last block1844 */1845 async getLatestBlockNumber(): Promise<number> {1846 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1847 }18481849 /**1850 * Get block hash by block number1851 * @param blockNumber number of block1852 * @example getBlockHashByNumber(12345);1853 * @returns hash of a block1854 */1855 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1856 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1857 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1858 return blockHash;1859 }18601861 // TODO add docs1862 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1863 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1864 if (!blockHash) return null;1865 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1866 }18671868 /**1869 * Get account nonce1870 * @param address substrate address1871 * @example getNonce("5GrwvaEF5zXb26Fz...");1872 * @returns number, account's nonce1873 */1874 async getNonce(address: TSubstrateAccount): Promise<number> {1875 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1876 }1877}187818791880class BalanceGroup extends HelperGroup {1881 /**1882 * Representation of the native token in the smallest unit1883 * @example getOneTokenNominal()1884 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1885 */1886 getOneTokenNominal(): bigint {1887 const chainProperties = this.helper.chain.getChainProperties();1888 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1889 }18901891 /**1892 * Get substrate address balance1893 * @param address substrate address1894 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1895 * @returns amount of tokens on address1896 */1897 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1898 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1899 }19001901 /**1902 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1903 * @param address substrate address1904 * @returns 1905 */1906 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1907 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1908 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1909 }19101911 /**1912 * Get ethereum address balance1913 * @param address ethereum address1914 * @example getEthereum("0x9F0583DbB855d...")1915 * @returns amount of tokens on address1916 */1917 async getEthereum(address: TEthereumAccount): Promise<bigint> {1918 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1919 }19201921 /**1922 * Transfer tokens to substrate address1923 * @param signer keyring of signer1924 * @param address substrate address of a recipient1925 * @param amount amount of tokens to be transfered1926 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1930 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);19311932 let transfer = {from: null, to: null, amount: 0n} as any;1933 result.result.events.forEach(({event: {data, method, section}}) => {1934 if ((section === 'balances') && (method === 'Transfer')) {1935 transfer = {1936 from: this.helper.address.normalizeSubstrate(data[0]),1937 to: this.helper.address.normalizeSubstrate(data[1]),1938 amount: BigInt(data[2]),1939 };1940 }1941 });1942 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1943 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1944 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1945 return isSuccess;1946 }1947}194819491950class AddressGroup extends HelperGroup {1951 /**1952 * Normalizes the address to the specified ss58 format, by default ```42```.1953 * @param address substrate address1954 * @param ss58Format format for address conversion, by default ```42```1955 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1956 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1957 */1958 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1959 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1960 }19611962 /**1963 * Get address in the connected chain format1964 * @param address substrate address1965 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1966 * @returns address in chain format1967 */1968 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1969 const info = this.helper.chain.getChainProperties();1970 return encodeAddress(decodeAddress(address), info.ss58Format);1971 }19721973 /**1974 * Get substrate mirror of an ethereum address1975 * @param ethAddress ethereum address1976 * @param toChainFormat false for normalized account1977 * @example ethToSubstrate('0x9F0583DbB855d...')1978 * @returns substrate mirror of a provided ethereum address1979 */1980 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1981 if(!toChainFormat) return evmToAddress(ethAddress);1982 const info = this.helper.chain.getChainProperties();1983 return evmToAddress(ethAddress, info.ss58Format);1984 }19851986 /**1987 * Get ethereum mirror of a substrate address1988 * @param subAddress substrate account1989 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1990 * @returns ethereum mirror of a provided substrate address1991 */1992 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1993 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1994 }1995}19961997class StakingGroup extends HelperGroup {1998 /**1999 * Stake tokens for App Promotion2000 * @param signer keyring of signer2001 * @param amountToStake amount of tokens to stake2002 * @param label extra label for log2003 * @returns2004 */2005 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2006 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2007 const stakeResult = await this.helper.executeExtrinsic(2008 signer, 'api.tx.appPromotion.stake',2009 [amountToStake], true,2010 );2011 // TODO extract info from stakeResult2012 return true;2013 }20142015 /**2016 * Unstake tokens for App Promotion2017 * @param signer keyring of signer2018 * @param amountToUnstake amount of tokens to unstake2019 * @param label extra label for log2020 * @returns block number where balances will be unlocked2021 */2022 async unstake(signer: TSigner, label?: string): Promise<number> {2023 if(typeof label === 'undefined') label = `${signer.address}`;2024 const unstakeResult = await this.helper.executeExtrinsic(2025 signer, 'api.tx.appPromotion.unstake', 2026 [], true,2027 );2028 // TODO extract block number fron events2029 return 1;2030 }20312032 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2033 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2034 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2035 }20362037 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2038 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2039 }20402041 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2042 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2043 }2044 2045 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2046 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2047 }2048}20492050export class UniqueHelper extends ChainHelperBase {2051 chain: ChainGroup;2052 balance: BalanceGroup;2053 address: AddressGroup;2054 collection: CollectionGroup;2055 nft: NFTGroup;2056 rft: RFTGroup;2057 ft: FTGroup;2058 staking: StakingGroup;20592060 constructor(logger?: ILogger) {2061 super(logger);2062 this.chain = new ChainGroup(this);2063 this.balance = new BalanceGroup(this);2064 this.address = new AddressGroup(this);2065 this.collection = new CollectionGroup(this);2066 this.nft = new NFTGroup(this);2067 this.rft = new RFTGroup(this);2068 this.ft = new FTGroup(this);2069 this.staking = new StakingGroup(this);2070 } 2071}207220732074class UniqueCollectionBase {2075 helper: UniqueHelper;2076 collectionId: number;20772078 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2079 this.collectionId = collectionId;2080 this.helper = uniqueHelper;2081 }20822083 async getData() {2084 return await this.helper.collection.getData(this.collectionId);2085 }20862087 async getLastTokenId() {2088 return await this.helper.collection.getLastTokenId(this.collectionId);2089 }20902091 async isTokenExists(tokenId: number) {2092 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2093 }20942095 async getAdmins() {2096 return await this.helper.collection.getAdmins(this.collectionId);2097 }20982099 async getAllowList() {2100 return await this.helper.collection.getAllowList(this.collectionId);2101 }21022103 async getEffectiveLimits() {2104 return await this.helper.collection.getEffectiveLimits(this.collectionId);2105 }21062107 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2108 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2109 }21102111 async confirmSponsorship(signer: TSigner) {2112 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2113 }21142115 async removeSponsor(signer: TSigner) {2116 return await this.helper.collection.removeSponsor(signer, this.collectionId);2117 }21182119 async setLimits(signer: TSigner, limits: ICollectionLimits) {2120 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2121 }21222123 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2124 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2125 }21262127 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2128 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2129 }21302131 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2132 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2133 }21342135 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2136 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2137 }21382139 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2140 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2141 }21422143 async setProperties(signer: TSigner, properties: IProperty[]) {2144 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2145 }21462147 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2148 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2149 }21502151 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2152 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2153 }21542155 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2156 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2157 }21582159 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2160 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2161 }21622163 async disableNesting(signer: TSigner) {2164 return await this.helper.collection.disableNesting(signer, this.collectionId);2165 }21662167 async burn(signer: TSigner) {2168 return await this.helper.collection.burn(signer, this.collectionId);2169 }2170}217121722173class UniqueNFTCollection extends UniqueCollectionBase {2174 getTokenObject(tokenId: number) {2175 return new UniqueNFTToken(tokenId, this);2176 }21772178 async getTokensByAddress(addressObj: ICrossAccountId) {2179 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2180 }21812182 async getToken(tokenId: number, blockHashAt?: string) {2183 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2184 }21852186 async getTokenOwner(tokenId: number, blockHashAt?: string) {2187 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2188 }21892190 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2191 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2192 }21932194 async getTokenChildren(tokenId: number, blockHashAt?: string) {2195 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2196 }21972198 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2199 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2200 }22012202 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2203 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2204 }22052206 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2207 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2208 }22092210 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2211 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2212 }22132214 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2215 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2216 }22172218 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2219 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2220 }22212222 async burnToken(signer: TSigner, tokenId: number) {2223 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2224 }22252226 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2227 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2228 }22292230 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2231 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2232 }22332234 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2235 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2236 }22372238 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2239 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2240 }22412242 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2243 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2244 }2245}224622472248class UniqueRFTCollection extends UniqueCollectionBase {2249 getTokenObject(tokenId: number) {2250 return new UniqueRFTToken(tokenId, this);2251 }22522253 async getTokensByAddress(addressObj: ICrossAccountId) {2254 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2255 }22562257 async getTop10TokenOwners(tokenId: number) {2258 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2259 }22602261 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2262 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2263 }22642265 async getTokenTotalPieces(tokenId: number) {2266 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2267 }22682269 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2270 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2271 }22722273 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2274 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2275 }22762277 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2278 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2279 }22802281 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2282 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2283 }22842285 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2286 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2287 }22882289 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2290 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2291 }22922293 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2294 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2295 }22962297 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2298 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2299 }23002301 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2302 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2303 }23042305 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2306 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2307 }23082309 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2310 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2311 }2312}231323142315class UniqueFTCollection extends UniqueCollectionBase {2316 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2317 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2318 }23192320 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2321 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2322 }23232324 async getBalance(addressObj: ICrossAccountId) {2325 return await this.helper.ft.getBalance(this.collectionId, addressObj);2326 }23272328 async getTop10Owners() {2329 return await this.helper.ft.getTop10Owners(this.collectionId);2330 }23312332 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2333 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2334 }23352336 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2337 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2338 }23392340 async burnTokens(signer: TSigner, amount=1n) {2341 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2342 }23432344 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2345 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2346 }23472348 async getTotalPieces() {2349 return await this.helper.ft.getTotalPieces(this.collectionId);2350 }23512352 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2353 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2354 }23552356 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2357 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2358 }2359}236023612362class UniqueTokenBase implements IToken {2363 collection: UniqueNFTCollection | UniqueRFTCollection;2364 collectionId: number;2365 tokenId: number;23662367 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2368 this.collection = collection;2369 this.collectionId = collection.collectionId;2370 this.tokenId = tokenId;2371 }23722373 async getNextSponsored(addressObj: ICrossAccountId) {2374 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2375 }23762377 async setProperties(signer: TSigner, properties: IProperty[]) {2378 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2379 }23802381 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2382 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2383 }2384}238523862387class UniqueNFTToken extends UniqueTokenBase {2388 collection: UniqueNFTCollection;23892390 constructor(tokenId: number, collection: UniqueNFTCollection) {2391 super(tokenId, collection);2392 this.collection = collection;2393 }23942395 async getData(blockHashAt?: string) {2396 return await this.collection.getToken(this.tokenId, blockHashAt);2397 }23982399 async getOwner(blockHashAt?: string) {2400 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2401 }24022403 async getTopmostOwner(blockHashAt?: string) {2404 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2405 }24062407 async getChildren(blockHashAt?: string) {2408 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2409 }24102411 async nest(signer: TSigner, toTokenObj: IToken) {2412 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2413 }24142415 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2416 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2417 }24182419 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2420 return await this.collection.transferToken(signer, this.tokenId, addressObj);2421 }24222423 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2424 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2425 }24262427 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2428 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2429 }24302431 async isApproved(toAddressObj: ICrossAccountId) {2432 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2433 }24342435 async burn(signer: TSigner) {2436 return await this.collection.burnToken(signer, this.tokenId);2437 }2438}24392440class UniqueRFTToken extends UniqueTokenBase {2441 collection: UniqueRFTCollection;24422443 constructor(tokenId: number, collection: UniqueRFTCollection) {2444 super(tokenId, collection);2445 this.collection = collection;2446 }24472448 async getTop10Owners() {2449 return await this.collection.getTop10TokenOwners(this.tokenId);2450 }24512452 async getBalance(addressObj: ICrossAccountId) {2453 return await this.collection.getTokenBalance(this.tokenId, addressObj);2454 }24552456 async getTotalPieces() {2457 return await this.collection.getTokenTotalPieces(this.tokenId);2458 }24592460 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2461 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2462 }24632464 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2465 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2466 }24672468 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2469 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2470 }24712472 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2473 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2474 }24752476 async repartition(signer: TSigner, amount: bigint) {2477 return await this.collection.repartitionToken(signer, this.tokenId, amount);2478 }24792480 async burn(signer: TSigner, amount=1n) {2481 return await this.collection.burnToken(signer, this.tokenId, amount);2482 }2483}tests/src/xcmTransfer.test.tsdiffbeforeafterboth--- a/tests/src/xcmTransfer.test.ts
+++ b/tests/src/xcmTransfer.test.ts
@@ -33,6 +33,7 @@
const KARURA_PORT = '9946';
const TRANSFER_AMOUNT = 2000000000000000000000000n;
+// todo:playgrounds refit when XCM drops
describe.skip('Integration test: Exchanging QTZ with Karura', () => {
let alice: IKeyringPair;