difftreelog
tests(playgrounds): updates and revisions for older tests on playgrounds
in: master
9 files changed
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -31,11 +31,11 @@
itSub('Changing owner changes owner address', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const beforeChanging = await helper.collection.getData(collection.collectionId);
- expect(beforeChanging?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(alice.address));
+ expect(beforeChanging?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(alice.address));
await collection.changeOwner(alice, bob.address);
const afterChanging = await helper.collection.getData(collection.collectionId);
- expect(afterChanging?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(bob.address));
+ expect(afterChanging?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(bob.address));
});
});
@@ -60,7 +60,7 @@
await expect(changeOwnerTx()).to.be.rejectedWith(/common\.NoPermission/);
const afterChanging = await helper.collection.getData(collection.collectionId);
- expect(afterChanging?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(bob.address));
+ expect(afterChanging?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(bob.address));
});
itSub('New collectionOwner has access to sponsorship management operations in the collection', async ({helper}) => {
@@ -68,7 +68,7 @@
await collection.changeOwner(alice, bob.address);
const afterChanging = await helper.collection.getData(collection.collectionId);
- expect(afterChanging?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(bob.address));
+ expect(afterChanging?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(bob.address));
await collection.setSponsor(bob, charlie.address);
await collection.confirmSponsorship(charlie);
@@ -97,7 +97,7 @@
await collection.changeOwner(alice, bob.address);
await collection.changeOwner(bob, charlie.address);
const collectionData = await collection.getData();
- expect(collectionData?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(charlie.address));
+ expect(collectionData?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(charlie.address));
});
});
@@ -140,7 +140,7 @@
await expect(changeOwnerTx()).to.be.rejectedWith(/common\.NoPermission/);
const afterChanging = await helper.collection.getData(collection.collectionId);
- expect(afterChanging?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(bob.address));
+ expect(afterChanging?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(bob.address));
const setSponsorTx = async () => collection.setSponsor(alice, charlie.address);
const confirmSponsorshipTx = async () => collection.confirmSponsorship(alice);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -14,12 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {IKeyringPair} from '@polkadot/types/types';
import {usingPlaygrounds, expect, itSub, Pallets} from './util/playgrounds';
-import {IKeyringPair} from '@polkadot/types/types';
import {ICollectionCreationOptions, IProperty} from './util/playgrounds/types';
-import {DevUniqueHelper} from './util/playgrounds/unique.dev';
+import {UniqueHelper} from './util/playgrounds/unique';
-async function mintCollectionHelper(helper: DevUniqueHelper, signer: IKeyringPair, options: ICollectionCreationOptions, type?: 'nft' | 'fungible' | 'refungible') {
+async function mintCollectionHelper(helper: UniqueHelper, signer: IKeyringPair, options: ICollectionCreationOptions, type?: 'nft' | 'fungible' | 'refungible') {
let collection;
if (type === 'nft') {
collection = await helper.nft.mintCollection(signer, options);
@@ -29,7 +29,7 @@
collection = await helper.rft.mintCollection(signer, options);
}
const data = await collection.getData();
- expect(data?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(signer.address));
+ expect(data?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(signer.address));
expect(data?.name).to.be.equal(options.name);
expect(data?.description).to.be.equal(options.description);
expect(data?.raw.tokenPrefix).to.be.equal(options.tokenPrefix);
@@ -54,32 +54,27 @@
});
});
itSub('Create new NFT collection', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 'nft');
});
itSub('Create new NFT collection whith collection_name of maximum length (64 bytes)', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'A'.repeat(64), description: 'descr', tokenPrefix: 'COL'}, 'nft');
});
itSub('Create new NFT collection whith collection_description of maximum length (256 bytes)', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'name', description: 'A'.repeat(256), tokenPrefix: 'COL'}, 'nft');
});
itSub('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'A'.repeat(16)}, 'nft');
});
+
itSub('Create new Fungible collection', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'}, 'fungible');
});
+
itSub.ifWithPallets('Create new ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'}, 'refungible');
});
itSub('create new collection with properties', async ({helper}) => {
-
await mintCollectionHelper(helper, alice, {
name: 'name', description: 'descr', tokenPrefix: 'COL',
properties: [{key: 'key1', value: 'val1'}],
@@ -88,7 +83,6 @@
});
itSub('Create new collection with extra fields', async ({helper}) => {
-
const collection = await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'}, 'fungible');
await collection.setPermissions(alice, {access: 'AllowList'});
await collection.setLimits(alice, {accountTokenOwnershipLimit: 3});
@@ -96,7 +90,7 @@
const limits = await collection.getEffectiveLimits();
const raw = data?.raw;
- expect(data?.normalizedOwner).to.be.equal(helper.util.normalizeSubstrateAddress(alice.address));
+ expect(data?.normalizedOwner).to.be.equal(helper.address.normalizeSubstrate(alice.address));
expect(data?.name).to.be.equal('name');
expect(data?.description).to.be.equal('descr');
expect(raw.permissions.access).to.be.equal('AllowList');
@@ -105,7 +99,6 @@
});
itSub('New collection is not external', async ({helper}) => {
-
const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'});
const data = await collection.getData();
expect(data?.raw.readOnly).to.be.false;
@@ -131,12 +124,11 @@
await expect(mintCollectionTx()).to.be.rejectedWith('Verification Error');
});
itSub('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async ({helper}) => {
-
const mintCollectionTx = async () => helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'A'.repeat(17)});
await expect(mintCollectionTx()).to.be.rejectedWith('Verification Error');
});
+
itSub('(!negative test!) fails when bad limits are set', async ({helper}) => {
-
const mintCollectionTx = async () => helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'COL', limits: {tokenLimit: 0}});
await expect(mintCollectionTx()).to.be.rejectedWith(/common\.CollectionTokenLimitExceeded/);
});
tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -15,24 +15,14 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-
-import {
- createCollection,
- itApi,
- normalizeAccountId,
- getCreateItemResult,
- CrossAccountId,
-} from './util/helpers';
-
import {usingPlaygrounds, expect, itSub, Pallets} from './util/playgrounds';
-import {IProperty} from './util/playgrounds/types';
-import {executeTransaction} from './substrate/substrate-api';
-import {DevUniqueHelper} from './util/playgrounds/unique.dev';
+import {IProperty, ICrossAccountId} from './util/playgrounds/types';
+import {UniqueHelper} from './util/playgrounds/unique';
-async function mintTokenHelper(helper: DevUniqueHelper, collection: any, signer: IKeyringPair, owner: CrossAccountId, type: 'nft' | 'fungible' | 'refungible'='nft', properties?: IProperty[]) {
+async function mintTokenHelper(helper: UniqueHelper, collection: any, signer: IKeyringPair, owner: ICrossAccountId, type: 'nft' | 'fungible' | 'refungible'='nft', properties?: IProperty[]) {
let token;
const itemCountBefore = await helper.collection.getLastTokenId(collection.collectionId);
- const itemBalanceBefore = (await helper.api!.rpc.unique.balance(collection.collectionId, owner, 0)).toBigInt();
+ const itemBalanceBefore = (await helper.callRpc('api.rpc.unique.balance', [collection.collectionId, owner, 0])).toBigInt();
if (type === 'nft') {
token = await collection.mintToken(signer, owner, properties);
} else if (type === 'fungible') {
@@ -42,7 +32,7 @@
}
const itemCountAfter = await helper.collection.getLastTokenId(collection.collectionId);
- const itemBalanceAfter = (await helper.api!.rpc.unique.balance(collection.collectionId, owner, 0)).toBigInt();
+ const itemBalanceAfter = (await helper.callRpc('api.rpc.unique.balance', [collection.collectionId, owner, 0])).toBigInt();
if (type === 'fungible') {
expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
@@ -75,27 +65,22 @@
});
itSub('Check events on create new item in Fungible collection', async ({helper}) => {
const {collectionId} = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}, 0);
- const api = helper.api!;
-
-
- const to = normalizeAccountId(alice);
+ const to = {Substrate: alice.address};
{
const createData = {fungible: {value: 100}};
- const tx = api.tx.unique.createItem(collectionId, to, createData as any);
- const events = await executeTransaction(api, alice, tx);
- const result = getCreateItemResult(events);
- expect(result.amount).to.be.equal(100);
- expect(result.collectionId).to.be.equal(collectionId);
- expect(result.recipient).to.be.deep.equal(to);
+ const events = await helper.executeExtrinsic(alice, 'api.tx.unique.createItem', [collectionId, to, createData as any]);
+ const result = helper.util.extractTokensFromCreationResult(events);
+ expect(result.tokens[0].amount).to.be.equal(100n);
+ expect(result.tokens[0].collectionId).to.be.equal(collectionId);
+ expect(result.tokens[0].owner).to.be.deep.equal(to);
}
{
const createData = {fungible: {value: 50}};
- const tx = api.tx.unique.createItem(collectionId, to, createData as any);
- const events = await executeTransaction(api, alice, tx);
- const result = getCreateItemResult(events);
- expect(result.amount).to.be.equal(50);
- expect(result.collectionId).to.be.equal(collectionId);
- expect(result.recipient).to.be.deep.equal(to);
+ const events = await helper.executeExtrinsic(alice, 'api.tx.unique.createItem', [collectionId, to, createData as any]);
+ const result = helper.util.extractTokensFromCreationResult(events);
+ expect(result.tokens[0].amount).to.be.equal(50n);
+ expect(result.tokens[0].collectionId).to.be.equal(collectionId);
+ expect(result.tokens[0].owner).to.be.deep.equal(to);
}
});
itSub.ifWithPallets('Create new item in ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
@@ -162,12 +147,12 @@
const amount = 1n;
const token = await mintTokenHelper(helper, collection, alice, {Substrate: bob.address});
{
- const totalPieces = await helper.api?.rpc.unique.totalPieces(collection.collectionId, token.tokenId);
+ const totalPieces = await helper.callRpc('api.rpc.unique.totalPieces', [collection.collectionId, token.tokenId]);
expect(totalPieces?.unwrap().toBigInt()).to.be.equal(amount);
}
await token.transfer(bob, {Substrate: alice.address});
{
- const totalPieces = await helper.api?.rpc.unique.totalPieces(collection.collectionId, token.tokenId);
+ const totalPieces = await helper.callRpc('api.rpc.unique.totalPieces', [collection.collectionId, token.tokenId]);
expect(totalPieces?.unwrap().toBigInt()).to.be.equal(amount);
}
});
@@ -267,21 +252,21 @@
itSub('Check total pieces for invalid Fungible token', async ({helper}) => {
const collection = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
const invalidTokenId = 1_000_000;
- expect((await helper.api?.rpc.unique.totalPieces(collection.collectionId, invalidTokenId))?.isNone).to.be.true;
- expect((await helper.api?.rpc.unique.tokenData(collection.collectionId, invalidTokenId))?.pieces.toBigInt()).to.be.equal(0n);
+ expect((await helper.callRpc('api.rpc.unique.totalPieces', [collection.collectionId, invalidTokenId]))?.isNone).to.be.true;
+ expect((await helper.callRpc('api.rpc.unique.tokenData', [collection.collectionId, invalidTokenId]))?.pieces.toBigInt()).to.be.equal(0n);
});
itSub('Check total pieces for invalid NFT token', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const invalidTokenId = 1_000_000;
- expect((await helper.api?.rpc.unique.totalPieces(collection.collectionId, invalidTokenId))?.isNone).to.be.true;
- expect((await helper.api?.rpc.unique.tokenData(collection.collectionId, invalidTokenId))?.pieces.toBigInt()).to.be.equal(0n);
+ expect((await helper.callRpc('api.rpc.unique.totalPieces', [collection.collectionId, invalidTokenId]))?.isNone).to.be.true;
+ expect((await helper.callRpc('api.rpc.unique.tokenData', [collection.collectionId, invalidTokenId]))?.pieces.toBigInt()).to.be.equal(0n);
});
itSub.ifWithPallets('Check total pieces for invalid Refungible token', [Pallets.ReFungible], async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const invalidTokenId = 1_000_000;
- expect((await helper.api?.rpc.unique.totalPieces(collection.collectionId, invalidTokenId))?.isNone).to.be.true;
- expect((await helper.api?.rpc.unique.tokenData(collection.collectionId, invalidTokenId))?.pieces.toBigInt()).to.be.equal(0n);
+ expect((await helper.callRpc('api.rpc.unique.totalPieces', [collection.collectionId, invalidTokenId]))?.isNone).to.be.true;
+ expect((await helper.callRpc('api.rpc.unique.tokenData', [collection.collectionId, invalidTokenId]))?.pieces.toBigInt()).to.be.equal(0n);
});
});
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -15,12 +15,8 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {
- normalizeAccountId,
-} from './util/helpers';
import {usingPlaygrounds, expect, Pallets, itSub} from './util/playgrounds';
-
describe('Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
let alice: IKeyringPair;
@@ -48,7 +44,7 @@
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
for (const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
- expect(tokenData?.normalizedOwner).to.be.deep.equal({Substrate: helper.util.normalizeSubstrateAddress(alice.address)});
+ expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
}
});
@@ -116,7 +112,7 @@
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
for (const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
- expect(tokenData?.normalizedOwner).to.be.deep.equal({Substrate: helper.util.normalizeSubstrateAddress(alice.address)});
+ expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
}
});
@@ -138,7 +134,7 @@
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
for (const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
- expect(tokenData?.normalizedOwner).to.be.deep.equal({Substrate: helper.util.normalizeSubstrateAddress(alice.address)});
+ expect(tokenData?.normalizedOwner.Substrate).to.be.deep.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
}
});
@@ -160,7 +156,7 @@
const tokens = await helper.nft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, args);
for (const [i, token] of tokens.entries()) {
const tokenData = await token.getData();
- expect(tokenData?.normalizedOwner).to.be.deep.equal({Substrate: helper.util.normalizeSubstrateAddress(alice.address)});
+ expect(tokenData?.normalizedOwner.Substrate).to.be.equal(helper.address.normalizeSubstrate(alice.address));
expect(tokenData?.properties[0].value).to.be.equal(args[i].properties[0].value);
}
});
@@ -275,8 +271,11 @@
});
const types = ['NFT', 'Fungible', 'ReFungible'];
- const mintTx = helper.api?.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), types);
- await expect(helper.signTransaction(alice, mintTx)).to.be.rejected;
+ await expect(helper.executeExtrinsic(
+ alice,
+ 'api.tx.unique.createMultipleItems',
+ [collectionId, {Substrate: alice.address}, types],
+ )).to.be.rejectedWith(/nonfungible\.NotNonfungibleDataUsedToMintFungibleCollectionToken/);
});
itSub('Create tokens with different data limits <> maximum data limit', async ({helper}) => {
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -16,11 +16,6 @@
import './interfaces/augment-api-consts';
import {IKeyringPair} from '@polkadot/types/types';
-import {
- UNIQUE,
-} from './util/helpers';
-
-import {default as waitNewBlocks} from './substrate/wait-new-blocks';
import {ApiPromise} from '@polkadot/api';
import {usingPlaygrounds, expect, itSub} from './util/playgrounds';
@@ -63,7 +58,7 @@
itSub('Total issuance does not change', async ({helper}) => {
const api = helper.api!;
await skipInflationBlock(api);
- await waitNewBlocks(api, 1);
+ await helper.wait.newBlocks(1);
const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
@@ -75,9 +70,8 @@
});
itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {
- const api = helper.api!;
- await skipInflationBlock(api);
- await waitNewBlocks(api, 1);
+ await skipInflationBlock(helper.api!);
+ await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -96,7 +90,7 @@
itSub('Treasury balance increased by failed tx fee', async ({helper}) => {
const api = helper.api!;
- await waitNewBlocks(api, 1);
+ await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
const bobBalanceBefore = await helper.balance.getSubstrate(bob.address);
@@ -113,9 +107,8 @@
});
itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {
- const api = helper.api!;
- await skipInflationBlock(api);
- await waitNewBlocks(api, 1);
+ await skipInflationBlock(helper.api!);
+ await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -131,9 +124,9 @@
});
itSub('Fees are sane', async ({helper}) => {
- const api = helper.api!;
- await skipInflationBlock(api);
- await waitNewBlocks(api, 1);
+ const unique = helper.balance.getOneTokenNominal();
+ await skipInflationBlock(helper.api!);
+ await helper.wait.newBlocks(1);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -142,14 +135,13 @@
const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
const fee = aliceBalanceBefore - aliceBalanceAfter;
- expect(fee / UNIQUE < BigInt(Math.ceil(saneMaximumFee + createCollectionDeposit))).to.be.true;
- expect(fee / UNIQUE < BigInt(Math.ceil(saneMinimumFee + createCollectionDeposit))).to.be.true;
+ expect(fee / unique < BigInt(Math.ceil(saneMaximumFee + createCollectionDeposit))).to.be.true;
+ expect(fee / unique < BigInt(Math.ceil(saneMinimumFee + createCollectionDeposit))).to.be.true;
});
itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {
- const api = helper.api!;
- await skipInflationBlock(api);
- await waitNewBlocks(api, 1);
+ await skipInflationBlock(helper.api!);
+ await helper.wait.newBlocks(1);
const collection = await helper.nft.mintCollection(alice, {
name: 'test',
@@ -163,7 +155,7 @@
await token.transfer(alice, {Substrate: bob.address});
const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
- const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);
+ const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal());
const expectedTransferFee = 0.1;
// fee drifts because of NextFeeMultiplier
const tolerance = 0.001;
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -15,10 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {
- Pallets,
-} from './util/helpers';
-import {itSub, expect, usingPlaygrounds} from './util/playgrounds';
+import {itSub, expect, usingPlaygrounds, Pallets} from './util/playgrounds';
describe('integration test: ext. destroyCollection():', () => {
let alice: IKeyringPair;
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -666,7 +666,6 @@
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
}
-
}
const properties = await nestedToken.getProperties(propertyKeys);
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -124,7 +124,7 @@
const token = await collection.mintToken(alice, 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 token.burn(alice, 99n)).to.be.true;
expect(await collection.isTokenExists(token.tokenId)).to.be.true;
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
@@ -136,7 +136,7 @@
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 token.burn(alice, 100n)).to.be.true;
expect(await collection.isTokenExists(token.tokenId)).to.be.false;
});
@@ -152,17 +152,17 @@
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)).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 token.burn(bob, 59n)).success).to.be.true;
+ expect(await token.burn(bob, 59n)).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)).to.be.true;
expect(await collection.isTokenExists(token.tokenId)).to.be.false;
});
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, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair) {24 return new CrossAccountId({Substrate: account.address});25 }2627 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29 }3031 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32 return encodeAddress(decodeAddress(address), ss58Format);33 }3435 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37 }38 39 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41 return this;42 }43 44 toLowerCase(): CrossAccountId {45 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47 return this;48 }49}5051const nesting = {52 toChecksumAddress(address: string): string {53 if (typeof address === 'undefined') return '';5455 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);5657 address = address.toLowerCase().replace(/^0x/i,'');58 const addressHash = keccakAsHex(address).replace(/^0x/i,'');59 const checksumAddress = ['0x'];6061 for (let i = 0; i < address.length; i++) {62 // If ith character is 8 to f then make it uppercase63 if (parseInt(addressHash[i], 16) > 7) {64 checksumAddress.push(address[i].toUpperCase());65 } else {66 checksumAddress.push(address[i]);67 }68 }69 return checksumAddress.join('');70 },71 tokenIdToAddress(collectionId: number, tokenId: number) {72 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);73 },74};7576class UniqueUtil {77 static transactionStatus = {78 NOT_READY: 'NotReady',79 FAIL: 'Fail',80 SUCCESS: 'Success',81 };8283 static chainLogType = {84 EXTRINSIC: 'extrinsic',85 RPC: 'rpc',86 };8788 static getTokenAccount(token: IToken): CrossAccountId {89 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});90 }9192 static getTokenAddress(token: IToken): string {93 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94 }9596 static getDefaultLogger(): ILogger {97 return {98 log(msg: any, level = 'INFO') {99 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));100 },101 level: {102 ERROR: 'ERROR',103 WARNING: 'WARNING',104 INFO: 'INFO',105 },106 };107 }108109 static vec2str(arr: string[] | number[]) {110 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');111 }112113 static str2vec(string: string) {114 if (typeof string !== 'string') return string;115 return Array.from(string).map(x => x.charCodeAt(0));116 }117118 static fromSeed(seed: string, ss58Format = 42) {119 const keyring = new Keyring({type: 'sr25519', ss58Format});120 return keyring.addFromUri(seed);121 }122123 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {124 if (creationResult.status !== this.transactionStatus.SUCCESS) {125 throw Error('Unable to create collection!');126 }127128 let collectionId = null;129 creationResult.result.events.forEach(({event: {data, method, section}}) => {130 if ((section === 'common') && (method === 'CollectionCreated')) {131 collectionId = parseInt(data[0].toString(), 10);132 }133 });134135 if (collectionId === null) {136 throw Error('No CollectionCreated event was found!');137 }138139 return collectionId;140 }141142 static extractTokensFromCreationResult(creationResult: ITransactionResult) {143 if (creationResult.status !== this.transactionStatus.SUCCESS) {144 throw Error('Unable to create tokens!');145 }146 let success = false;147 const tokens = [] as any;148 creationResult.result.events.forEach(({event: {data, method, section}}) => {149 if (method === 'ExtrinsicSuccess') {150 success = true;151 } else if ((section === 'common') && (method === 'ItemCreated')) {152 tokens.push({153 collectionId: parseInt(data[0].toString(), 10),154 tokenId: parseInt(data[1].toString(), 10),155 owner: data[2].toJSON(),156 });157 }158 });159 return {success, tokens};160 }161162 static extractTokensFromBurnResult(burnResult: ITransactionResult) {163 if (burnResult.status !== this.transactionStatus.SUCCESS) {164 throw Error('Unable to burn tokens!');165 }166 let success = false;167 const tokens = [] as any;168 burnResult.result.events.forEach(({event: {data, method, section}}) => {169 if (method === 'ExtrinsicSuccess') {170 success = true;171 } else if ((section === 'common') && (method === 'ItemDestroyed')) {172 tokens.push({173 collectionId: parseInt(data[0].toString(), 10),174 tokenId: parseInt(data[1].toString(), 10),175 owner: data[2].toJSON(),176 });177 }178 });179 return {success, tokens};180 }181182 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {183 let eventId = null;184 events.forEach(({event: {data, method, section}}) => {185 if ((section === expectedSection) && (method === expectedMethod)) {186 eventId = parseInt(data[0].toString(), 10);187 }188 });189190 if (eventId === null) {191 throw Error(`No ${expectedMethod} event was found!`);192 }193 return eventId === collectionId;194 }195196 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {197 const normalizeAddress = (address: string | ICrossAccountId) => {198 if(typeof address === 'string') return address;199 const obj = {} as any;200 Object.keys(address).forEach(k => {201 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];202 });203 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);204 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();205 return address;206 };207 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;208 events.forEach(({event: {data, method, section}}) => {209 if ((section === 'common') && (method === 'Transfer')) {210 const hData = (data as any).toJSON();211 transfer = {212 collectionId: hData[0],213 tokenId: hData[1],214 from: normalizeAddress(hData[2]),215 to: normalizeAddress(hData[3]),216 amount: BigInt(hData[4]),217 };218 }219 });220 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;221 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);222 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);223 isSuccess = isSuccess && amount === transfer.amount;224 return isSuccess;225 }226}227228class UniqueEventHelper {229 private static extractIndex(index: any): [number, number] | string {230 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];231 return index.toJSON();232 }233234 private static extractSub(data: any, subTypes: any): {[key: string]: any} {235 let obj: any = {};236 let index = 0;237238 if (data.entries) {239 for(const [key, value] of data.entries()) {240 obj[key] = this.extractData(value, subTypes[index]);241 index++;242 }243 } else obj = data.toJSON();244245 return obj;246 }247 248 private static extractData(data: any, type: any): any {249 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();250 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();251 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);252 return data.toHuman();253 }254255 public static extractEvents(records: ITransactionResult): IEvent[] {256 const parsedEvents: IEvent[] = [];257258 records.result.events.forEach((record) => {259 const {event, phase} = record;260 const types = (event as any).typeDef;261262 const eventData: IEvent = {263 section: event.section.toString(),264 method: event.method.toString(),265 index: this.extractIndex(event.index),266 data: [],267 phase: phase.toJSON(),268 };269270 event.data.forEach((val: any, index: number) => {271 eventData.data.push(this.extractData(val, types[index]));272 });273274 parsedEvents.push(eventData);275 });276277 return parsedEvents;278 }279}280281class ChainHelperBase {282 transactionStatus = UniqueUtil.transactionStatus;283 chainLogType = UniqueUtil.chainLogType;284 util: typeof UniqueUtil;285 eventHelper: typeof UniqueEventHelper;286 logger: ILogger;287 api: ApiPromise | null;288 forcedNetwork: TUniqueNetworks | null;289 network: TUniqueNetworks | null;290 chainLog: IUniqueHelperLog[];291292 constructor(logger?: ILogger) {293 this.util = UniqueUtil;294 this.eventHelper = UniqueEventHelper;295 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();296 this.logger = logger;297 this.api = null;298 this.forcedNetwork = null;299 this.network = null;300 this.chainLog = [];301 }302303 clearChainLog(): void {304 this.chainLog = [];305 }306307 forceNetwork(value: TUniqueNetworks): void {308 this.forcedNetwork = value;309 }310311 async connect(wsEndpoint: string, listeners?: IApiListeners) {312 if (this.api !== null) throw Error('Already connected');313 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);314 this.api = api;315 this.network = network;316 }317318 async disconnect() {319 if (this.api === null) return;320 await this.api.disconnect();321 this.api = null;322 this.network = null;323 }324325 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {326 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;327 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;328 return 'opal';329 }330331 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {332 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});333 await api.isReady;334335 const network = await this.detectNetwork(api);336337 await api.disconnect();338339 return network;340 }341342 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{343 api: ApiPromise;344 network: TUniqueNetworks;345 }> {346 if(typeof network === 'undefined' || network === null) network = 'opal';347 const supportedRPC = {348 opal: {349 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,350 },351 quartz: {352 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,353 },354 unique: {355 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,356 },357 };358 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);359 const rpc = supportedRPC[network];360361 // TODO: investigate how to replace rpc in runtime362 // api._rpcCore.addUserInterfaces(rpc);363364 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});365366 await api.isReadyOrError;367368 if (typeof listeners === 'undefined') listeners = {};369 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {370 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;371 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);372 }373374 return {api, network};375 }376377 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {378 const {events, status} = data;379 if (status.isReady) {380 return this.transactionStatus.NOT_READY;381 }382 if (status.isBroadcast) {383 return this.transactionStatus.NOT_READY;384 }385 if (status.isInBlock || status.isFinalized) {386 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');387 if (errors.length > 0) {388 return this.transactionStatus.FAIL;389 }390 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {391 return this.transactionStatus.SUCCESS;392 }393 }394395 return this.transactionStatus.FAIL;396 }397398 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {399 const sign = (callback: any) => {400 if(options !== null) return transaction.signAndSend(sender, options, callback);401 return transaction.signAndSend(sender, callback);402 };403 // eslint-disable-next-line no-async-promise-executor404 return new Promise(async (resolve, reject) => {405 try {406 const unsub = await sign((result: any) => {407 const status = this.getTransactionStatus(result);408409 if (status === this.transactionStatus.SUCCESS) {410 this.logger.log(`${label} successful`);411 unsub();412 resolve({result, status});413 } else if (status === this.transactionStatus.FAIL) {414 let moduleError = null;415416 if (result.hasOwnProperty('dispatchError')) {417 const dispatchError = result['dispatchError'];418419 if (dispatchError) {420 if (dispatchError.isModule) {421 const modErr = dispatchError.asModule;422 const errorMeta = dispatchError.registry.findMetaError(modErr);423424 moduleError = `${errorMeta.section}.${errorMeta.name}`;425 } else {426 moduleError = dispatchError.toHuman();427 }428 } else {429 this.logger.log(result, this.logger.level.ERROR);430 }431 }432433 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);434 unsub();435 reject({status, moduleError, result});436 }437 });438 } catch (e) {439 this.logger.log(e, this.logger.level.ERROR);440 reject(e);441 }442 });443 }444445 constructApiCall(apiCall: string, params: any[]) {446 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);447 let call = this.api as any;448 for(const part of apiCall.slice(4).split('.')) {449 call = call[part];450 }451 return call(...params);452 }453454 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {455 if(this.api === null) throw Error('API not initialized');456 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);457458 const startTime = (new Date()).getTime();459 let result: ITransactionResult;460 let events: IEvent[] = [];461 try {462 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;463 events = this.eventHelper.extractEvents(result);464 }465 catch(e) {466 if(!(e as object).hasOwnProperty('status')) throw e;467 result = e as ITransactionResult;468 }469470 const endTime = (new Date()).getTime();471472 const log = {473 executedAt: endTime,474 executionTime: endTime - startTime,475 type: this.chainLogType.EXTRINSIC,476 status: result.status,477 call: extrinsic,478 signer: this.getSignerAddress(sender),479 params,480 } as IUniqueHelperLog;481482 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;483 if(events.length > 0) log.events = events;484485 this.chainLog.push(log);486487 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);488 return result;489 }490491 async callRpc(rpc: string, params?: any[]) {492 if(typeof params === 'undefined') params = [];493 if(this.api === null) throw Error('API not initialized');494 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);495496 const startTime = (new Date()).getTime();497 let result;498 let error = null;499 const log = {500 type: this.chainLogType.RPC,501 call: rpc,502 params,503 } as IUniqueHelperLog;504505 try {506 result = await this.constructApiCall(rpc, params);507 }508 catch(e) {509 error = e;510 }511512 const endTime = (new Date()).getTime();513514 log.executedAt = endTime;515 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';516 log.executionTime = endTime - startTime;517518 this.chainLog.push(log);519520 if(error !== null) throw error;521522 return result;523 }524525 getSignerAddress(signer: IKeyringPair | string): string {526 if(typeof signer === 'string') return signer;527 return signer.address;528 }529530 fetchAllPalletNames(): string[] {531 if(this.api === null) throw Error('API not initialized');532 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());533 }534535 fetchMissingPalletNames(requiredPallets: string[]): string[] {536 const palletNames = this.fetchAllPalletNames();537 return requiredPallets.filter(p => !palletNames.includes(p));538 }539}540541542class HelperGroup {543 helper: UniqueHelper;544545 constructor(uniqueHelper: UniqueHelper) {546 this.helper = uniqueHelper;547 }548}549550551class CollectionGroup extends HelperGroup {552 /**553 * Get number of blocks when sponsored transaction is available.554 *555 * @param collectionId ID of collection556 * @param tokenId ID of token557 * @param addressObj address for which the sponsorship is checked558 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});559 * @returns number of blocks or null if sponsorship hasn't been set560 */561 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {562 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();563 }564565 /**566 * Get the number of created collections.567 *568 * @returns number of created collections569 */570 async getTotalCount(): Promise<number> {571 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();572 }573574 /**575 * Get information about the collection with additional data,576 * including the number of tokens it contains, its administrators,577 * the normalized address of the collection's owner, and decoded name and description.578 *579 * @param collectionId ID of collection580 * @example await getData(2)581 * @returns collection information object582 */583 async getData(collectionId: number): Promise<{584 id: number;585 name: string;586 description: string;587 tokensCount: number;588 admins: CrossAccountId[];589 normalizedOwner: TSubstrateAccount;590 raw: any591 } | null> {592 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);593 const humanCollection = collection.toHuman(), collectionData = {594 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],595 raw: humanCollection,596 } as any, jsonCollection = collection.toJSON();597 if (humanCollection === null) return null;598 collectionData.raw.limits = jsonCollection.limits;599 collectionData.raw.permissions = jsonCollection.permissions;600 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);601 for (const key of ['name', 'description']) {602 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);603 }604605 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))606 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)607 : 0;608 collectionData.admins = await this.getAdmins(collectionId);609610 return collectionData;611 }612613 /**614 * Get the addresses of the collection's administrators, optionally normalized.615 *616 * @param collectionId ID of collection617 * @param normalize whether to normalize the addresses to the default ss58 format618 * @example await getAdmins(1)619 * @returns array of administrators620 */621 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {622 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();623624 return normalize625 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())626 : admins;627 }628629 /**630 * Get the addresses added to the collection allow-list, optionally normalized.631 * @param collectionId ID of collection632 * @param normalize whether to normalize the addresses to the default ss58 format633 * @example await getAllowList(1)634 * @returns array of allow-listed addresses635 */636 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {637 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();638 return normalize639 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())640 : allowListed;641 }642643 /**644 * Get the effective limits of the collection instead of null for default values645 *646 * @param collectionId ID of collection647 * @example await getEffectiveLimits(2)648 * @returns object of collection limits649 */650 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {651 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();652 }653654 /**655 * Burns the collection if the signer has sufficient permissions and collection is empty.656 *657 * @param signer keyring of signer658 * @param collectionId ID of collection659 * @example await helper.collection.burn(aliceKeyring, 3);660 * @returns ```true``` if extrinsic success, otherwise ```false```661 */662 async burn(signer: TSigner, collectionId: number): Promise<boolean> {663 const result = await this.helper.executeExtrinsic(664 signer,665 'api.tx.unique.destroyCollection', [collectionId],666 true,667 );668669 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');670 }671672 /**673 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.674 *675 * @param signer keyring of signer676 * @param collectionId ID of collection677 * @param sponsorAddress Sponsor substrate address678 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")679 * @returns ```true``` if extrinsic success, otherwise ```false```680 */681 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {682 const result = await this.helper.executeExtrinsic(683 signer,684 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],685 true,686 );687688 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');689 }690691 /**692 * Confirms consent to sponsor the collection on behalf of the signer.693 *694 * @param signer keyring of signer695 * @param collectionId ID of collection696 * @example confirmSponsorship(aliceKeyring, 10)697 * @returns ```true``` if extrinsic success, otherwise ```false```698 */699 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {700 const result = await this.helper.executeExtrinsic(701 signer,702 'api.tx.unique.confirmSponsorship', [collectionId],703 true,704 );705706 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');707 }708709 /**710 * Removes the sponsor of a collection, regardless if it consented or not.711 *712 * @param signer keyring of signer713 * @param collectionId ID of collection714 * @example removeSponsor(aliceKeyring, 10)715 * @returns ```true``` if extrinsic success, otherwise ```false```716 */717 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {718 const result = await this.helper.executeExtrinsic(719 signer,720 'api.tx.unique.removeCollectionSponsor', [collectionId],721 true,722 );723724 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');725 }726727 /**728 * Sets the limits of the collection. At least one limit must be specified for a correct call.729 *730 * @param signer keyring of signer731 * @param collectionId ID of collection732 * @param limits collection limits object733 * @example734 * await setLimits(735 * aliceKeyring,736 * 10,737 * {738 * sponsorTransferTimeout: 0,739 * ownerCanDestroy: false740 * }741 * )742 * @returns ```true``` if extrinsic success, otherwise ```false```743 */744 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {745 const result = await this.helper.executeExtrinsic(746 signer,747 'api.tx.unique.setCollectionLimits', [collectionId, limits],748 true,749 );750751 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');752 }753754 /**755 * Changes the owner of the collection to the new Substrate address.756 *757 * @param signer keyring of signer758 * @param collectionId ID of collection759 * @param ownerAddress substrate address of new owner760 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")761 * @returns ```true``` if extrinsic success, otherwise ```false```762 */763 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {764 const result = await this.helper.executeExtrinsic(765 signer,766 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],767 true,768 );769770 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');771 }772773 /**774 * Adds a collection administrator.775 *776 * @param signer keyring of signer777 * @param collectionId ID of collection778 * @param adminAddressObj Administrator address (substrate or ethereum)779 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})780 * @returns ```true``` if extrinsic success, otherwise ```false```781 */782 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {783 const result = await this.helper.executeExtrinsic(784 signer,785 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],786 true,787 );788789 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');790 }791792 /**793 * Removes a collection administrator.794 *795 * @param signer keyring of signer796 * @param collectionId ID of collection797 * @param adminAddressObj Administrator address (substrate or ethereum)798 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})799 * @returns ```true``` if extrinsic success, otherwise ```false```800 */801 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {802 const result = await this.helper.executeExtrinsic(803 signer,804 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],805 true,806 );807808 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');809 }810811 /**812 * Check if user is in allow list.813 * 814 * @param collectionId ID of collection815 * @param user Account to check816 * @example await getAdmins(1)817 * @returns is user in allow list818 */819 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {820 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();821 }822823 /**824 * Adds an address to allow list825 * @param signer keyring of signer826 * @param collectionId ID of collection827 * @param addressObj address to add to the allow list828 * @returns ```true``` if extrinsic success, otherwise ```false```829 */830 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.addToAllowList', [collectionId, addressObj],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');838 }839840 /**841 * Removes an address from allow list842 *843 * @param signer keyring of signer844 * @param collectionId ID of collection845 * @param addressObj address to remove from the allow list846 * @returns ```true``` if extrinsic success, otherwise ```false```847 */848 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');856 }857858 /**859 * Sets onchain permissions for selected collection.860 *861 * @param signer keyring of signer862 * @param collectionId ID of collection863 * @param permissions collection permissions object864 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});865 * @returns ```true``` if extrinsic success, otherwise ```false```866 */867 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {868 const result = await this.helper.executeExtrinsic(869 signer,870 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],871 true,872 );873874 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');875 }876877 /**878 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.879 *880 * @param signer keyring of signer881 * @param collectionId ID of collection882 * @param permissions nesting permissions object883 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});884 * @returns ```true``` if extrinsic success, otherwise ```false```885 */886 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {887 return await this.setPermissions(signer, collectionId, {nesting: permissions});888 }889890 /**891 * Disables nesting for selected collection.892 *893 * @param signer keyring of signer894 * @param collectionId ID of collection895 * @example disableNesting(aliceKeyring, 10);896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {899 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});900 }901902 /**903 * Sets onchain properties to the collection.904 *905 * @param signer keyring of signer906 * @param collectionId ID of collection907 * @param properties array of property objects908 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);909 * @returns ```true``` if extrinsic success, otherwise ```false```910 */911 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {912 const result = await this.helper.executeExtrinsic(913 signer,914 'api.tx.unique.setCollectionProperties', [collectionId, properties],915 true,916 );917918 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');919 }920921 /**922 * Get collection properties.923 * 924 * @param collectionId ID of collection925 * @param propertyKeys optionally filter the returned properties to only these keys926 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);927 * @returns array of key-value pairs928 */929 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {930 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();931 }932933 /**934 * Deletes onchain properties from the collection.935 *936 * @param signer keyring of signer937 * @param collectionId ID of collection938 * @param propertyKeys array of property keys to delete939 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);940 * @returns ```true``` if extrinsic success, otherwise ```false```941 */942 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {943 const result = await this.helper.executeExtrinsic(944 signer,945 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],946 true,947 );948949 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');950 }951952 /**953 * Changes the owner of the token.954 *955 * @param signer keyring of signer956 * @param collectionId ID of collection957 * @param tokenId ID of token958 * @param addressObj address of a new owner959 * @param amount amount of tokens to be transfered. For NFT must be set to 1n960 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})961 * @returns true if the token success, otherwise false962 */963 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],967 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,968 );969970 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);971 }972973 /**974 *975 * Change ownership of a token(s) on behalf of the owner.976 *977 * @param signer keyring of signer978 * @param collectionId ID of collection979 * @param tokenId ID of token980 * @param fromAddressObj address on behalf of which the token will be sent981 * @param toAddressObj new token owner982 * @param amount amount of tokens to be transfered. For NFT must be set to 1n983 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})984 * @returns true if the token success, otherwise false985 */986 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {987 const result = await this.helper.executeExtrinsic(988 signer,989 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],990 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,991 );992 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);993 }994995 /**996 *997 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.998 *999 * @param signer keyring of signer1000 * @param collectionId ID of collection1001 * @param tokenId ID of token1002 * @param amount amount of tokens to be burned. For NFT must be set to 1n1003 * @example burnToken(aliceKeyring, 10, 5);1004 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1005 */1006 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{1007 success: boolean,1008 token: number | null1009 }> {1010 const burnResult = await this.helper.executeExtrinsic(1011 signer,1012 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1013 true, // `Unable to burn token for ${label}`,1014 );1015 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1016 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1017 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};1018 }10191020 /**1021 * Destroys a concrete instance of NFT on behalf of the owner1022 *1023 * @param signer keyring of signer1024 * @param collectionId ID of collection1025 * @param tokenId ID of token1026 * @param fromAddressObj address on behalf of which the token will be burnt1027 * @param amount amount of tokens to be burned. For NFT must be set to 1n1028 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1029 * @returns ```true``` if extrinsic success, otherwise ```false```1030 */1031 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1032 const burnResult = await this.helper.executeExtrinsic(1033 signer,1034 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1035 true, // `Unable to burn token from for ${label}`,1036 );1037 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1038 return burnedTokens.success && burnedTokens.tokens.length > 0;1039 }10401041 /**1042 * Set, change, or remove approved address to transfer the ownership of the NFT.1043 *1044 * @param signer keyring of signer1045 * @param collectionId ID of collection1046 * @param tokenId ID of token1047 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1048 * @param amount amount of token to be approved. For NFT must be set to 1n1049 * @returns ```true``` if extrinsic success, otherwise ```false```1050 */1051 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1052 const approveResult = await this.helper.executeExtrinsic(1053 signer,1054 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1055 true, // `Unable to approve token for ${label}`,1056 );10571058 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1059 }10601061 /**1062 * Get the amount of token pieces approved to transfer or burn. Normally 0.1063 *1064 * @param collectionId ID of collection1065 * @param tokenId ID of token1066 * @param toAccountObj address which is approved to use token pieces1067 * @param fromAccountObj address which may have allowed the use of its owned tokens1068 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1069 * @returns number of approved to transfer pieces1070 */1071 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1072 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1073 }10741075 /**1076 * Get the last created token ID in a collection1077 *1078 * @param collectionId ID of collection1079 * @example getLastTokenId(10);1080 * @returns id of the last created token1081 */1082 async getLastTokenId(collectionId: number): Promise<number> {1083 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1084 }10851086 /**1087 * Check if token exists1088 *1089 * @param collectionId ID of collection1090 * @param tokenId ID of token1091 * @example isTokenExists(10, 20);1092 * @returns true if the token exists, otherwise false1093 */1094 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1095 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1096 }1097}10981099class NFTnRFT extends CollectionGroup {1100 /**1101 * Get tokens owned by account1102 *1103 * @param collectionId ID of collection1104 * @param addressObj tokens owner1105 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1106 * @returns array of token ids owned by account1107 */1108 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1109 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1110 }11111112 /**1113 * Get token data1114 *1115 * @param collectionId ID of collection1116 * @param tokenId ID of token1117 * @param propertyKeys optionally filter the token properties to only these keys1118 * @param blockHashAt optionally query the data at some block with this hash1119 * @example getToken(10, 5);1120 * @returns human readable token data1121 */1122 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1123 properties: IProperty[];1124 owner: CrossAccountId;1125 normalizedOwner: CrossAccountId;1126 }| null> {1127 let tokenData;1128 if(typeof blockHashAt === 'undefined') {1129 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1130 }1131 else {1132 if(propertyKeys.length == 0) {1133 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1134 if(!collection) return null;1135 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1136 }1137 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1138 }1139 tokenData = tokenData.toHuman();1140 if (tokenData === null || tokenData.owner === null) return null;1141 const owner = {} as any;1142 for (const key of Object.keys(tokenData.owner)) {1143 owner[key.toLocaleLowerCase()] = new CrossAccountId(tokenData.owner[key]).withNormalizedSubstrate();1144 }1145 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1146 return tokenData;1147 }11481149 /**1150 * Set permissions to change token properties1151 *1152 * @param signer keyring of signer1153 * @param collectionId ID of collection1154 * @param permissions permissions to change a property by the collection admin or token owner1155 * @example setTokenPropertyPermissions(1156 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1157 * )1158 * @returns true if extrinsic success otherwise false1159 */1160 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1161 const result = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1164 true,1165 );11661167 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1168 }11691170 /**1171 * Get token property permissions.1172 * 1173 * @param collectionId ID of collection1174 * @param propertyKeys optionally filter the returned property permissions to only these keys1175 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1176 * @returns array of key-permission pairs1177 */1178 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1179 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1180 }11811182 /**1183 * Set token properties1184 *1185 * @param signer keyring of signer1186 * @param collectionId ID of collection1187 * @param tokenId ID of token1188 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1189 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1190 * @returns ```true``` if extrinsic success, otherwise ```false```1191 */1192 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1193 const result = await this.helper.executeExtrinsic(1194 signer,1195 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1196 true,1197 );11981199 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1200 }12011202 /**1203 * Get properties, metadata assigned to a token.1204 * 1205 * @param collectionId ID of collection1206 * @param tokenId ID of token1207 * @param propertyKeys optionally filter the returned properties to only these keys1208 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1209 * @returns array of key-value pairs1210 */1211 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1212 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1213 }12141215 /**1216 * Delete the provided properties of a token1217 * @param signer keyring of signer1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param propertyKeys property keys to be deleted1221 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1222 * @returns ```true``` if extrinsic success, otherwise ```false```1223 */1224 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1225 const result = await this.helper.executeExtrinsic(1226 signer,1227 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1228 true,1229 );12301231 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1232 }12331234 /**1235 * Mint new collection1236 *1237 * @param signer keyring of signer1238 * @param collectionOptions basic collection options and properties1239 * @param mode NFT or RFT type of a collection1240 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1241 * @returns object of the created collection1242 */1243 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1244 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1245 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1246 for (const key of ['name', 'description', 'tokenPrefix']) {1247 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);1248 }1249 const creationResult = await this.helper.executeExtrinsic(1250 signer,1251 'api.tx.unique.createCollectionEx', [collectionOptions],1252 true, // errorLabel,1253 );1254 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1255 }12561257 getCollectionObject(_collectionId: number): any {1258 return null;1259 }12601261 getTokenObject(_collectionId: number, _tokenId: number): any {1262 return null;1263 }1264}126512661267class NFTGroup extends NFTnRFT {1268 /**1269 * Get collection object1270 * @param collectionId ID of collection1271 * @example getCollectionObject(2);1272 * @returns instance of UniqueNFTCollection1273 */1274 getCollectionObject(collectionId: number): UniqueNFTCollection {1275 return new UniqueNFTCollection(collectionId, this.helper);1276 }12771278 /**1279 * Get token object1280 * @param collectionId ID of collection1281 * @param tokenId ID of token1282 * @example getTokenObject(10, 5);1283 * @returns instance of UniqueNFTToken1284 */1285 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1286 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1287 }12881289 /**1290 * Get token's owner1291 * @param collectionId ID of collection1292 * @param tokenId ID of token1293 * @param blockHashAt optionally query the data at the block with this hash1294 * @example getTokenOwner(10, 5);1295 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1296 */1297 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1298 let owner;1299 if (typeof blockHashAt === 'undefined') {1300 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1301 } else {1302 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1303 }1304 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1305 }13061307 /**1308 * Is token approved to transfer1309 * @param collectionId ID of collection1310 * @param tokenId ID of token1311 * @param toAccountObj address to be approved1312 * @returns ```true``` if extrinsic success, otherwise ```false```1313 */1314 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1315 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1316 }13171318 /**1319 * Changes the owner of the token.1320 *1321 * @param signer keyring of signer1322 * @param collectionId ID of collection1323 * @param tokenId ID of token1324 * @param addressObj address of a new owner1325 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1326 * @returns ```true``` if extrinsic success, otherwise ```false```1327 */1328 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1329 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1330 }13311332 /**1333 *1334 * Change ownership of a NFT on behalf of the owner.1335 *1336 * @param signer keyring of signer1337 * @param collectionId ID of collection1338 * @param tokenId ID of token1339 * @param fromAddressObj address on behalf of which the token will be sent1340 * @param toAddressObj new token owner1341 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1345 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1346 }13471348 /**1349 * Recursively find the address that owns the token1350 * @param collectionId ID of collection1351 * @param tokenId ID of token1352 * @param blockHashAt1353 * @example getTokenTopmostOwner(10, 5);1354 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1355 */1356 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1357 let owner;1358 if (typeof blockHashAt === 'undefined') {1359 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1360 } else {1361 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1362 }13631364 if (owner === null) return null;13651366 return owner.toHuman();1367 }13681369 /**1370 * Get tokens nested in the provided token1371 * @param collectionId ID of collection1372 * @param tokenId ID of token1373 * @param blockHashAt optionally query the data at the block with this hash1374 * @example getTokenChildren(10, 5);1375 * @returns tokens whose depth of nesting is <= 51376 */1377 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1378 let children;1379 if(typeof blockHashAt === 'undefined') {1380 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1381 } else {1382 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1383 }13841385 return children.toJSON().map((x: any) => {1386 return {collectionId: x.collection, tokenId: x.token};1387 });1388 }13891390 /**1391 * Nest one token into another1392 * @param signer keyring of signer1393 * @param tokenObj token to be nested1394 * @param rootTokenObj token to be parent1395 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1396 * @returns ```true``` if extrinsic success, otherwise ```false```1397 */1398 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1399 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1400 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1401 if(!result) {1402 throw Error('Unable to nest token!');1403 }1404 return result;1405 }14061407 /**1408 * Remove token from nested state1409 * @param signer keyring of signer1410 * @param tokenObj token to unnest1411 * @param rootTokenObj parent of a token1412 * @param toAddressObj address of a new token owner1413 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1414 * @returns ```true``` if extrinsic success, otherwise ```false```1415 */1416 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1417 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1418 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1419 if(!result) {1420 throw Error('Unable to unnest token!');1421 }1422 return result;1423 }14241425 /**1426 * Mint new collection1427 * @param signer keyring of signer1428 * @param collectionOptions Collection options1429 * @example1430 * mintCollection(aliceKeyring, {1431 * name: 'New',1432 * description: 'New collection',1433 * tokenPrefix: 'NEW',1434 * })1435 * @returns object of the created collection1436 */1437 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1438 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1439 }14401441 /**1442 * Mint new token1443 * @param signer keyring of signer1444 * @param data token data1445 * @returns created token object1446 */1447 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1448 const creationResult = await this.helper.executeExtrinsic(1449 signer,1450 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1451 nft: {1452 properties: data.properties,1453 },1454 }],1455 true,1456 );1457 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1458 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1459 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1460 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1461 }14621463 /**1464 * Mint multiple NFT tokens1465 * @param signer keyring of signer1466 * @param collectionId ID of collection1467 * @param tokens array of tokens with owner and properties1468 * @example1469 * mintMultipleTokens(aliceKeyring, 10, [{1470 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1471 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1472 * },{1473 * owner: {Ethereum: "0x9F0583DbB855d..."},1474 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1475 * }]);1476 * @returns ```true``` if extrinsic success, otherwise ```false```1477 */1478 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1479 const creationResult = await this.helper.executeExtrinsic(1480 signer,1481 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1482 true,1483 );1484 const collection = this.getCollectionObject(collectionId);1485 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1486 }14871488 /**1489 * Mint multiple NFT tokens with one owner1490 * @param signer keyring of signer1491 * @param collectionId ID of collection1492 * @param owner tokens owner1493 * @param tokens array of tokens with owner and properties1494 * @example1495 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1496 * properties: [{1497 * key: "gender",1498 * value: "female",1499 * },{1500 * key: "age",1501 * value: "33",1502 * }],1503 * }]);1504 * @returns array of newly created tokens1505 */1506 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1507 const rawTokens = [];1508 for (const token of tokens) {1509 const raw = {NFT: {properties: token.properties}};1510 rawTokens.push(raw);1511 }1512 const creationResult = await this.helper.executeExtrinsic(1513 signer,1514 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1515 true,1516 );1517 const collection = this.getCollectionObject(collectionId);1518 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1519 }15201521 /**1522 * Set, change, or remove approved address to transfer the ownership of the NFT.1523 *1524 * @param signer keyring of signer1525 * @param collectionId ID of collection1526 * @param tokenId ID of token1527 * @param toAddressObj address to approve1528 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1529 * @returns ```true``` if extrinsic success, otherwise ```false```1530 */1531 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1532 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1533 }1534}153515361537class RFTGroup extends NFTnRFT {1538 /**1539 * Get collection object1540 * @param collectionId ID of collection1541 * @example getCollectionObject(2);1542 * @returns instance of UniqueRFTCollection1543 */1544 getCollectionObject(collectionId: number): UniqueRFTCollection {1545 return new UniqueRFTCollection(collectionId, this.helper);1546 }15471548 /**1549 * Get token object1550 * @param collectionId ID of collection1551 * @param tokenId ID of token1552 * @example getTokenObject(10, 5);1553 * @returns instance of UniqueNFTToken1554 */1555 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1556 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1557 }15581559 /**1560 * Get top 10 token owners with the largest number of pieces1561 * @param collectionId ID of collection1562 * @param tokenId ID of token1563 * @example getTokenTop10Owners(10, 5);1564 * @returns array of top 10 owners1565 */1566 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1567 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1568 }15691570 /**1571 * Get number of pieces owned by address1572 * @param collectionId ID of collection1573 * @param tokenId ID of token1574 * @param addressObj address token owner1575 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1576 * @returns number of pieces ownerd by address1577 */1578 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1579 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1580 }15811582 /**1583 * Transfer pieces of token to another address1584 * @param signer keyring of signer1585 * @param collectionId ID of collection1586 * @param tokenId ID of token1587 * @param addressObj address of a new owner1588 * @param amount number of pieces to be transfered1589 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1590 * @returns ```true``` if extrinsic success, otherwise ```false```1591 */1592 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1593 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1594 }15951596 /**1597 * Change ownership of some pieces of RFT on behalf of the owner.1598 * @param signer keyring of signer1599 * @param collectionId ID of collection1600 * @param tokenId ID of token1601 * @param fromAddressObj address on behalf of which the token will be sent1602 * @param toAddressObj new token owner1603 * @param amount number of pieces to be transfered1604 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1605 * @returns ```true``` if extrinsic success, otherwise ```false```1606 */1607 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1608 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1609 }16101611 /**1612 * Mint new collection1613 * @param signer keyring of signer1614 * @param collectionOptions Collection options1615 * @example1616 * mintCollection(aliceKeyring, {1617 * name: 'New',1618 * description: 'New collection',1619 * tokenPrefix: 'NEW',1620 * })1621 * @returns object of the created collection1622 */1623 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1624 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1625 }16261627 /**1628 * Mint new token1629 * @param signer keyring of signer1630 * @param data token data1631 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1632 * @returns created token object1633 */1634 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1635 const creationResult = await this.helper.executeExtrinsic(1636 signer,1637 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1638 refungible: {1639 pieces: data.pieces,1640 properties: data.properties,1641 },1642 }],1643 true,1644 );1645 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1646 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1647 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1648 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1649 }16501651 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1652 throw Error('Not implemented');1653 const creationResult = await this.helper.executeExtrinsic(1654 signer,1655 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1656 true, // `Unable to mint RFT tokens for ${label}`,1657 );1658 const collection = this.getCollectionObject(collectionId);1659 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1660 }16611662 /**1663 * Mint multiple RFT tokens with one owner1664 * @param signer keyring of signer1665 * @param collectionId ID of collection1666 * @param owner tokens owner1667 * @param tokens array of tokens with properties and pieces1668 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1669 * @returns array of newly created RFT tokens1670 */1671 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1672 const rawTokens = [];1673 for (const token of tokens) {1674 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1675 rawTokens.push(raw);1676 }1677 const creationResult = await this.helper.executeExtrinsic(1678 signer,1679 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1680 true,1681 );1682 const collection = this.getCollectionObject(collectionId);1683 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1684 }16851686 /**1687 * Destroys a concrete instance of RFT.1688 * @param signer keyring of signer1689 * @param collectionId ID of collection1690 * @param tokenId ID of token1691 * @param amount number of pieces to be burnt1692 * @example burnToken(aliceKeyring, 10, 5);1693 * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1694 */1695 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1696 return await super.burnToken(signer, collectionId, tokenId, amount);1697 }16981699 /**1700 * Destroys a concrete instance of RFT on behalf of the owner.1701 * @param signer keyring of signer1702 * @param collectionId ID of collection1703 * @param tokenId ID of token1704 * @param fromAddressObj address on behalf of which the token will be burnt1705 * @param amount number of pieces to be burnt1706 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1707 * @returns ```true``` if extrinsic success, otherwise ```false```1708 */1709 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1710 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1711 }17121713 /**1714 * Set, change, or remove approved address to transfer the ownership of the RFT.1715 *1716 * @param signer keyring of signer1717 * @param collectionId ID of collection1718 * @param tokenId ID of token1719 * @param toAddressObj address to approve1720 * @param amount number of pieces to be approved1721 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1722 * @returns true if the token success, otherwise false1723 */1724 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1725 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1726 }17271728 /**1729 * Get total number of pieces1730 * @param collectionId ID of collection1731 * @param tokenId ID of token1732 * @example getTokenTotalPieces(10, 5);1733 * @returns number of pieces1734 */1735 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1736 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1737 }17381739 /**1740 * Change number of token pieces. Signer must be the owner of all token pieces.1741 * @param signer keyring of signer1742 * @param collectionId ID of collection1743 * @param tokenId ID of token1744 * @param amount new number of pieces1745 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1746 * @returns true if the repartion was success, otherwise false1747 */1748 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1749 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1750 const repartitionResult = await this.helper.executeExtrinsic(1751 signer,1752 'api.tx.unique.repartition', [collectionId, tokenId, amount],1753 true,1754 );1755 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1756 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1757 }1758}175917601761class FTGroup extends CollectionGroup {1762 /**1763 * Get collection object1764 * @param collectionId ID of collection1765 * @example getCollectionObject(2);1766 * @returns instance of UniqueFTCollection1767 */1768 getCollectionObject(collectionId: number): UniqueFTCollection {1769 return new UniqueFTCollection(collectionId, this.helper);1770 }17711772 /**1773 * Mint new fungible collection1774 * @param signer keyring of signer1775 * @param collectionOptions Collection options1776 * @param decimalPoints number of token decimals1777 * @example1778 * mintCollection(aliceKeyring, {1779 * name: 'New',1780 * description: 'New collection',1781 * tokenPrefix: 'NEW',1782 * }, 18)1783 * @returns newly created fungible collection1784 */1785 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1786 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1787 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1788 collectionOptions.mode = {fungible: decimalPoints};1789 for (const key of ['name', 'description', 'tokenPrefix']) {1790 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);1791 }1792 const creationResult = await this.helper.executeExtrinsic(1793 signer,1794 'api.tx.unique.createCollectionEx', [collectionOptions],1795 true,1796 );1797 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1798 }17991800 /**1801 * Mint tokens1802 * @param signer keyring of signer1803 * @param collectionId ID of collection1804 * @param owner address owner of new tokens1805 * @param amount amount of tokens to be meanted1806 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1807 * @returns ```true``` if extrinsic success, otherwise ```false```1808 */1809 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1810 const creationResult = await this.helper.executeExtrinsic(1811 signer,1812 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1813 fungible: {1814 value: amount,1815 },1816 }],1817 true, // `Unable to mint fungible tokens for ${label}`,1818 );1819 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1820 }18211822 /**1823 * Mint multiple Fungible tokens with one owner1824 * @param signer keyring of signer1825 * @param collectionId ID of collection1826 * @param owner tokens owner1827 * @param tokens array of tokens with properties and pieces1828 * @returns ```true``` if extrinsic success, otherwise ```false```1829 */1830 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1831 const rawTokens = [];1832 for (const token of tokens) {1833 const raw = {Fungible: {Value: token.value}};1834 rawTokens.push(raw);1835 }1836 const creationResult = await this.helper.executeExtrinsic(1837 signer,1838 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1839 true,1840 );1841 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1842 }18431844 /**1845 * Get the top 10 owners with the largest balance for the Fungible collection1846 * @param collectionId ID of collection1847 * @example getTop10Owners(10);1848 * @returns array of ```ICrossAccountId```1849 */1850 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1851 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1852 }18531854 /**1855 * Get account balance1856 * @param collectionId ID of collection1857 * @param addressObj address of owner1858 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1859 * @returns amount of fungible tokens owned by address1860 */1861 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1862 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1863 }18641865 /**1866 * Transfer tokens to address1867 * @param signer keyring of signer1868 * @param collectionId ID of collection1869 * @param toAddressObj address recipient1870 * @param amount amount of tokens to be sent1871 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1872 * @returns ```true``` if extrinsic success, otherwise ```false```1873 */1874 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1875 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1876 }18771878 /**1879 * Transfer some tokens on behalf of the owner.1880 * @param signer keyring of signer1881 * @param collectionId ID of collection1882 * @param fromAddressObj address on behalf of which tokens will be sent1883 * @param toAddressObj address where token to be sent1884 * @param amount number of tokens to be sent1885 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1886 * @returns ```true``` if extrinsic success, otherwise ```false```1887 */1888 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1889 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1890 }18911892 /**1893 * Destroy some amount of tokens1894 * @param signer keyring of signer1895 * @param collectionId ID of collection1896 * @param amount amount of tokens to be destroyed1897 * @example burnTokens(aliceKeyring, 10, 1000n);1898 * @returns ```true``` if extrinsic success, otherwise ```false```1899 */1900 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1901 return (await super.burnToken(signer, collectionId, 0, amount)).success;1902 }19031904 /**1905 * Burn some tokens on behalf of the owner.1906 * @param signer keyring of signer1907 * @param collectionId ID of collection1908 * @param fromAddressObj address on behalf of which tokens will be burnt1909 * @param amount amount of tokens to be burnt1910 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1911 * @returns ```true``` if extrinsic success, otherwise ```false```1912 */1913 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1914 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1915 }19161917 /**1918 * Get total collection supply1919 * @param collectionId1920 * @returns1921 */1922 async getTotalPieces(collectionId: number): Promise<bigint> {1923 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1924 }19251926 /**1927 * Set, change, or remove approved address to transfer tokens.1928 *1929 * @param signer keyring of signer1930 * @param collectionId ID of collection1931 * @param toAddressObj address to be approved1932 * @param amount amount of tokens to be approved1933 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1934 * @returns ```true``` if extrinsic success, otherwise ```false```1935 */1936 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1937 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1938 }19391940 /**1941 * Get amount of fungible tokens approved to transfer1942 * @param collectionId ID of collection1943 * @param fromAddressObj owner of tokens1944 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1945 * @returns number of tokens approved for the transfer1946 */1947 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1948 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1949 }1950}195119521953class ChainGroup extends HelperGroup {1954 /**1955 * Get system properties of a chain1956 * @example getChainProperties();1957 * @returns ss58Format, token decimals, and token symbol1958 */1959 getChainProperties(): IChainProperties {1960 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1961 return {1962 ss58Format: properties.ss58Format.toJSON(),1963 tokenDecimals: properties.tokenDecimals.toJSON(),1964 tokenSymbol: properties.tokenSymbol.toJSON(),1965 };1966 }19671968 /**1969 * Get chain header1970 * @example getLatestBlockNumber();1971 * @returns the number of the last block1972 */1973 async getLatestBlockNumber(): Promise<number> {1974 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1975 }19761977 /**1978 * Get block hash by block number1979 * @param blockNumber number of block1980 * @example getBlockHashByNumber(12345);1981 * @returns hash of a block1982 */1983 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1984 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1985 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1986 return blockHash;1987 }19881989 // TODO add docs1990 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1991 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1992 if (!blockHash) return null;1993 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1994 }19951996 /**1997 * Get account nonce1998 * @param address substrate address1999 * @example getNonce("5GrwvaEF5zXb26Fz...");2000 * @returns number, account's nonce2001 */2002 async getNonce(address: TSubstrateAccount): Promise<number> {2003 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2004 }2005}200620072008class BalanceGroup extends HelperGroup {2009 /**2010 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2011 * @example getOneTokenNominal()2012 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2013 */2014 getOneTokenNominal(): bigint {2015 const chainProperties = this.helper.chain.getChainProperties();2016 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2017 }20182019 /**2020 * Get substrate address balance2021 * @param address substrate address2022 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2023 * @returns amount of tokens on address2024 */2025 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2026 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2027 }20282029 /**2030 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2031 * @param address substrate address2032 * @returns2033 */2034 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2035 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2036 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2037 }20382039 /**2040 * Get ethereum address balance2041 * @param address ethereum address2042 * @example getEthereum("0x9F0583DbB855d...")2043 * @returns amount of tokens on address2044 */2045 async getEthereum(address: TEthereumAccount): Promise<bigint> {2046 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2047 }20482049 /**2050 * Transfer tokens to substrate address2051 * @param signer keyring of signer2052 * @param address substrate address of a recipient2053 * @param amount amount of tokens to be transfered2054 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2055 * @returns ```true``` if extrinsic success, otherwise ```false```2056 */2057 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2058 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}`*/);20592060 let transfer = {from: null, to: null, amount: 0n} as any;2061 result.result.events.forEach(({event: {data, method, section}}) => {2062 if ((section === 'balances') && (method === 'Transfer')) {2063 transfer = {2064 from: this.helper.address.normalizeSubstrate(data[0]),2065 to: this.helper.address.normalizeSubstrate(data[1]),2066 amount: BigInt(data[2]),2067 };2068 }2069 });2070 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2071 && this.helper.address.normalizeSubstrate(address) === transfer.to 2072 && BigInt(amount) === transfer.amount;2073 return isSuccess;2074 }2075}207620772078class AddressGroup extends HelperGroup {2079 /**2080 * Normalizes the address to the specified ss58 format, by default ```42```.2081 * @param address substrate address2082 * @param ss58Format format for address conversion, by default ```42```2083 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2084 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2085 */2086 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2087 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2088 }20892090 /**2091 * Get address in the connected chain format2092 * @param address substrate address2093 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2094 * @returns address in chain format2095 */2096 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2097 const info = this.helper.chain.getChainProperties();2098 return encodeAddress(decodeAddress(address), info.ss58Format);2099 }21002101 /**2102 * Get substrate mirror of an ethereum address2103 * @param ethAddress ethereum address2104 * @param toChainFormat false for normalized account2105 * @example ethToSubstrate('0x9F0583DbB855d...')2106 * @returns substrate mirror of a provided ethereum address2107 */2108 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2109 if(!toChainFormat) return evmToAddress(ethAddress);2110 const info = this.helper.chain.getChainProperties();2111 return evmToAddress(ethAddress, info.ss58Format);2112 }21132114 /**2115 * Get ethereum mirror of a substrate address2116 * @param subAddress substrate account2117 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2118 * @returns ethereum mirror of a provided substrate address2119 */2120 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2121 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2122 }2123}21242125class StakingGroup extends HelperGroup {2126 /**2127 * Stake tokens for App Promotion2128 * @param signer keyring of signer2129 * @param amountToStake amount of tokens to stake2130 * @param label extra label for log2131 * @returns2132 */2133 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2134 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2135 const stakeResult = await this.helper.executeExtrinsic(2136 signer, 'api.tx.appPromotion.stake',2137 [amountToStake], true,2138 );2139 // TODO extract info from stakeResult2140 return true;2141 }21422143 /**2144 * Unstake tokens for App Promotion2145 * @param signer keyring of signer2146 * @param amountToUnstake amount of tokens to unstake2147 * @param label extra label for log2148 * @returns block number where balances will be unlocked2149 */2150 async unstake(signer: TSigner, label?: string): Promise<number> {2151 if(typeof label === 'undefined') label = `${signer.address}`;2152 const unstakeResult = await this.helper.executeExtrinsic(2153 signer, 'api.tx.appPromotion.unstake',2154 [], true,2155 );2156 // TODO extract block number fron events2157 return 1;2158 }21592160 /**2161 * Get total staked amount for address2162 * @param address substrate or ethereum address2163 * @returns total staked amount2164 */2165 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2166 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2167 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2168 }21692170 /**2171 * Get total staked per block2172 * @param address substrate or ethereum address2173 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2174 */2175 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2176 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2177 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2178 return { 2179 block: block.toBigInt(),2180 amount: amount.toBigInt(),2181 };2182 });2183 }21842185 /**2186 * Get total pending unstake amount for address2187 * @param address substrate or ethereum address2188 * @returns total pending unstake amount2189 */2190 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2191 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2192 }21932194 /**2195 * Get pending unstake amount per block for address2196 * @param address substrate or ethereum address2197 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2198 */2199 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2200 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2201 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2202 return {2203 block: block.toBigInt(),2204 amount: amount.toBigInt(),2205 };2206 });2207 return result;2208 }2209}22102211export class UniqueHelper extends ChainHelperBase {2212 chain: ChainGroup;2213 balance: BalanceGroup;2214 address: AddressGroup;2215 collection: CollectionGroup;2216 nft: NFTGroup;2217 rft: RFTGroup;2218 ft: FTGroup;2219 staking: StakingGroup;22202221 constructor(logger?: ILogger) {2222 super(logger);2223 this.chain = new ChainGroup(this);2224 this.balance = new BalanceGroup(this);2225 this.address = new AddressGroup(this);2226 this.collection = new CollectionGroup(this);2227 this.nft = new NFTGroup(this);2228 this.rft = new RFTGroup(this);2229 this.ft = new FTGroup(this);2230 this.staking = new StakingGroup(this);2231 }2232}223322342235export class UniqueBaseCollection {2236 helper: UniqueHelper;2237 collectionId: number;22382239 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2240 this.collectionId = collectionId;2241 this.helper = uniqueHelper;2242 }22432244 async getData() {2245 return await this.helper.collection.getData(this.collectionId);2246 }22472248 async getLastTokenId() {2249 return await this.helper.collection.getLastTokenId(this.collectionId);2250 }22512252 async isTokenExists(tokenId: number) {2253 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2254 }22552256 async getAdmins() {2257 return await this.helper.collection.getAdmins(this.collectionId);2258 }22592260 async getAllowList() {2261 return await this.helper.collection.getAllowList(this.collectionId);2262 }22632264 async getEffectiveLimits() {2265 return await this.helper.collection.getEffectiveLimits(this.collectionId);2266 }22672268 async getProperties(propertyKeys: string[] | null = null) {2269 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2270 }22712272 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2273 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2274 }22752276 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2277 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2278 }22792280 async confirmSponsorship(signer: TSigner) {2281 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2282 }22832284 async removeSponsor(signer: TSigner) {2285 return await this.helper.collection.removeSponsor(signer, this.collectionId);2286 }22872288 async setLimits(signer: TSigner, limits: ICollectionLimits) {2289 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2290 }22912292 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2293 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2294 }22952296 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2297 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2298 }22992300 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2301 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2302 }23032304 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2305 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2306 }23072308 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2309 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2310 }23112312 async setProperties(signer: TSigner, properties: IProperty[]) {2313 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2314 }23152316 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2317 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2318 }23192320 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2321 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2322 }23232324 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2325 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2326 }23272328 async disableNesting(signer: TSigner) {2329 return await this.helper.collection.disableNesting(signer, this.collectionId);2330 }23312332 async burn(signer: TSigner) {2333 return await this.helper.collection.burn(signer, this.collectionId);2334 }2335}233623372338export class UniqueNFTCollection extends UniqueBaseCollection {2339 getTokenObject(tokenId: number) {2340 return new UniqueNFToken(tokenId, this);2341 }23422343 async getTokensByAddress(addressObj: ICrossAccountId) {2344 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2345 }23462347 async getToken(tokenId: number, blockHashAt?: string) {2348 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2349 }23502351 async getTokenOwner(tokenId: number, blockHashAt?: string) {2352 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2353 }23542355 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2356 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2357 }23582359 async getTokenChildren(tokenId: number, blockHashAt?: string) {2360 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2361 }23622363 async getPropertyPermissions(propertyKeys: string[] | null = null) {2364 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2365 }23662367 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2368 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2369 }23702371 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2372 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2373 }23742375 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2376 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2377 }23782379 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2380 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2381 }23822383 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2384 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2385 }23862387 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2388 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2389 }23902391 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2392 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2393 }23942395 async burnToken(signer: TSigner, tokenId: number) {2396 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2397 }23982399 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2400 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2401 }24022403 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2404 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2405 }24062407 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2408 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2409 }24102411 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2412 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2413 }24142415 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2416 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2417 }24182419 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2420 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2421 }2422}242324242425export class UniqueRFTCollection extends UniqueBaseCollection {2426 getTokenObject(tokenId: number) {2427 return new UniqueRFToken(tokenId, this);2428 }24292430 async getToken(tokenId: number, blockHashAt?: string) {2431 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2432 }24332434 async getTokensByAddress(addressObj: ICrossAccountId) {2435 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2436 }24372438 async getTop10TokenOwners(tokenId: number) {2439 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2440 }24412442 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2443 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2444 }24452446 async getTokenTotalPieces(tokenId: number) {2447 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2448 }24492450 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2451 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2452 }24532454 async getPropertyPermissions(propertyKeys: string[] | null = null) {2455 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2456 }24572458 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2459 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2460 }24612462 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2463 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2464 }24652466 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2467 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2468 }24692470 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2471 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2472 }24732474 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2475 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2476 }24772478 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2479 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2480 }24812482 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2483 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2484 }24852486 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2487 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2488 }24892490 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2491 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2492 }24932494 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2495 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2496 }24972498 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2499 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2500 }25012502 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2503 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2504 }2505}250625072508export class UniqueFTCollection extends UniqueBaseCollection {2509 async getBalance(addressObj: ICrossAccountId) {2510 return await this.helper.ft.getBalance(this.collectionId, addressObj);2511 }25122513 async getTotalPieces() {2514 return await this.helper.ft.getTotalPieces(this.collectionId);2515 }25162517 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2518 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2519 }25202521 async getTop10Owners() {2522 return await this.helper.ft.getTop10Owners(this.collectionId);2523 }25242525 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2526 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2527 }25282529 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2530 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2531 }25322533 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2534 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2535 }25362537 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2538 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2539 }25402541 async burnTokens(signer: TSigner, amount=1n) {2542 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2543 }25442545 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2546 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2547 }25482549 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2550 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2551 }2552}255325542555export class UniqueBaseToken {2556 collection: UniqueNFTCollection | UniqueRFTCollection;2557 collectionId: number;2558 tokenId: number;25592560 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2561 this.collection = collection;2562 this.collectionId = collection.collectionId;2563 this.tokenId = tokenId;2564 }25652566 async getNextSponsored(addressObj: ICrossAccountId) {2567 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2568 }25692570 async getProperties(propertyKeys: string[] | null = null) {2571 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2572 }25732574 async setProperties(signer: TSigner, properties: IProperty[]) {2575 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2576 }25772578 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2579 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2580 }25812582 nestingAccount() {2583 return this.collection.helper.util.getTokenAccount(this);2584 }2585}258625872588export class UniqueNFToken extends UniqueBaseToken {2589 collection: UniqueNFTCollection;25902591 constructor(tokenId: number, collection: UniqueNFTCollection) {2592 super(tokenId, collection);2593 this.collection = collection;2594 }25952596 async getData(blockHashAt?: string) {2597 return await this.collection.getToken(this.tokenId, blockHashAt);2598 }25992600 async getOwner(blockHashAt?: string) {2601 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2602 }26032604 async getTopmostOwner(blockHashAt?: string) {2605 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2606 }26072608 async getChildren(blockHashAt?: string) {2609 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2610 }26112612 async nest(signer: TSigner, toTokenObj: IToken) {2613 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2614 }26152616 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2617 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2618 }26192620 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2621 return await this.collection.transferToken(signer, this.tokenId, addressObj);2622 }26232624 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2625 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2626 }26272628 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2629 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2630 }26312632 async isApproved(toAddressObj: ICrossAccountId) {2633 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2634 }26352636 async burn(signer: TSigner) {2637 return await this.collection.burnToken(signer, this.tokenId);2638 }26392640 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2641 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2642 }2643}26442645export class UniqueRFToken extends UniqueBaseToken {2646 collection: UniqueRFTCollection;26472648 constructor(tokenId: number, collection: UniqueRFTCollection) {2649 super(tokenId, collection);2650 this.collection = collection;2651 }26522653 async getData(blockHashAt?: string) {2654 return await this.collection.getToken(this.tokenId, blockHashAt);2655 }26562657 async getTop10Owners() {2658 return await this.collection.getTop10TokenOwners(this.tokenId);2659 }26602661 async getBalance(addressObj: ICrossAccountId) {2662 return await this.collection.getTokenBalance(this.tokenId, addressObj);2663 }26642665 async getTotalPieces() {2666 return await this.collection.getTokenTotalPieces(this.tokenId);2667 }26682669 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2670 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2671 }26722673 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2674 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2675 }26762677 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2678 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2679 }26802681 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2682 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2683 }26842685 async repartition(signer: TSigner, amount: bigint) {2686 return await this.collection.repartitionToken(signer, this.tokenId, amount);2687 }26882689 async burn(signer: TSigner, amount=1n) {2690 return await this.collection.burnToken(signer, this.tokenId, amount);2691 }26922693 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2694 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2695 }2696}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, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair) {24 return new CrossAccountId({Substrate: account.address});25 }2627 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29 }3031 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32 return encodeAddress(decodeAddress(address), ss58Format);33 }3435 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37 }38 39 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41 return this;42 }43 44 toLowerCase(): CrossAccountId {45 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47 return this;48 }49}5051const nesting = {52 toChecksumAddress(address: string): string {53 if (typeof address === 'undefined') return '';5455 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);5657 address = address.toLowerCase().replace(/^0x/i,'');58 const addressHash = keccakAsHex(address).replace(/^0x/i,'');59 const checksumAddress = ['0x'];6061 for (let i = 0; i < address.length; i++) {62 // If ith character is 8 to f then make it uppercase63 if (parseInt(addressHash[i], 16) > 7) {64 checksumAddress.push(address[i].toUpperCase());65 } else {66 checksumAddress.push(address[i]);67 }68 }69 return checksumAddress.join('');70 },71 tokenIdToAddress(collectionId: number, tokenId: number) {72 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);73 },74};7576class UniqueUtil {77 static transactionStatus = {78 NOT_READY: 'NotReady',79 FAIL: 'Fail',80 SUCCESS: 'Success',81 };8283 static chainLogType = {84 EXTRINSIC: 'extrinsic',85 RPC: 'rpc',86 };8788 static getTokenAccount(token: IToken): CrossAccountId {89 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});90 }9192 static getTokenAddress(token: IToken): string {93 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94 }9596 static getDefaultLogger(): ILogger {97 return {98 log(msg: any, level = 'INFO') {99 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));100 },101 level: {102 ERROR: 'ERROR',103 WARNING: 'WARNING',104 INFO: 'INFO',105 },106 };107 }108109 static vec2str(arr: string[] | number[]) {110 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');111 }112113 static str2vec(string: string) {114 if (typeof string !== 'string') return string;115 return Array.from(string).map(x => x.charCodeAt(0));116 }117118 static fromSeed(seed: string, ss58Format = 42) {119 const keyring = new Keyring({type: 'sr25519', ss58Format});120 return keyring.addFromUri(seed);121 }122123 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {124 if (creationResult.status !== this.transactionStatus.SUCCESS) {125 throw Error('Unable to create collection!');126 }127128 let collectionId = null;129 creationResult.result.events.forEach(({event: {data, method, section}}) => {130 if ((section === 'common') && (method === 'CollectionCreated')) {131 collectionId = parseInt(data[0].toString(), 10);132 }133 });134135 if (collectionId === null) {136 throw Error('No CollectionCreated event was found!');137 }138139 return collectionId;140 }141142 static extractTokensFromCreationResult(creationResult: ITransactionResult): {143 success: boolean, 144 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],145 } {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create tokens!');148 }149 let success = false;150 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if (method === 'ExtrinsicSuccess') {153 success = true;154 } else if ((section === 'common') && (method === 'ItemCreated')) {155 tokens.push({156 collectionId: parseInt(data[0].toString(), 10),157 tokenId: parseInt(data[1].toString(), 10),158 owner: data[2].toHuman(),159 amount: data[3].toBigInt(),160 });161 }162 });163 return {success, tokens};164 }165166 static extractTokensFromBurnResult(burnResult: ITransactionResult): {167 success: boolean, 168 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],169 } {170 if (burnResult.status !== this.transactionStatus.SUCCESS) {171 throw Error('Unable to burn tokens!');172 }173 let success = false;174 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];175 burnResult.result.events.forEach(({event: {data, method, section}}) => {176 if (method === 'ExtrinsicSuccess') {177 success = true;178 } else if ((section === 'common') && (method === 'ItemDestroyed')) {179 tokens.push({180 collectionId: parseInt(data[0].toString(), 10),181 tokenId: parseInt(data[1].toString(), 10),182 owner: data[2].toHuman(),183 amount: data[3].toBigInt(),184 });185 }186 });187 return {success, tokens};188 }189190 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {191 let eventId = null;192 events.forEach(({event: {data, method, section}}) => {193 if ((section === expectedSection) && (method === expectedMethod)) {194 eventId = parseInt(data[0].toString(), 10);195 }196 });197198 if (eventId === null) {199 throw Error(`No ${expectedMethod} event was found!`);200 }201 return eventId === collectionId;202 }203204 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {205 const normalizeAddress = (address: string | ICrossAccountId) => {206 if(typeof address === 'string') return address;207 const obj = {} as any;208 Object.keys(address).forEach(k => {209 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];210 });211 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);212 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();213 return address;214 };215 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;216 events.forEach(({event: {data, method, section}}) => {217 if ((section === 'common') && (method === 'Transfer')) {218 const hData = (data as any).toJSON();219 transfer = {220 collectionId: hData[0],221 tokenId: hData[1],222 from: normalizeAddress(hData[2]),223 to: normalizeAddress(hData[3]),224 amount: BigInt(hData[4]),225 };226 }227 });228 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;229 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);230 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);231 isSuccess = isSuccess && amount === transfer.amount;232 return isSuccess;233 }234}235236class UniqueEventHelper {237 private static extractIndex(index: any): [number, number] | string {238 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];239 return index.toJSON();240 }241242 private static extractSub(data: any, subTypes: any): {[key: string]: any} {243 let obj: any = {};244 let index = 0;245246 if (data.entries) {247 for(const [key, value] of data.entries()) {248 obj[key] = this.extractData(value, subTypes[index]);249 index++;250 }251 } else obj = data.toJSON();252253 return obj;254 }255 256 private static extractData(data: any, type: any): any {257 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();258 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();259 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);260 return data.toHuman();261 }262263 public static extractEvents(records: ITransactionResult): IEvent[] {264 const parsedEvents: IEvent[] = [];265266 records.result.events.forEach((record) => {267 const {event, phase} = record;268 const types = (event as any).typeDef;269270 const eventData: IEvent = {271 section: event.section.toString(),272 method: event.method.toString(),273 index: this.extractIndex(event.index),274 data: [],275 phase: phase.toJSON(),276 };277278 event.data.forEach((val: any, index: number) => {279 eventData.data.push(this.extractData(val, types[index]));280 });281282 parsedEvents.push(eventData);283 });284285 return parsedEvents;286 }287}288289class ChainHelperBase {290 transactionStatus = UniqueUtil.transactionStatus;291 chainLogType = UniqueUtil.chainLogType;292 util: typeof UniqueUtil;293 eventHelper: typeof UniqueEventHelper;294 logger: ILogger;295 api: ApiPromise | null;296 forcedNetwork: TUniqueNetworks | null;297 network: TUniqueNetworks | null;298 chainLog: IUniqueHelperLog[];299300 constructor(logger?: ILogger) {301 this.util = UniqueUtil;302 this.eventHelper = UniqueEventHelper;303 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();304 this.logger = logger;305 this.api = null;306 this.forcedNetwork = null;307 this.network = null;308 this.chainLog = [];309 }310311 clearChainLog(): void {312 this.chainLog = [];313 }314315 forceNetwork(value: TUniqueNetworks): void {316 this.forcedNetwork = value;317 }318319 async connect(wsEndpoint: string, listeners?: IApiListeners) {320 if (this.api !== null) throw Error('Already connected');321 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);322 this.api = api;323 this.network = network;324 }325326 async disconnect() {327 if (this.api === null) return;328 await this.api.disconnect();329 this.api = null;330 this.network = null;331 }332333 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {334 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;335 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;336 return 'opal';337 }338339 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {340 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});341 await api.isReady;342343 const network = await this.detectNetwork(api);344345 await api.disconnect();346347 return network;348 }349350 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{351 api: ApiPromise;352 network: TUniqueNetworks;353 }> {354 if(typeof network === 'undefined' || network === null) network = 'opal';355 const supportedRPC = {356 opal: {357 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,358 },359 quartz: {360 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,361 },362 unique: {363 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,364 },365 };366 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);367 const rpc = supportedRPC[network];368369 // TODO: investigate how to replace rpc in runtime370 // api._rpcCore.addUserInterfaces(rpc);371372 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});373374 await api.isReadyOrError;375376 if (typeof listeners === 'undefined') listeners = {};377 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {378 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;379 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);380 }381382 return {api, network};383 }384385 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {386 const {events, status} = data;387 if (status.isReady) {388 return this.transactionStatus.NOT_READY;389 }390 if (status.isBroadcast) {391 return this.transactionStatus.NOT_READY;392 }393 if (status.isInBlock || status.isFinalized) {394 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');395 if (errors.length > 0) {396 return this.transactionStatus.FAIL;397 }398 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {399 return this.transactionStatus.SUCCESS;400 }401 }402403 return this.transactionStatus.FAIL;404 }405406 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {407 const sign = (callback: any) => {408 if(options !== null) return transaction.signAndSend(sender, options, callback);409 return transaction.signAndSend(sender, callback);410 };411 // eslint-disable-next-line no-async-promise-executor412 return new Promise(async (resolve, reject) => {413 try {414 const unsub = await sign((result: any) => {415 const status = this.getTransactionStatus(result);416417 if (status === this.transactionStatus.SUCCESS) {418 this.logger.log(`${label} successful`);419 unsub();420 resolve({result, status});421 } else if (status === this.transactionStatus.FAIL) {422 let moduleError = null;423424 if (result.hasOwnProperty('dispatchError')) {425 const dispatchError = result['dispatchError'];426427 if (dispatchError) {428 if (dispatchError.isModule) {429 const modErr = dispatchError.asModule;430 const errorMeta = dispatchError.registry.findMetaError(modErr);431432 moduleError = `${errorMeta.section}.${errorMeta.name}`;433 } else {434 moduleError = dispatchError.toHuman();435 }436 } else {437 this.logger.log(result, this.logger.level.ERROR);438 }439 }440441 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);442 unsub();443 reject({status, moduleError, result});444 }445 });446 } catch (e) {447 this.logger.log(e, this.logger.level.ERROR);448 reject(e);449 }450 });451 }452453 constructApiCall(apiCall: string, params: any[]) {454 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);455 let call = this.api as any;456 for(const part of apiCall.slice(4).split('.')) {457 call = call[part];458 }459 return call(...params);460 }461462 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {463 if(this.api === null) throw Error('API not initialized');464 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);465466 const startTime = (new Date()).getTime();467 let result: ITransactionResult;468 let events: IEvent[] = [];469 try {470 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;471 events = this.eventHelper.extractEvents(result);472 }473 catch(e) {474 if(!(e as object).hasOwnProperty('status')) throw e;475 result = e as ITransactionResult;476 }477478 const endTime = (new Date()).getTime();479480 const log = {481 executedAt: endTime,482 executionTime: endTime - startTime,483 type: this.chainLogType.EXTRINSIC,484 status: result.status,485 call: extrinsic,486 signer: this.getSignerAddress(sender),487 params,488 } as IUniqueHelperLog;489490 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;491 if(events.length > 0) log.events = events;492493 this.chainLog.push(log);494495 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);496 return result;497 }498499 async callRpc(rpc: string, params?: any[]) {500 if(typeof params === 'undefined') params = [];501 if(this.api === null) throw Error('API not initialized');502 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);503504 const startTime = (new Date()).getTime();505 let result;506 let error = null;507 const log = {508 type: this.chainLogType.RPC,509 call: rpc,510 params,511 } as IUniqueHelperLog;512513 try {514 result = await this.constructApiCall(rpc, params);515 }516 catch(e) {517 error = e;518 }519520 const endTime = (new Date()).getTime();521522 log.executedAt = endTime;523 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';524 log.executionTime = endTime - startTime;525526 this.chainLog.push(log);527528 if(error !== null) throw error;529530 return result;531 }532533 getSignerAddress(signer: IKeyringPair | string): string {534 if(typeof signer === 'string') return signer;535 return signer.address;536 }537538 fetchAllPalletNames(): string[] {539 if(this.api === null) throw Error('API not initialized');540 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());541 }542543 fetchMissingPalletNames(requiredPallets: string[]): string[] {544 const palletNames = this.fetchAllPalletNames();545 return requiredPallets.filter(p => !palletNames.includes(p));546 }547}548549550class HelperGroup {551 helper: UniqueHelper;552553 constructor(uniqueHelper: UniqueHelper) {554 this.helper = uniqueHelper;555 }556}557558559class CollectionGroup extends HelperGroup {560 /**561 * Get number of blocks when sponsored transaction is available.562 *563 * @param collectionId ID of collection564 * @param tokenId ID of token565 * @param addressObj address for which the sponsorship is checked566 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});567 * @returns number of blocks or null if sponsorship hasn't been set568 */569 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {570 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();571 }572573 /**574 * Get the number of created collections.575 *576 * @returns number of created collections577 */578 async getTotalCount(): Promise<number> {579 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();580 }581582 /**583 * Get information about the collection with additional data,584 * including the number of tokens it contains, its administrators,585 * the normalized address of the collection's owner, and decoded name and description.586 *587 * @param collectionId ID of collection588 * @example await getData(2)589 * @returns collection information object590 */591 async getData(collectionId: number): Promise<{592 id: number;593 name: string;594 description: string;595 tokensCount: number;596 admins: CrossAccountId[];597 normalizedOwner: TSubstrateAccount;598 raw: any599 } | null> {600 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);601 const humanCollection = collection.toHuman(), collectionData = {602 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],603 raw: humanCollection,604 } as any, jsonCollection = collection.toJSON();605 if (humanCollection === null) return null;606 collectionData.raw.limits = jsonCollection.limits;607 collectionData.raw.permissions = jsonCollection.permissions;608 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);609 for (const key of ['name', 'description']) {610 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);611 }612613 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))614 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)615 : 0;616 collectionData.admins = await this.getAdmins(collectionId);617618 return collectionData;619 }620621 /**622 * Get the addresses of the collection's administrators, optionally normalized.623 *624 * @param collectionId ID of collection625 * @param normalize whether to normalize the addresses to the default ss58 format626 * @example await getAdmins(1)627 * @returns array of administrators628 */629 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {630 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();631632 return normalize633 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())634 : admins;635 }636637 /**638 * Get the addresses added to the collection allow-list, optionally normalized.639 * @param collectionId ID of collection640 * @param normalize whether to normalize the addresses to the default ss58 format641 * @example await getAllowList(1)642 * @returns array of allow-listed addresses643 */644 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {645 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();646 return normalize647 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())648 : allowListed;649 }650651 /**652 * Get the effective limits of the collection instead of null for default values653 *654 * @param collectionId ID of collection655 * @example await getEffectiveLimits(2)656 * @returns object of collection limits657 */658 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {659 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();660 }661662 /**663 * Burns the collection if the signer has sufficient permissions and collection is empty.664 *665 * @param signer keyring of signer666 * @param collectionId ID of collection667 * @example await helper.collection.burn(aliceKeyring, 3);668 * @returns ```true``` if extrinsic success, otherwise ```false```669 */670 async burn(signer: TSigner, collectionId: number): Promise<boolean> {671 const result = await this.helper.executeExtrinsic(672 signer,673 'api.tx.unique.destroyCollection', [collectionId],674 true,675 );676677 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');678 }679680 /**681 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.682 *683 * @param signer keyring of signer684 * @param collectionId ID of collection685 * @param sponsorAddress Sponsor substrate address686 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")687 * @returns ```true``` if extrinsic success, otherwise ```false```688 */689 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {690 const result = await this.helper.executeExtrinsic(691 signer,692 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],693 true,694 );695696 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');697 }698699 /**700 * Confirms consent to sponsor the collection on behalf of the signer.701 *702 * @param signer keyring of signer703 * @param collectionId ID of collection704 * @example confirmSponsorship(aliceKeyring, 10)705 * @returns ```true``` if extrinsic success, otherwise ```false```706 */707 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {708 const result = await this.helper.executeExtrinsic(709 signer,710 'api.tx.unique.confirmSponsorship', [collectionId],711 true,712 );713714 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');715 }716717 /**718 * Removes the sponsor of a collection, regardless if it consented or not.719 *720 * @param signer keyring of signer721 * @param collectionId ID of collection722 * @example removeSponsor(aliceKeyring, 10)723 * @returns ```true``` if extrinsic success, otherwise ```false```724 */725 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {726 const result = await this.helper.executeExtrinsic(727 signer,728 'api.tx.unique.removeCollectionSponsor', [collectionId],729 true,730 );731732 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');733 }734735 /**736 * Sets the limits of the collection. At least one limit must be specified for a correct call.737 *738 * @param signer keyring of signer739 * @param collectionId ID of collection740 * @param limits collection limits object741 * @example742 * await setLimits(743 * aliceKeyring,744 * 10,745 * {746 * sponsorTransferTimeout: 0,747 * ownerCanDestroy: false748 * }749 * )750 * @returns ```true``` if extrinsic success, otherwise ```false```751 */752 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {753 const result = await this.helper.executeExtrinsic(754 signer,755 'api.tx.unique.setCollectionLimits', [collectionId, limits],756 true,757 );758759 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');760 }761762 /**763 * Changes the owner of the collection to the new Substrate address.764 *765 * @param signer keyring of signer766 * @param collectionId ID of collection767 * @param ownerAddress substrate address of new owner768 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")769 * @returns ```true``` if extrinsic success, otherwise ```false```770 */771 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {772 const result = await this.helper.executeExtrinsic(773 signer,774 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],775 true,776 );777778 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');779 }780781 /**782 * Adds a collection administrator.783 *784 * @param signer keyring of signer785 * @param collectionId ID of collection786 * @param adminAddressObj Administrator address (substrate or ethereum)787 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})788 * @returns ```true``` if extrinsic success, otherwise ```false```789 */790 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {791 const result = await this.helper.executeExtrinsic(792 signer,793 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],794 true,795 );796797 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');798 }799800 /**801 * Removes a collection administrator.802 *803 * @param signer keyring of signer804 * @param collectionId ID of collection805 * @param adminAddressObj Administrator address (substrate or ethereum)806 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})807 * @returns ```true``` if extrinsic success, otherwise ```false```808 */809 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {810 const result = await this.helper.executeExtrinsic(811 signer,812 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],813 true,814 );815816 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');817 }818819 /**820 * Check if user is in allow list.821 * 822 * @param collectionId ID of collection823 * @param user Account to check824 * @example await getAdmins(1)825 * @returns is user in allow list826 */827 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {828 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();829 }830831 /**832 * Adds an address to allow list833 * @param signer keyring of signer834 * @param collectionId ID of collection835 * @param addressObj address to add to the allow list836 * @returns ```true``` if extrinsic success, otherwise ```false```837 */838 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {839 const result = await this.helper.executeExtrinsic(840 signer,841 'api.tx.unique.addToAllowList', [collectionId, addressObj],842 true,843 );844845 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');846 }847848 /**849 * Removes an address from allow list850 *851 * @param signer keyring of signer852 * @param collectionId ID of collection853 * @param addressObj address to remove from the allow list854 * @returns ```true``` if extrinsic success, otherwise ```false```855 */856 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {857 const result = await this.helper.executeExtrinsic(858 signer,859 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],860 true,861 );862863 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');864 }865866 /**867 * Sets onchain permissions for selected collection.868 *869 * @param signer keyring of signer870 * @param collectionId ID of collection871 * @param permissions collection permissions object872 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});873 * @returns ```true``` if extrinsic success, otherwise ```false```874 */875 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {876 const result = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],879 true,880 );881882 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');883 }884885 /**886 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.887 *888 * @param signer keyring of signer889 * @param collectionId ID of collection890 * @param permissions nesting permissions object891 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});892 * @returns ```true``` if extrinsic success, otherwise ```false```893 */894 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {895 return await this.setPermissions(signer, collectionId, {nesting: permissions});896 }897898 /**899 * Disables nesting for selected collection.900 *901 * @param signer keyring of signer902 * @param collectionId ID of collection903 * @example disableNesting(aliceKeyring, 10);904 * @returns ```true``` if extrinsic success, otherwise ```false```905 */906 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {907 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});908 }909910 /**911 * Sets onchain properties to the collection.912 *913 * @param signer keyring of signer914 * @param collectionId ID of collection915 * @param properties array of property objects916 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);917 * @returns ```true``` if extrinsic success, otherwise ```false```918 */919 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.setCollectionProperties', [collectionId, properties],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');927 }928929 /**930 * Get collection properties.931 * 932 * @param collectionId ID of collection933 * @param propertyKeys optionally filter the returned properties to only these keys934 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);935 * @returns array of key-value pairs936 */937 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {938 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();939 }940941 /**942 * Deletes onchain properties from the collection.943 *944 * @param signer keyring of signer945 * @param collectionId ID of collection946 * @param propertyKeys array of property keys to delete947 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);948 * @returns ```true``` if extrinsic success, otherwise ```false```949 */950 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');958 }959960 /**961 * Changes the owner of the token.962 *963 * @param signer keyring of signer964 * @param collectionId ID of collection965 * @param tokenId ID of token966 * @param addressObj address of a new owner967 * @param amount amount of tokens to be transfered. For NFT must be set to 1n968 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})969 * @returns true if the token success, otherwise false970 */971 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],975 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,976 );977978 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);979 }980981 /**982 *983 * Change ownership of a token(s) on behalf of the owner.984 *985 * @param signer keyring of signer986 * @param collectionId ID of collection987 * @param tokenId ID of token988 * @param fromAddressObj address on behalf of which the token will be sent989 * @param toAddressObj new token owner990 * @param amount amount of tokens to be transfered. For NFT must be set to 1n991 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})992 * @returns true if the token success, otherwise false993 */994 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],998 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,999 );1000 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1001 }10021003 /**1004 *1005 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1006 *1007 * @param signer keyring of signer1008 * @param collectionId ID of collection1009 * @param tokenId ID of token1010 * @param amount amount of tokens to be burned. For NFT must be set to 1n1011 * @example burnToken(aliceKeyring, 10, 5);1012 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1013 */1014 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1015 const burnResult = await this.helper.executeExtrinsic(1016 signer,1017 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1018 true, // `Unable to burn token for ${label}`,1019 );1020 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1021 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1022 return burnedTokens.success;1023 }10241025 /**1026 * Destroys a concrete instance of NFT on behalf of the owner1027 *1028 * @param signer keyring of signer1029 * @param collectionId ID of collection1030 * @param tokenId ID of token1031 * @param fromAddressObj address on behalf of which the token will be burnt1032 * @param amount amount of tokens to be burned. For NFT must be set to 1n1033 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1034 * @returns ```true``` if extrinsic success, otherwise ```false```1035 */1036 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1037 const burnResult = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1040 true, // `Unable to burn token from for ${label}`,1041 );1042 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1043 return burnedTokens.success && burnedTokens.tokens.length > 0;1044 }10451046 /**1047 * Set, change, or remove approved address to transfer the ownership of the NFT.1048 *1049 * @param signer keyring of signer1050 * @param collectionId ID of collection1051 * @param tokenId ID of token1052 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1053 * @param amount amount of token to be approved. For NFT must be set to 1n1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1057 const approveResult = await this.helper.executeExtrinsic(1058 signer,1059 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1060 true, // `Unable to approve token for ${label}`,1061 );10621063 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1064 }10651066 /**1067 * Get the amount of token pieces approved to transfer or burn. Normally 0.1068 *1069 * @param collectionId ID of collection1070 * @param tokenId ID of token1071 * @param toAccountObj address which is approved to use token pieces1072 * @param fromAccountObj address which may have allowed the use of its owned tokens1073 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1074 * @returns number of approved to transfer pieces1075 */1076 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1077 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1078 }10791080 /**1081 * Get the last created token ID in a collection1082 *1083 * @param collectionId ID of collection1084 * @example getLastTokenId(10);1085 * @returns id of the last created token1086 */1087 async getLastTokenId(collectionId: number): Promise<number> {1088 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1089 }10901091 /**1092 * Check if token exists1093 *1094 * @param collectionId ID of collection1095 * @param tokenId ID of token1096 * @example isTokenExists(10, 20);1097 * @returns true if the token exists, otherwise false1098 */1099 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1100 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1101 }1102}11031104class NFTnRFT extends CollectionGroup {1105 /**1106 * Get tokens owned by account1107 *1108 * @param collectionId ID of collection1109 * @param addressObj tokens owner1110 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1111 * @returns array of token ids owned by account1112 */1113 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1114 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1115 }11161117 /**1118 * Get token data1119 *1120 * @param collectionId ID of collection1121 * @param tokenId ID of token1122 * @param propertyKeys optionally filter the token properties to only these keys1123 * @param blockHashAt optionally query the data at some block with this hash1124 * @example getToken(10, 5);1125 * @returns human readable token data1126 */1127 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1128 properties: IProperty[];1129 owner: CrossAccountId;1130 normalizedOwner: CrossAccountId;1131 }| null> {1132 let tokenData;1133 if(typeof blockHashAt === 'undefined') {1134 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1135 }1136 else {1137 if(propertyKeys.length == 0) {1138 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1139 if(!collection) return null;1140 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1141 }1142 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1143 }1144 tokenData = tokenData.toHuman();1145 if (tokenData === null || tokenData.owner === null) return null;1146 const owner = {} as any;1147 for (const key of Object.keys(tokenData.owner)) {1148 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1149 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1150 : tokenData.owner[key];1151 }1152 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1153 return tokenData;1154 }11551156 /**1157 * Set permissions to change token properties1158 *1159 * @param signer keyring of signer1160 * @param collectionId ID of collection1161 * @param permissions permissions to change a property by the collection admin or token owner1162 * @example setTokenPropertyPermissions(1163 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1164 * )1165 * @returns true if extrinsic success otherwise false1166 */1167 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1171 true,1172 );11731174 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1175 }11761177 /**1178 * Get token property permissions.1179 * 1180 * @param collectionId ID of collection1181 * @param propertyKeys optionally filter the returned property permissions to only these keys1182 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1183 * @returns array of key-permission pairs1184 */1185 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1186 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1187 }11881189 /**1190 * Set token properties1191 *1192 * @param signer keyring of signer1193 * @param collectionId ID of collection1194 * @param tokenId ID of token1195 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1196 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1197 * @returns ```true``` if extrinsic success, otherwise ```false```1198 */1199 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1200 const result = await this.helper.executeExtrinsic(1201 signer,1202 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1203 true,1204 );12051206 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1207 }12081209 /**1210 * Get properties, metadata assigned to a token.1211 * 1212 * @param collectionId ID of collection1213 * @param tokenId ID of token1214 * @param propertyKeys optionally filter the returned properties to only these keys1215 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1216 * @returns array of key-value pairs1217 */1218 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1219 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1220 }12211222 /**1223 * Delete the provided properties of a token1224 * @param signer keyring of signer1225 * @param collectionId ID of collection1226 * @param tokenId ID of token1227 * @param propertyKeys property keys to be deleted1228 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1229 * @returns ```true``` if extrinsic success, otherwise ```false```1230 */1231 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1232 const result = await this.helper.executeExtrinsic(1233 signer,1234 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1235 true,1236 );12371238 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1239 }12401241 /**1242 * Mint new collection1243 *1244 * @param signer keyring of signer1245 * @param collectionOptions basic collection options and properties1246 * @param mode NFT or RFT type of a collection1247 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1248 * @returns object of the created collection1249 */1250 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1251 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1252 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1253 for (const key of ['name', 'description', 'tokenPrefix']) {1254 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);1255 }1256 const creationResult = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.createCollectionEx', [collectionOptions],1259 true, // errorLabel,1260 );1261 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1262 }12631264 getCollectionObject(_collectionId: number): any {1265 return null;1266 }12671268 getTokenObject(_collectionId: number, _tokenId: number): any {1269 return null;1270 }1271}127212731274class NFTGroup extends NFTnRFT {1275 /**1276 * Get collection object1277 * @param collectionId ID of collection1278 * @example getCollectionObject(2);1279 * @returns instance of UniqueNFTCollection1280 */1281 getCollectionObject(collectionId: number): UniqueNFTCollection {1282 return new UniqueNFTCollection(collectionId, this.helper);1283 }12841285 /**1286 * Get token object1287 * @param collectionId ID of collection1288 * @param tokenId ID of token1289 * @example getTokenObject(10, 5);1290 * @returns instance of UniqueNFTToken1291 */1292 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1293 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1294 }12951296 /**1297 * Get token's owner1298 * @param collectionId ID of collection1299 * @param tokenId ID of token1300 * @param blockHashAt optionally query the data at the block with this hash1301 * @example getTokenOwner(10, 5);1302 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1303 */1304 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1305 let owner;1306 if (typeof blockHashAt === 'undefined') {1307 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1308 } else {1309 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1310 }1311 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1312 }13131314 /**1315 * Is token approved to transfer1316 * @param collectionId ID of collection1317 * @param tokenId ID of token1318 * @param toAccountObj address to be approved1319 * @returns ```true``` if extrinsic success, otherwise ```false```1320 */1321 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1322 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1323 }13241325 /**1326 * Changes the owner of the token.1327 *1328 * @param signer keyring of signer1329 * @param collectionId ID of collection1330 * @param tokenId ID of token1331 * @param addressObj address of a new owner1332 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1333 * @returns ```true``` if extrinsic success, otherwise ```false```1334 */1335 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1336 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1337 }13381339 /**1340 *1341 * Change ownership of a NFT on behalf of the owner.1342 *1343 * @param signer keyring of signer1344 * @param collectionId ID of collection1345 * @param tokenId ID of token1346 * @param fromAddressObj address on behalf of which the token will be sent1347 * @param toAddressObj new token owner1348 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1349 * @returns ```true``` if extrinsic success, otherwise ```false```1350 */1351 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1352 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1353 }13541355 /**1356 * Recursively find the address that owns the token1357 * @param collectionId ID of collection1358 * @param tokenId ID of token1359 * @param blockHashAt1360 * @example getTokenTopmostOwner(10, 5);1361 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1362 */1363 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1364 let owner;1365 if (typeof blockHashAt === 'undefined') {1366 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1367 } else {1368 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1369 }13701371 if (owner === null) return null;13721373 return owner.toHuman();1374 }13751376 /**1377 * Get tokens nested in the provided token1378 * @param collectionId ID of collection1379 * @param tokenId ID of token1380 * @param blockHashAt optionally query the data at the block with this hash1381 * @example getTokenChildren(10, 5);1382 * @returns tokens whose depth of nesting is <= 51383 */1384 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1385 let children;1386 if(typeof blockHashAt === 'undefined') {1387 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1388 } else {1389 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1390 }13911392 return children.toJSON().map((x: any) => {1393 return {collectionId: x.collection, tokenId: x.token};1394 });1395 }13961397 /**1398 * Nest one token into another1399 * @param signer keyring of signer1400 * @param tokenObj token to be nested1401 * @param rootTokenObj token to be parent1402 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1403 * @returns ```true``` if extrinsic success, otherwise ```false```1404 */1405 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1406 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1407 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1408 if(!result) {1409 throw Error('Unable to nest token!');1410 }1411 return result;1412 }14131414 /**1415 * Remove token from nested state1416 * @param signer keyring of signer1417 * @param tokenObj token to unnest1418 * @param rootTokenObj parent of a token1419 * @param toAddressObj address of a new token owner1420 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1421 * @returns ```true``` if extrinsic success, otherwise ```false```1422 */1423 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1424 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1425 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1426 if(!result) {1427 throw Error('Unable to unnest token!');1428 }1429 return result;1430 }14311432 /**1433 * Mint new collection1434 * @param signer keyring of signer1435 * @param collectionOptions Collection options1436 * @example1437 * mintCollection(aliceKeyring, {1438 * name: 'New',1439 * description: 'New collection',1440 * tokenPrefix: 'NEW',1441 * })1442 * @returns object of the created collection1443 */1444 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1445 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1446 }14471448 /**1449 * Mint new token1450 * @param signer keyring of signer1451 * @param data token data1452 * @returns created token object1453 */1454 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1455 const creationResult = await this.helper.executeExtrinsic(1456 signer,1457 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1458 nft: {1459 properties: data.properties,1460 },1461 }],1462 true,1463 );1464 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1465 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1466 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1467 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1468 }14691470 /**1471 * Mint multiple NFT tokens1472 * @param signer keyring of signer1473 * @param collectionId ID of collection1474 * @param tokens array of tokens with owner and properties1475 * @example1476 * mintMultipleTokens(aliceKeyring, 10, [{1477 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1478 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1479 * },{1480 * owner: {Ethereum: "0x9F0583DbB855d..."},1481 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1482 * }]);1483 * @returns ```true``` if extrinsic success, otherwise ```false```1484 */1485 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1486 const creationResult = await this.helper.executeExtrinsic(1487 signer,1488 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1489 true,1490 );1491 const collection = this.getCollectionObject(collectionId);1492 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1493 }14941495 /**1496 * Mint multiple NFT tokens with one owner1497 * @param signer keyring of signer1498 * @param collectionId ID of collection1499 * @param owner tokens owner1500 * @param tokens array of tokens with owner and properties1501 * @example1502 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1503 * properties: [{1504 * key: "gender",1505 * value: "female",1506 * },{1507 * key: "age",1508 * value: "33",1509 * }],1510 * }]);1511 * @returns array of newly created tokens1512 */1513 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1514 const rawTokens = [];1515 for (const token of tokens) {1516 const raw = {NFT: {properties: token.properties}};1517 rawTokens.push(raw);1518 }1519 const creationResult = await this.helper.executeExtrinsic(1520 signer,1521 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1522 true,1523 );1524 const collection = this.getCollectionObject(collectionId);1525 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1526 }15271528 /**1529 * Set, change, or remove approved address to transfer the ownership of the NFT.1530 *1531 * @param signer keyring of signer1532 * @param collectionId ID of collection1533 * @param tokenId ID of token1534 * @param toAddressObj address to approve1535 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1536 * @returns ```true``` if extrinsic success, otherwise ```false```1537 */1538 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1539 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1540 }1541}154215431544class RFTGroup extends NFTnRFT {1545 /**1546 * Get collection object1547 * @param collectionId ID of collection1548 * @example getCollectionObject(2);1549 * @returns instance of UniqueRFTCollection1550 */1551 getCollectionObject(collectionId: number): UniqueRFTCollection {1552 return new UniqueRFTCollection(collectionId, this.helper);1553 }15541555 /**1556 * Get token object1557 * @param collectionId ID of collection1558 * @param tokenId ID of token1559 * @example getTokenObject(10, 5);1560 * @returns instance of UniqueNFTToken1561 */1562 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1563 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1564 }15651566 /**1567 * Get top 10 token owners with the largest number of pieces1568 * @param collectionId ID of collection1569 * @param tokenId ID of token1570 * @example getTokenTop10Owners(10, 5);1571 * @returns array of top 10 owners1572 */1573 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1574 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1575 }15761577 /**1578 * Get number of pieces owned by address1579 * @param collectionId ID of collection1580 * @param tokenId ID of token1581 * @param addressObj address token owner1582 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1583 * @returns number of pieces ownerd by address1584 */1585 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1586 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1587 }15881589 /**1590 * Transfer pieces of token to another address1591 * @param signer keyring of signer1592 * @param collectionId ID of collection1593 * @param tokenId ID of token1594 * @param addressObj address of a new owner1595 * @param amount number of pieces to be transfered1596 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1597 * @returns ```true``` if extrinsic success, otherwise ```false```1598 */1599 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1600 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1601 }16021603 /**1604 * Change ownership of some pieces of RFT on behalf of the owner.1605 * @param signer keyring of signer1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param fromAddressObj address on behalf of which the token will be sent1609 * @param toAddressObj new token owner1610 * @param amount number of pieces to be transfered1611 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1612 * @returns ```true``` if extrinsic success, otherwise ```false```1613 */1614 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1615 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1616 }16171618 /**1619 * Mint new collection1620 * @param signer keyring of signer1621 * @param collectionOptions Collection options1622 * @example1623 * mintCollection(aliceKeyring, {1624 * name: 'New',1625 * description: 'New collection',1626 * tokenPrefix: 'NEW',1627 * })1628 * @returns object of the created collection1629 */1630 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1631 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1632 }16331634 /**1635 * Mint new token1636 * @param signer keyring of signer1637 * @param data token data1638 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1639 * @returns created token object1640 */1641 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1642 const creationResult = await this.helper.executeExtrinsic(1643 signer,1644 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1645 refungible: {1646 pieces: data.pieces,1647 properties: data.properties,1648 },1649 }],1650 true,1651 );1652 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1653 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1654 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1655 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1656 }16571658 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1659 throw Error('Not implemented');1660 const creationResult = await this.helper.executeExtrinsic(1661 signer,1662 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1663 true, // `Unable to mint RFT tokens for ${label}`,1664 );1665 const collection = this.getCollectionObject(collectionId);1666 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1667 }16681669 /**1670 * Mint multiple RFT tokens with one owner1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param owner tokens owner1674 * @param tokens array of tokens with properties and pieces1675 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1676 * @returns array of newly created RFT tokens1677 */1678 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1679 const rawTokens = [];1680 for (const token of tokens) {1681 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1682 rawTokens.push(raw);1683 }1684 const creationResult = await this.helper.executeExtrinsic(1685 signer,1686 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1687 true,1688 );1689 const collection = this.getCollectionObject(collectionId);1690 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1691 }16921693 /**1694 * Destroys a concrete instance of RFT.1695 * @param signer keyring of signer1696 * @param collectionId ID of collection1697 * @param tokenId ID of token1698 * @param amount number of pieces to be burnt1699 * @example burnToken(aliceKeyring, 10, 5);1700 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1701 */1702 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1703 return await super.burnToken(signer, collectionId, tokenId, amount);1704 }17051706 /**1707 * Destroys a concrete instance of RFT on behalf of the owner.1708 * @param signer keyring of signer1709 * @param collectionId ID of collection1710 * @param tokenId ID of token1711 * @param fromAddressObj address on behalf of which the token will be burnt1712 * @param amount number of pieces to be burnt1713 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1714 * @returns ```true``` if extrinsic success, otherwise ```false```1715 */1716 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1717 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1718 }17191720 /**1721 * Set, change, or remove approved address to transfer the ownership of the RFT.1722 *1723 * @param signer keyring of signer1724 * @param collectionId ID of collection1725 * @param tokenId ID of token1726 * @param toAddressObj address to approve1727 * @param amount number of pieces to be approved1728 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1729 * @returns true if the token success, otherwise false1730 */1731 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1732 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1733 }17341735 /**1736 * Get total number of pieces1737 * @param collectionId ID of collection1738 * @param tokenId ID of token1739 * @example getTokenTotalPieces(10, 5);1740 * @returns number of pieces1741 */1742 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1743 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1744 }17451746 /**1747 * Change number of token pieces. Signer must be the owner of all token pieces.1748 * @param signer keyring of signer1749 * @param collectionId ID of collection1750 * @param tokenId ID of token1751 * @param amount new number of pieces1752 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1753 * @returns true if the repartion was success, otherwise false1754 */1755 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1756 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1757 const repartitionResult = await this.helper.executeExtrinsic(1758 signer,1759 'api.tx.unique.repartition', [collectionId, tokenId, amount],1760 true,1761 );1762 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1763 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1764 }1765}176617671768class FTGroup extends CollectionGroup {1769 /**1770 * Get collection object1771 * @param collectionId ID of collection1772 * @example getCollectionObject(2);1773 * @returns instance of UniqueFTCollection1774 */1775 getCollectionObject(collectionId: number): UniqueFTCollection {1776 return new UniqueFTCollection(collectionId, this.helper);1777 }17781779 /**1780 * Mint new fungible collection1781 * @param signer keyring of signer1782 * @param collectionOptions Collection options1783 * @param decimalPoints number of token decimals1784 * @example1785 * mintCollection(aliceKeyring, {1786 * name: 'New',1787 * description: 'New collection',1788 * tokenPrefix: 'NEW',1789 * }, 18)1790 * @returns newly created fungible collection1791 */1792 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1793 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1794 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1795 collectionOptions.mode = {fungible: decimalPoints};1796 for (const key of ['name', 'description', 'tokenPrefix']) {1797 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);1798 }1799 const creationResult = await this.helper.executeExtrinsic(1800 signer,1801 'api.tx.unique.createCollectionEx', [collectionOptions],1802 true,1803 );1804 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1805 }18061807 /**1808 * Mint tokens1809 * @param signer keyring of signer1810 * @param collectionId ID of collection1811 * @param owner address owner of new tokens1812 * @param amount amount of tokens to be meanted1813 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1814 * @returns ```true``` if extrinsic success, otherwise ```false```1815 */1816 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1817 const creationResult = await this.helper.executeExtrinsic(1818 signer,1819 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1820 fungible: {1821 value: amount,1822 },1823 }],1824 true, // `Unable to mint fungible tokens for ${label}`,1825 );1826 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1827 }18281829 /**1830 * Mint multiple Fungible tokens with one owner1831 * @param signer keyring of signer1832 * @param collectionId ID of collection1833 * @param owner tokens owner1834 * @param tokens array of tokens with properties and pieces1835 * @returns ```true``` if extrinsic success, otherwise ```false```1836 */1837 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1838 const rawTokens = [];1839 for (const token of tokens) {1840 const raw = {Fungible: {Value: token.value}};1841 rawTokens.push(raw);1842 }1843 const creationResult = await this.helper.executeExtrinsic(1844 signer,1845 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1846 true,1847 );1848 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1849 }18501851 /**1852 * Get the top 10 owners with the largest balance for the Fungible collection1853 * @param collectionId ID of collection1854 * @example getTop10Owners(10);1855 * @returns array of ```ICrossAccountId```1856 */1857 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1858 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1859 }18601861 /**1862 * Get account balance1863 * @param collectionId ID of collection1864 * @param addressObj address of owner1865 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1866 * @returns amount of fungible tokens owned by address1867 */1868 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1869 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1870 }18711872 /**1873 * Transfer tokens to address1874 * @param signer keyring of signer1875 * @param collectionId ID of collection1876 * @param toAddressObj address recipient1877 * @param amount amount of tokens to be sent1878 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1879 * @returns ```true``` if extrinsic success, otherwise ```false```1880 */1881 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1882 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1883 }18841885 /**1886 * Transfer some tokens on behalf of the owner.1887 * @param signer keyring of signer1888 * @param collectionId ID of collection1889 * @param fromAddressObj address on behalf of which tokens will be sent1890 * @param toAddressObj address where token to be sent1891 * @param amount number of tokens to be sent1892 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1893 * @returns ```true``` if extrinsic success, otherwise ```false```1894 */1895 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1896 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1897 }18981899 /**1900 * Destroy some amount of tokens1901 * @param signer keyring of signer1902 * @param collectionId ID of collection1903 * @param amount amount of tokens to be destroyed1904 * @example burnTokens(aliceKeyring, 10, 1000n);1905 * @returns ```true``` if extrinsic success, otherwise ```false```1906 */1907 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1908 return await super.burnToken(signer, collectionId, 0, amount);1909 }19101911 /**1912 * Burn some tokens on behalf of the owner.1913 * @param signer keyring of signer1914 * @param collectionId ID of collection1915 * @param fromAddressObj address on behalf of which tokens will be burnt1916 * @param amount amount of tokens to be burnt1917 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1918 * @returns ```true``` if extrinsic success, otherwise ```false```1919 */1920 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1921 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1922 }19231924 /**1925 * Get total collection supply1926 * @param collectionId1927 * @returns1928 */1929 async getTotalPieces(collectionId: number): Promise<bigint> {1930 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1931 }19321933 /**1934 * Set, change, or remove approved address to transfer tokens.1935 *1936 * @param signer keyring of signer1937 * @param collectionId ID of collection1938 * @param toAddressObj address to be approved1939 * @param amount amount of tokens to be approved1940 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1941 * @returns ```true``` if extrinsic success, otherwise ```false```1942 */1943 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1944 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1945 }19461947 /**1948 * Get amount of fungible tokens approved to transfer1949 * @param collectionId ID of collection1950 * @param fromAddressObj owner of tokens1951 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1952 * @returns number of tokens approved for the transfer1953 */1954 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1955 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1956 }1957}195819591960class ChainGroup extends HelperGroup {1961 /**1962 * Get system properties of a chain1963 * @example getChainProperties();1964 * @returns ss58Format, token decimals, and token symbol1965 */1966 getChainProperties(): IChainProperties {1967 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1968 return {1969 ss58Format: properties.ss58Format.toJSON(),1970 tokenDecimals: properties.tokenDecimals.toJSON(),1971 tokenSymbol: properties.tokenSymbol.toJSON(),1972 };1973 }19741975 /**1976 * Get chain header1977 * @example getLatestBlockNumber();1978 * @returns the number of the last block1979 */1980 async getLatestBlockNumber(): Promise<number> {1981 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1982 }19831984 /**1985 * Get block hash by block number1986 * @param blockNumber number of block1987 * @example getBlockHashByNumber(12345);1988 * @returns hash of a block1989 */1990 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1991 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1992 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1993 return blockHash;1994 }19951996 // TODO add docs1997 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1998 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1999 if (!blockHash) return null;2000 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2001 }20022003 /**2004 * Get account nonce2005 * @param address substrate address2006 * @example getNonce("5GrwvaEF5zXb26Fz...");2007 * @returns number, account's nonce2008 */2009 async getNonce(address: TSubstrateAccount): Promise<number> {2010 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2011 }2012}201320142015class BalanceGroup extends HelperGroup {2016 /**2017 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2018 * @example getOneTokenNominal()2019 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2020 */2021 getOneTokenNominal(): bigint {2022 const chainProperties = this.helper.chain.getChainProperties();2023 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2024 }20252026 /**2027 * Get substrate address balance2028 * @param address substrate address2029 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2030 * @returns amount of tokens on address2031 */2032 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2033 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2034 }20352036 /**2037 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2038 * @param address substrate address2039 * @returns2040 */2041 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2042 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2043 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2044 }20452046 /**2047 * Get ethereum address balance2048 * @param address ethereum address2049 * @example getEthereum("0x9F0583DbB855d...")2050 * @returns amount of tokens on address2051 */2052 async getEthereum(address: TEthereumAccount): Promise<bigint> {2053 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2054 }20552056 /**2057 * Transfer tokens to substrate address2058 * @param signer keyring of signer2059 * @param address substrate address of a recipient2060 * @param amount amount of tokens to be transfered2061 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2062 * @returns ```true``` if extrinsic success, otherwise ```false```2063 */2064 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2065 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}`*/);20662067 let transfer = {from: null, to: null, amount: 0n} as any;2068 result.result.events.forEach(({event: {data, method, section}}) => {2069 if ((section === 'balances') && (method === 'Transfer')) {2070 transfer = {2071 from: this.helper.address.normalizeSubstrate(data[0]),2072 to: this.helper.address.normalizeSubstrate(data[1]),2073 amount: BigInt(data[2]),2074 };2075 }2076 });2077 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2078 && this.helper.address.normalizeSubstrate(address) === transfer.to 2079 && BigInt(amount) === transfer.amount;2080 return isSuccess;2081 }2082}208320842085class AddressGroup extends HelperGroup {2086 /**2087 * Normalizes the address to the specified ss58 format, by default ```42```.2088 * @param address substrate address2089 * @param ss58Format format for address conversion, by default ```42```2090 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2091 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2092 */2093 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2094 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2095 }20962097 /**2098 * Get address in the connected chain format2099 * @param address substrate address2100 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2101 * @returns address in chain format2102 */2103 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2104 const info = this.helper.chain.getChainProperties();2105 return encodeAddress(decodeAddress(address), info.ss58Format);2106 }21072108 /**2109 * Get substrate mirror of an ethereum address2110 * @param ethAddress ethereum address2111 * @param toChainFormat false for normalized account2112 * @example ethToSubstrate('0x9F0583DbB855d...')2113 * @returns substrate mirror of a provided ethereum address2114 */2115 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2116 if(!toChainFormat) return evmToAddress(ethAddress);2117 const info = this.helper.chain.getChainProperties();2118 return evmToAddress(ethAddress, info.ss58Format);2119 }21202121 /**2122 * Get ethereum mirror of a substrate address2123 * @param subAddress substrate account2124 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2125 * @returns ethereum mirror of a provided substrate address2126 */2127 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2128 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2129 }2130}21312132class StakingGroup extends HelperGroup {2133 /**2134 * Stake tokens for App Promotion2135 * @param signer keyring of signer2136 * @param amountToStake amount of tokens to stake2137 * @param label extra label for log2138 * @returns2139 */2140 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2141 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2142 const stakeResult = await this.helper.executeExtrinsic(2143 signer, 'api.tx.appPromotion.stake',2144 [amountToStake], true,2145 );2146 // TODO extract info from stakeResult2147 return true;2148 }21492150 /**2151 * Unstake tokens for App Promotion2152 * @param signer keyring of signer2153 * @param amountToUnstake amount of tokens to unstake2154 * @param label extra label for log2155 * @returns block number where balances will be unlocked2156 */2157 async unstake(signer: TSigner, label?: string): Promise<number> {2158 if(typeof label === 'undefined') label = `${signer.address}`;2159 const unstakeResult = await this.helper.executeExtrinsic(2160 signer, 'api.tx.appPromotion.unstake',2161 [], true,2162 );2163 // TODO extract block number fron events2164 return 1;2165 }21662167 /**2168 * Get total staked amount for address2169 * @param address substrate or ethereum address2170 * @returns total staked amount2171 */2172 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2173 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2174 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2175 }21762177 /**2178 * Get total staked per block2179 * @param address substrate or ethereum address2180 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2181 */2182 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2183 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2184 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2185 return { 2186 block: block.toBigInt(),2187 amount: amount.toBigInt(),2188 };2189 });2190 }21912192 /**2193 * Get total pending unstake amount for address2194 * @param address substrate or ethereum address2195 * @returns total pending unstake amount2196 */2197 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2198 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2199 }22002201 /**2202 * Get pending unstake amount per block for address2203 * @param address substrate or ethereum address2204 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2205 */2206 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2207 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2208 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2209 return {2210 block: block.toBigInt(),2211 amount: amount.toBigInt(),2212 };2213 });2214 return result;2215 }2216}22172218export class UniqueHelper extends ChainHelperBase {2219 chain: ChainGroup;2220 balance: BalanceGroup;2221 address: AddressGroup;2222 collection: CollectionGroup;2223 nft: NFTGroup;2224 rft: RFTGroup;2225 ft: FTGroup;2226 staking: StakingGroup;22272228 constructor(logger?: ILogger) {2229 super(logger);2230 this.chain = new ChainGroup(this);2231 this.balance = new BalanceGroup(this);2232 this.address = new AddressGroup(this);2233 this.collection = new CollectionGroup(this);2234 this.nft = new NFTGroup(this);2235 this.rft = new RFTGroup(this);2236 this.ft = new FTGroup(this);2237 this.staking = new StakingGroup(this);2238 }2239}224022412242export class UniqueBaseCollection {2243 helper: UniqueHelper;2244 collectionId: number;22452246 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2247 this.collectionId = collectionId;2248 this.helper = uniqueHelper;2249 }22502251 async getData() {2252 return await this.helper.collection.getData(this.collectionId);2253 }22542255 async getLastTokenId() {2256 return await this.helper.collection.getLastTokenId(this.collectionId);2257 }22582259 async isTokenExists(tokenId: number) {2260 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2261 }22622263 async getAdmins() {2264 return await this.helper.collection.getAdmins(this.collectionId);2265 }22662267 async getAllowList() {2268 return await this.helper.collection.getAllowList(this.collectionId);2269 }22702271 async getEffectiveLimits() {2272 return await this.helper.collection.getEffectiveLimits(this.collectionId);2273 }22742275 async getProperties(propertyKeys: string[] | null = null) {2276 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2277 }22782279 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2280 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2281 }22822283 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2284 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2285 }22862287 async confirmSponsorship(signer: TSigner) {2288 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2289 }22902291 async removeSponsor(signer: TSigner) {2292 return await this.helper.collection.removeSponsor(signer, this.collectionId);2293 }22942295 async setLimits(signer: TSigner, limits: ICollectionLimits) {2296 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2297 }22982299 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2300 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2301 }23022303 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2304 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2305 }23062307 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2308 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2309 }23102311 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2312 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2313 }23142315 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2316 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2317 }23182319 async setProperties(signer: TSigner, properties: IProperty[]) {2320 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2321 }23222323 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2324 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2325 }23262327 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2328 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2329 }23302331 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2332 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2333 }23342335 async disableNesting(signer: TSigner) {2336 return await this.helper.collection.disableNesting(signer, this.collectionId);2337 }23382339 async burn(signer: TSigner) {2340 return await this.helper.collection.burn(signer, this.collectionId);2341 }2342}234323442345export class UniqueNFTCollection extends UniqueBaseCollection {2346 getTokenObject(tokenId: number) {2347 return new UniqueNFToken(tokenId, this);2348 }23492350 async getTokensByAddress(addressObj: ICrossAccountId) {2351 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2352 }23532354 async getToken(tokenId: number, blockHashAt?: string) {2355 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2356 }23572358 async getTokenOwner(tokenId: number, blockHashAt?: string) {2359 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2360 }23612362 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2363 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2364 }23652366 async getTokenChildren(tokenId: number, blockHashAt?: string) {2367 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2368 }23692370 async getPropertyPermissions(propertyKeys: string[] | null = null) {2371 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2372 }23732374 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2375 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2376 }23772378 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2379 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2380 }23812382 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2383 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2384 }23852386 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2387 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2388 }23892390 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2391 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2392 }23932394 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2395 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2396 }23972398 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2399 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2400 }24012402 async burnToken(signer: TSigner, tokenId: number) {2403 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2404 }24052406 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2407 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2408 }24092410 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2411 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2412 }24132414 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2415 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2416 }24172418 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2419 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2420 }24212422 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2423 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2424 }24252426 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2427 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2428 }2429}243024312432export class UniqueRFTCollection extends UniqueBaseCollection {2433 getTokenObject(tokenId: number) {2434 return new UniqueRFToken(tokenId, this);2435 }24362437 async getToken(tokenId: number, blockHashAt?: string) {2438 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2439 }24402441 async getTokensByAddress(addressObj: ICrossAccountId) {2442 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2443 }24442445 async getTop10TokenOwners(tokenId: number) {2446 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2447 }24482449 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2450 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2451 }24522453 async getTokenTotalPieces(tokenId: number) {2454 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2455 }24562457 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2458 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2459 }24602461 async getPropertyPermissions(propertyKeys: string[] | null = null) {2462 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2463 }24642465 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2466 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2467 }24682469 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2470 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2471 }24722473 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2474 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2475 }24762477 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2478 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2479 }24802481 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2482 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2483 }24842485 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2486 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2487 }24882489 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2490 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2491 }24922493 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2494 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2495 }24962497 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2498 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2499 }25002501 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2502 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2503 }25042505 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2506 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2507 }25082509 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2510 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2511 }2512}251325142515export class UniqueFTCollection extends UniqueBaseCollection {2516 async getBalance(addressObj: ICrossAccountId) {2517 return await this.helper.ft.getBalance(this.collectionId, addressObj);2518 }25192520 async getTotalPieces() {2521 return await this.helper.ft.getTotalPieces(this.collectionId);2522 }25232524 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2525 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2526 }25272528 async getTop10Owners() {2529 return await this.helper.ft.getTop10Owners(this.collectionId);2530 }25312532 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2533 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2534 }25352536 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2537 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2538 }25392540 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2541 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2542 }25432544 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2545 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2546 }25472548 async burnTokens(signer: TSigner, amount=1n) {2549 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2550 }25512552 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2553 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2554 }25552556 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2557 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2558 }2559}256025612562export class UniqueBaseToken {2563 collection: UniqueNFTCollection | UniqueRFTCollection;2564 collectionId: number;2565 tokenId: number;25662567 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2568 this.collection = collection;2569 this.collectionId = collection.collectionId;2570 this.tokenId = tokenId;2571 }25722573 async getNextSponsored(addressObj: ICrossAccountId) {2574 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2575 }25762577 async getProperties(propertyKeys: string[] | null = null) {2578 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2579 }25802581 async setProperties(signer: TSigner, properties: IProperty[]) {2582 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2583 }25842585 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2586 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2587 }25882589 nestingAccount() {2590 return this.collection.helper.util.getTokenAccount(this);2591 }2592}259325942595export class UniqueNFToken extends UniqueBaseToken {2596 collection: UniqueNFTCollection;25972598 constructor(tokenId: number, collection: UniqueNFTCollection) {2599 super(tokenId, collection);2600 this.collection = collection;2601 }26022603 async getData(blockHashAt?: string) {2604 return await this.collection.getToken(this.tokenId, blockHashAt);2605 }26062607 async getOwner(blockHashAt?: string) {2608 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2609 }26102611 async getTopmostOwner(blockHashAt?: string) {2612 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2613 }26142615 async getChildren(blockHashAt?: string) {2616 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2617 }26182619 async nest(signer: TSigner, toTokenObj: IToken) {2620 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2621 }26222623 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2624 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2625 }26262627 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2628 return await this.collection.transferToken(signer, this.tokenId, addressObj);2629 }26302631 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2632 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2633 }26342635 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2636 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2637 }26382639 async isApproved(toAddressObj: ICrossAccountId) {2640 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2641 }26422643 async burn(signer: TSigner) {2644 return await this.collection.burnToken(signer, this.tokenId);2645 }26462647 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2648 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2649 }2650}26512652export class UniqueRFToken extends UniqueBaseToken {2653 collection: UniqueRFTCollection;26542655 constructor(tokenId: number, collection: UniqueRFTCollection) {2656 super(tokenId, collection);2657 this.collection = collection;2658 }26592660 async getData(blockHashAt?: string) {2661 return await this.collection.getToken(this.tokenId, blockHashAt);2662 }26632664 async getTop10Owners() {2665 return await this.collection.getTop10TokenOwners(this.tokenId);2666 }26672668 async getBalance(addressObj: ICrossAccountId) {2669 return await this.collection.getTokenBalance(this.tokenId, addressObj);2670 }26712672 async getTotalPieces() {2673 return await this.collection.getTokenTotalPieces(this.tokenId);2674 }26752676 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2677 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2678 }26792680 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2681 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2682 }26832684 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2685 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2686 }26872688 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2689 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2690 }26912692 async repartition(signer: TSigner, amount: bigint) {2693 return await this.collection.repartitionToken(signer, this.tokenId, amount);2694 }26952696 async burn(signer: TSigner, amount=1n) {2697 return await this.collection.burnToken(signer, this.tokenId, amount);2698 }26992700 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2701 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2702 }2703}