difftreelog
Merge branch 'develop' into feature/app-staking
in: master
24 files changed
.docker/Dockerfile-parachain-node-onlydiffbeforeafterboth--- a/.docker/Dockerfile-parachain-node-only
+++ b/.docker/Dockerfile-parachain-node-only
@@ -27,6 +27,7 @@
RUN mkdir /unique_parachain
WORKDIR /unique_parachain
+
# ===== BUILD current version ======
FROM rust-builder as builder-unique-current
@@ -45,8 +46,6 @@
ARG PROFILE=release
ARG FEATURE=
-ARG BRANCH=
-ARG REPO_URL=
COPY . /unique_parachain
WORKDIR /unique_parachain
.github/workflows/codestyle.ymldiffbeforeafterboth--- a/.github/workflows/codestyle.yml
+++ b/.github/workflows/codestyle.yml
@@ -11,7 +11,7 @@
- ready_for_review
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
jobs:
.github/workflows/dev-build-tests.ymldiffbeforeafterboth--- a/.github/workflows/dev-build-tests.yml
+++ b/.github/workflows/dev-build-tests.yml
@@ -20,7 +20,7 @@
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
.github/workflows/forkless-update-data.ymldiffbeforeafterboth--- a/.github/workflows/forkless-update-data.yml
+++ b/.github/workflows/forkless-update-data.yml
@@ -20,7 +20,7 @@
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
.github/workflows/forkless-update-nodata.ymldiffbeforeafterboth--- a/.github/workflows/forkless-update-nodata.yml
+++ b/.github/workflows/forkless-update-nodata.yml
@@ -20,7 +20,7 @@
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
.github/workflows/nodes-only-update.ymldiffbeforeafterboth--- a/.github/workflows/nodes-only-update.yml
+++ b/.github/workflows/nodes-only-update.yml
@@ -20,7 +20,7 @@
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
@@ -142,7 +142,7 @@
node-version: 16
- name: Build the stack
- run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" up -d --build --force-recreate --timeout 300
+ run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" up -d --build --remove-orphans --force-recreate --timeout 300
# 🚀 POLKADOT LAUNCH COMPLETE 🚀
- name: Check if docker logs consist messages related to testing of Node Parachain Upgrade.
@@ -191,8 +191,8 @@
shell: bash
- name: Run tests before Node Parachain upgrade
+ working-directory: tests
run: |
- cd tests
yarn install
yarn add mochawesome
echo "Ready to start tests"
@@ -211,7 +211,7 @@
fail-on-error: 'false'
- name: Send SIGUSR1 to polkadotlaunch process
- if: success()
+ if: success() || failure()
run: |
#Get PID of polkadot-launch
PID=$(docker exec node-parachain pidof 'polkadot-launch')
@@ -266,8 +266,8 @@
shell: bash
- name: Run tests after Node Parachain upgrade
+ working-directory: tests
run: |
- cd tests
yarn install
yarn add mochawesome
echo "Ready to start tests"
@@ -288,9 +288,14 @@
- name: Stop running containers
if: always() # run this step always
- run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" down
+ run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" down --volumes
- #docker-compose rm -f
- - name: Remove Docker build artefacts
+ - name: Remove builder cache
if: always() # run this step always
- run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" rm -f
+ run: |
+ docker builder prune -f
+ docker system prune -f
+
+ - name: Clean Workspace
+ if: always()
+ uses: AutoModality/action-clean@v1.1.0
.github/workflows/tests_codestyle.ymldiffbeforeafterboth--- a/.github/workflows/tests_codestyle.yml
+++ b/.github/workflows/tests_codestyle.yml
@@ -11,7 +11,7 @@
- ready_for_review
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
jobs:
.github/workflows/try-runtime.ymldiffbeforeafterboth--- a/.github/workflows/try-runtime.yml
+++ b/.github/workflows/try-runtime.yml
@@ -20,7 +20,7 @@
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
.github/workflows/unit-test.ymldiffbeforeafterboth--- a/.github/workflows/unit-test.yml
+++ b/.github/workflows/unit-test.yml
@@ -17,7 +17,7 @@
workflow_dispatch:
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -30,6 +30,7 @@
"testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
"testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",
"testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",
+ "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
"load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
"loadTransfer": "ts-node src/transfer.nload.ts",
"testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
@@ -79,7 +80,8 @@
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
"testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
"testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
- "testEthCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createCollection.test.ts",
+ "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",
+ "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",
"testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",
"testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
"testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -15,7 +15,7 @@
import {expect} from 'chai';
import privateKey from '../substrate/privateKey';
-import { UNIQUE } from '../util/helpers';
+import {UNIQUE} from '../util/helpers';
import {
createEthAccount,
createEthAccountWithBalance,
@@ -24,7 +24,6 @@
getCollectionAddressFromResult,
itWeb3,
recordEthFee,
- subToEth,
} from './util/helpers';
describe('Add collection admins', () => {
@@ -37,7 +36,7 @@
.send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
- const newAdmin = await createEthAccount(web3);
+ const newAdmin = createEthAccount(web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
const adminList = await api.rpc.unique.adminlist(collectionId);
@@ -92,7 +91,7 @@
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
await collectionEvm.methods.addCollectionAdmin(admin).send();
- const user = await createEthAccount(web3);
+ const user = createEthAccount(web3);
await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))
.to.be.rejectedWith('NoPermission');
@@ -114,7 +113,7 @@
const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- const user = await createEthAccount(web3);
+ const user = createEthAccount(web3);
await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))
.to.be.rejectedWith('NoPermission');
@@ -175,7 +174,7 @@
.send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
- const newAdmin = await createEthAccount(web3);
+ const newAdmin = createEthAccount(web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
{
@@ -226,7 +225,7 @@
const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
await collectionEvm.methods.addCollectionAdmin(admin0).send();
- const admin1 = await createEthAccount(web3);
+ const admin1 = createEthAccount(web3);
await collectionEvm.methods.addCollectionAdmin(admin1).send();
await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))
@@ -253,7 +252,7 @@
const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
await collectionEvm.methods.addCollectionAdmin(admin).send();
- const notAdmin = await createEthAccount(web3);
+ const notAdmin = createEthAccount(web3);
await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))
.to.be.rejectedWith('NoPermission');
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,5 +1,5 @@
import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
-import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';
+import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
import {expect} from 'chai';
import {evmToAddress} from '@polkadot/util-crypto';
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -181,7 +181,7 @@
});
itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
- const owner = await createEthAccount(web3);
+ const owner = createEthAccount(web3);
const helper = evmCollectionHelpers(web3, owner);
const collectionName = 'A';
const description = 'A';
@@ -194,7 +194,7 @@
itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccount(web3);
+ const notOwner = createEthAccount(web3);
const collectionHelpers = evmCollectionHelpers(web3, owner);
const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -189,7 +189,7 @@
});
itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
- const owner = await createEthAccount(web3);
+ const owner = createEthAccount(web3);
const helper = evmCollectionHelpers(web3, owner);
const collectionName = 'A';
const description = 'A';
@@ -202,7 +202,7 @@
itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccount(web3);
+ const notOwner = createEthAccount(web3);
const collectionHelpers = evmCollectionHelpers(web3, owner);
const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -1,217 +1,220 @@
-import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
-import {expect} from 'chai';
-import Web3 from 'web3';
-import {createEthAccountWithBalance, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, tokenIdToAddress} from '../../eth/util/helpers';
-import nonFungibleAbi from '../nonFungibleAbi.json';
+import {itEth, EthUniqueHelper, usingEthPlaygrounds, expect} from '../util/playgrounds';
+
const createNestingCollection = async (
- api: ApiPromise,
- web3: Web3,
+ helper: EthUniqueHelper,
owner: string,
): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
- const collectionHelper = evmCollectionHelpers(web3, owner);
-
- const result = await collectionHelper.methods
- .createNonfungibleCollection('A', 'B', 'C')
- .send();
- const {collectionIdAddress: collectionAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
- const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionAddress, {from: owner, ...GAS_ARGS});
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await contract.methods.setCollectionNesting(true).send({from: owner});
return {collectionId, collectionAddress, contract};
};
-describe('Integration Test: EVM Nesting', () => {
- itWeb3('NFT: allows an Owner to nest/unnest their token', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const {collectionId, contract} = await createNestingCollection(api, web3, owner);
- // Create a token to be nested
- const targetNFTTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNFTTokenId,
- ).send({from: owner});
-
- const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNFTTokenId);
-
- // Create a nested token
- const firstTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- targetNftTokenAddress,
- firstTokenId,
- ).send({from: owner});
+describe('EVM nesting tests group', () => {
+ let donor: IKeyringPair;
- expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
-
- // Create a token to be nested and nest
- const secondTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- secondTokenId,
- ).send({from: owner});
-
- await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
-
- expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
-
- // Unnest token back
- await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
- expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
});
- itWeb3('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);
- const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);
- await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
- // Create a token to nest into
- const targetNftTokenId = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
- const nftTokenAddressA1 = tokenIdToAddress(collectionIdA, targetNftTokenId);
-
- // Create a token for nesting in the same collection as the target
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
-
- // Create a token for nesting in a different collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
- // Nest
- await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
- expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
-
- await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
- expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
- });
-});
-
-describe('Negative Test: EVM Nesting', async() => {
- itWeb3('NFT: disallows to nest token if nesting is disabled', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionId, contract} = await createNestingCollection(api, web3, owner);
- await contract.methods.setCollectionNesting(false).send({from: owner});
-
- // Create a token to nest into
- const targetNftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
-
- const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNftTokenId);
-
- // Create a token to nest
- const nftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- nftTokenId,
- ).send({from: owner});
-
- // Try to nest
- await expect(contract.methods
- .transfer(targetNftTokenAddress, nftTokenId)
- .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
- });
-
- itWeb3('NFT: disallows a non-Owner to nest someone else\'s token', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionId, contract} = await createNestingCollection(api, web3, owner);
-
- // Mint a token
- const targetTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetTokenId,
- ).send({from: owner});
- const targetTokenAddress = tokenIdToAddress(collectionId, targetTokenId);
-
- // Mint a token belonging to a different account
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- malignant,
- tokenId,
- ).send({from: owner});
-
- // Try to nest one token in another as a non-owner account
- await expect(contract.methods
- .transfer(targetTokenAddress, tokenId)
- .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
- });
-
- itWeb3('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);
- const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);
-
- await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
- // Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
- const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);
-
- // Create a token in another collection belonging to someone else
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- malignant,
- nftTokenIdB,
- ).send({from: owner});
-
- // Try to drag someone else's token into the other collection and nest
- await expect(contractB.methods
- .transfer(nftTokenAddressA, nftTokenIdB)
- .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ describe('Integration Test: EVM Nesting', () => {
+ itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId, contract} = await createNestingCollection(helper, owner);
+
+ // Create a token to be nested
+ const targetNFTTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ owner,
+ targetNFTTokenId,
+ ).send({from: owner});
+
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
+
+ // Create a nested token
+ const firstTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ targetNftTokenAddress,
+ firstTokenId,
+ ).send({from: owner});
+
+ expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+ // Create a token to be nested and nest
+ const secondTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ owner,
+ secondTokenId,
+ ).send({from: owner});
+
+ await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
+
+ expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+ // Unnest token back
+ await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
+ expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
+ });
+
+ itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
+ await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+
+ // Create a token to nest into
+ const targetNftTokenId = await contractA.methods.nextTokenId().call();
+ await contractA.methods.mint(
+ owner,
+ targetNftTokenId,
+ ).send({from: owner});
+ const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
+
+ // Create a token for nesting in the same collection as the target
+ const nftTokenIdA = await contractA.methods.nextTokenId().call();
+ await contractA.methods.mint(
+ owner,
+ nftTokenIdA,
+ ).send({from: owner});
+
+ // Create a token for nesting in a different collection
+ const nftTokenIdB = await contractB.methods.nextTokenId().call();
+ await contractB.methods.mint(
+ owner,
+ nftTokenIdB,
+ ).send({from: owner});
+
+ // Nest
+ await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
+ expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
+
+ await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
+ expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
+ });
});
- itWeb3('NFT: disallows to nest token in an unlisted collection', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);
- const {contract: contractB} = await createNestingCollection(api, web3, owner);
-
- await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
-
- // Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
- const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);
-
- // Create a token in another collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
- // Try to nest into a token in the other collection, disallowed in the first
- await expect(contractB.methods
- .transfer(nftTokenAddressA, nftTokenIdB)
- .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
+ describe('Negative Test: EVM Nesting', async() => {
+ itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, contract} = await createNestingCollection(helper, owner);
+ await contract.methods.setCollectionNesting(false).send({from: owner});
+
+ // Create a token to nest into
+ const targetNftTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ owner,
+ targetNftTokenId,
+ ).send({from: owner});
+
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
+
+ // Create a token to nest
+ const nftTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ owner,
+ nftTokenId,
+ ).send({from: owner});
+
+ // Try to nest
+ await expect(contract.methods
+ .transfer(targetNftTokenAddress, nftTokenId)
+ .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ });
+
+ itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const malignant = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, contract} = await createNestingCollection(helper, owner);
+
+ // Mint a token
+ const targetTokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ owner,
+ targetTokenId,
+ ).send({from: owner});
+ const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
+ // Mint a token belonging to a different account
+ const tokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(
+ malignant,
+ tokenId,
+ ).send({from: owner});
+
+ // Try to nest one token in another as a non-owner account
+ await expect(contract.methods
+ .transfer(targetTokenAddress, tokenId)
+ .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ });
+
+ itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const malignant = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
+
+ await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+
+ // Create a token in one collection
+ const nftTokenIdA = await contractA.methods.nextTokenId().call();
+ await contractA.methods.mint(
+ owner,
+ nftTokenIdA,
+ ).send({from: owner});
+ const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
+
+ // Create a token in another collection belonging to someone else
+ const nftTokenIdB = await contractB.methods.nextTokenId().call();
+ await contractB.methods.mint(
+ malignant,
+ nftTokenIdB,
+ ).send({from: owner});
+
+ // Try to drag someone else's token into the other collection and nest
+ await expect(contractB.methods
+ .transfer(nftTokenAddressA, nftTokenIdB)
+ .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ });
+
+ itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {contract: contractB} = await createNestingCollection(helper, owner);
+
+ await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
+
+ // Create a token in one collection
+ const nftTokenIdA = await contractA.methods.nextTokenId().call();
+ await contractA.methods.mint(
+ owner,
+ nftTokenIdA,
+ ).send({from: owner});
+ const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
+
+ // Create a token in another collection
+ const nftTokenIdB = await contractB.methods.nextTokenId().call();
+ await contractB.methods.mint(
+ owner,
+ nftTokenIdB,
+ ).send({from: owner});
+
+ // Try to nest into a token in the other collection, disallowed in the first
+ await expect(contractB.methods
+ .transfer(nftTokenAddressA, nftTokenIdB)
+ .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
+ });
});
});
tests/src/eth/payable.test.tsdiffbeforeafterboth--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -14,97 +14,91 @@
// 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 {expect} from 'chai';
-import {submitTransactionAsync} from '../substrate/substrate-api';
-import {createEthAccountWithBalance, deployCollector, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
-import {evmToAddress} from '@polkadot/util-crypto';
-import {getGenericResult, UNIQUE} from '../util/helpers';
-import {getBalanceSingle, transferBalanceExpectSuccess} from '../substrate/get-balance';
+import {IKeyringPair} from '@polkadot/types/types';
+
+import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';
describe('EVM payable contracts', () => {
- itWeb3('Evm contract can receive wei from eth account', async ({api, web3, privateKeyWrapper}) => {
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contract = await deployCollector(web3, deployer);
+ let donor: IKeyringPair;
- await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', ...GAS_ARGS});
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Evm contract can receive wei from eth account', async ({helper}) => {
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const contract = await helper.eth.deployCollectorContract(deployer);
+
+ const web3 = helper.getWeb3();
+
+ await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', gas: helper.eth.DEFAULT_GAS});
expect(await contract.methods.getCollected().call()).to.be.equal('10000');
});
- itWeb3('Evm contract can receive wei from substrate account', async ({api, web3, privateKeyWrapper}) => {
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contract = await deployCollector(web3, deployer);
- const alice = privateKeyWrapper('//Alice');
+ itEth('Evm contract can receive wei from substrate account', async ({helper}) => {
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const contract = await helper.eth.deployCollectorContract(deployer);
+ const [alice] = await helper.arrange.createAccounts([10n], donor);
+
+ const weiCount = '10000';
// Transaction fee/value will be payed from subToEth(sender) evm balance,
// which is backed by evmToAddress(subToEth(sender)) substrate balance
- await transferBalanceToEth(api, alice, subToEth(alice.address));
+ await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);
+
- {
- const tx = api.tx.evm.call(
- subToEth(alice.address),
- contract.options.address,
- contract.methods.giveMoney().encodeABI(),
- '10000',
- GAS_ARGS.gas,
- await web3.eth.getGasPrice(),
- null,
- null,
- [],
- );
- const events = await submitTransactionAsync(alice, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
- }
+ await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
- expect(await contract.methods.getCollected().call()).to.be.equal('10000');
+ expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);
});
// We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible
- itWeb3('Wei sent directly to backing storage of evm contract balance is unaccounted', async({api, web3, privateKeyWrapper}) => {
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contract = await deployCollector(web3, deployer);
- const alice = privateKeyWrapper('//Alice');
+ itEth('Wei sent directly to backing storage of evm contract balance is unaccounted', async({helper}) => {
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const contract = await helper.eth.deployCollectorContract(deployer);
+ const [alice] = await helper.arrange.createAccounts([10n], donor);
+
+ const weiCount = 10_000n;
- await transferBalanceExpectSuccess(api, alice, evmToAddress(contract.options.address), '10000');
+ await helper.eth.transferBalanceFromSubstrate(alice, contract.options.address, weiCount, false);
- expect(await contract.methods.getUnaccounted().call()).to.be.equal('10000');
+ expect(await contract.methods.getUnaccounted().call()).to.be.equal(weiCount.toString());
});
- itWeb3('Balance can be retrieved from evm contract', async({api, web3, privateKeyWrapper}) => {
- const FEE_BALANCE = 1000n * UNIQUE;
- const CONTRACT_BALANCE = 1n * UNIQUE;
+ itEth('Balance can be retrieved from evm contract', async({helper, privateKey}) => {
+ const FEE_BALANCE = 10n * helper.balance.getOneTokenNominal();
+ const CONTRACT_BALANCE = 1n * helper.balance.getOneTokenNominal();
+
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const contract = await helper.eth.deployCollectorContract(deployer);
+ const [alice] = await helper.arrange.createAccounts([20n], donor);
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contract = await deployCollector(web3, deployer);
- const alice = privateKeyWrapper('//Alice');
+ const web3 = helper.getWeb3();
- await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), ...GAS_ARGS});
+ await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
- const receiver = privateKeyWrapper(`//Receiver${Date.now()}`);
+ const receiver = privateKey(`//Receiver${Date.now()}`);
// First receive balance on eth balance of bob
{
- const ethReceiver = subToEth(receiver.address);
+ const ethReceiver = helper.address.substrateToEth(receiver.address);
expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');
await contract.methods.withdraw(ethReceiver).send({from: deployer});
expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());
}
// Some balance is required to pay fee for evm.withdraw call
- await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());
+ await helper.balance.transferToSubstrate(alice, receiver.address, FEE_BALANCE);
+ // await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());
// Withdraw balance from eth to substrate
{
- const initialReceiverBalance = await getBalanceSingle(api, receiver.address);
- const tx = api.tx.evm.withdraw(
- subToEth(receiver.address),
- CONTRACT_BALANCE.toString(),
- );
- const events = await submitTransactionAsync(receiver, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
- const finalReceiverBalance = await getBalanceSingle(api, receiver.address);
+ const initialReceiverBalance = await helper.balance.getSubstrate(receiver.address);
+ await helper.executeExtrinsic(receiver, 'api.tx.evm.withdraw', [helper.address.substrateToEth(receiver.address), CONTRACT_BALANCE.toString()], true);
+ const finalReceiverBalance = await helper.balance.getSubstrate(receiver.address);
expect(finalReceiverBalance > initialReceiverBalance).to.be.true;
}
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -0,0 +1,49 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+import {IKeyringPair} from '@polkadot/types/types';
+
+import config from '../../../config';
+
+import {EthUniqueHelper} from './unique.dev';
+import {SilentLogger, SilentConsole} from '../../../util/playgrounds/unique.dev';
+
+export {EthUniqueHelper} from './unique.dev';
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+chai.use(chaiAsPromised);
+export const expect = chai.expect;
+
+export const usingEthPlaygrounds = async (code: (helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
+ const silentConsole = new SilentConsole();
+ silentConsole.enable();
+
+ const helper = new EthUniqueHelper(new SilentLogger());
+
+ try {
+ await helper.connect(config.substrateUrl);
+ await helper.connectWeb3(config.substrateUrl);
+ const ss58Format = helper.chain.getChainProperties().ss58Format;
+ const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);
+ await code(helper, privateKey);
+ }
+ finally {
+ await helper.disconnect();
+ await helper.disconnectWeb3();
+ silentConsole.disable();
+ }
+};
+
+export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+ let i: any = it;
+ if (opts.only) i = i.only;
+ else if (opts.skip) i = i.skip;
+ i(name, async () => {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ await cb({helper, privateKey});
+ });
+ });
+}
+itEth.only = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {only: true});
+itEth.skip = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {skip: true});
\ No newline at end of file
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -0,0 +1,9 @@
+export interface ContractImports {
+ solPath: string;
+ fsPath: string;
+}
+
+export interface CompiledContract {
+ abi: any;
+ object: string;
+}
\ No newline at end of file
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -0,0 +1,268 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+/* eslint-disable function-call-argument-newline */
+
+import {readFile} from 'fs/promises';
+
+import Web3 from 'web3';
+import {WebsocketProvider} from 'web3-core';
+import {Contract} from 'web3-eth-contract';
+
+import * as solc from 'solc';
+
+import {evmToAddress} from '@polkadot/util-crypto';
+import {IKeyringPair} from '@polkadot/types/types';
+
+import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
+
+import {ContractImports, CompiledContract} from './types';
+
+// Native contracts ABI
+import collectionHelpersAbi from '../../collectionHelpersAbi.json';
+import fungibleAbi from '../../fungibleAbi.json';
+import nonFungibleAbi from '../../nonFungibleAbi.json';
+import refungibleAbi from '../../reFungibleAbi.json';
+import refungibleTokenAbi from '../../reFungibleTokenAbi.json';
+import contractHelpersAbi from './../contractHelpersAbi.json';
+
+class EthGroupBase {
+ helper: EthUniqueHelper;
+
+ constructor(helper: EthUniqueHelper) {
+ this.helper = helper;
+ }
+}
+
+
+class ContractGroup extends EthGroupBase {
+ async findImports(imports?: ContractImports[]){
+ if(!imports) return function(path: string) {
+ return {error: `File not found: ${path}`};
+ };
+
+ const knownImports = {} as any;
+ for(const imp of imports) {
+ knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
+ }
+
+ return function(path: string) {
+ if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};
+ return {error: `File not found: ${path}`};
+ };
+ }
+
+ async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {
+ const out = JSON.parse(solc.compile(JSON.stringify({
+ language: 'Solidity',
+ sources: {
+ [`${name}.sol`]: {
+ content: src,
+ },
+ },
+ settings: {
+ outputSelection: {
+ '*': {
+ '*': ['*'],
+ },
+ },
+ },
+ }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
+
+ return {
+ abi: out.abi,
+ object: '0x' + out.evm.bytecode.object,
+ };
+ }
+
+ async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {
+ const compiledContract = await this.compile(name, src, imports);
+ return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);
+ }
+
+ async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {
+ const web3 = this.helper.getWeb3();
+ const contract = new web3.eth.Contract(abi, undefined, {
+ data: object,
+ from: signer,
+ gas: this.helper.eth.DEFAULT_GAS,
+ });
+ return await contract.deploy({data: object}).send({from: signer});
+ }
+
+}
+
+class NativeContractGroup extends EthGroupBase {
+
+ contractHelpers(caller: string): Contract {
+ const web3 = this.helper.getWeb3();
+ return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
+ }
+
+ collectionHelpers(caller: string) {
+ const web3 = this.helper.getWeb3();
+ return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
+ }
+
+ collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {
+ const abi = {
+ 'nft': nonFungibleAbi,
+ 'rft': refungibleAbi,
+ 'ft': fungibleAbi,
+ }[mode];
+ const web3 = this.helper.getWeb3();
+ return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
+ }
+
+ rftTokenByAddress(address: string, caller?: string): Contract {
+ const web3 = this.helper.getWeb3();
+ return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
+ }
+
+ rftToken(collectionId: number, tokenId: number, caller?: string): Contract {
+ return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);
+ }
+}
+
+
+class EthGroup extends EthGroupBase {
+ DEFAULT_GAS = 2_500_000;
+
+ createAccount() {
+ const web3 = this.helper.getWeb3();
+ const account = web3.eth.accounts.create();
+ web3.eth.accounts.wallet.add(account.privateKey);
+ return account.address;
+ }
+
+ async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {
+ const account = this.createAccount();
+ await this.transferBalanceFromSubstrate(donor, account, amount);
+
+ return account;
+ }
+
+ async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {
+ return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
+ }
+
+ async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {
+ if(!gasLimit) gasLimit = this.DEFAULT_GAS;
+ const web3 = this.helper.getWeb3();
+ const gasPrice = await web3.eth.getGasPrice();
+ // TODO: check execution status
+ await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],
+ true,
+ );
+ }
+
+ async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();
+
+ const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
+
+ return {collectionId, collectionAddress};
+ }
+
+ async deployCollectorContract(signer: string): Promise<Contract> {
+ return await this.helper.ethContract.deployByCode(signer, 'Collector', `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ contract Collector {
+ uint256 collected;
+ fallback() external payable {
+ giveMoney();
+ }
+ function giveMoney() public payable {
+ collected += msg.value;
+ }
+ function getCollected() public view returns (uint256) {
+ return collected;
+ }
+ function getUnaccounted() public view returns (uint256) {
+ return address(this).balance - collected;
+ }
+
+ function withdraw(address payable target) public {
+ target.transfer(collected);
+ collected = 0;
+ }
+ }
+ `);
+ }
+}
+
+
+class EthAddressGroup extends EthGroupBase {
+ extractCollectionId(address: string): number {
+ if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');
+ return parseInt(address.substr(address.length - 8), 16);
+ }
+
+ fromCollectionId(collectionId: number): string {
+ if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');
+ return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);
+ }
+
+ extractTokenId(address: string): {collectionId: number, tokenId: number} {
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return {
+ collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
+ tokenId: Number('0x' + address.substring(address.length - 8)),
+ };
+ }
+
+ fromTokenId(collectionId: number, tokenId: number): string {
+ return this.helper.util.getNestingTokenAddress(collectionId, tokenId);
+ }
+
+ normalizeAddress(address: string): string {
+ return '0x' + address.substring(address.length - 40);
+ }
+}
+
+
+export class EthUniqueHelper extends DevUniqueHelper {
+ web3: Web3 | null = null;
+ web3Provider: WebsocketProvider | null = null;
+
+ eth: EthGroup;
+ ethAddress: EthAddressGroup;
+ ethNativeContract: NativeContractGroup;
+ ethContract: ContractGroup;
+
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
+ super(logger);
+ this.eth = new EthGroup(this);
+ this.ethAddress = new EthAddressGroup(this);
+ this.ethNativeContract = new NativeContractGroup(this);
+ this.ethContract = new ContractGroup(this);
+ }
+
+ getWeb3(): Web3 {
+ if(this.web3 === null) throw Error('Web3 not connected');
+ return this.web3;
+ }
+
+ async connectWeb3(wsEndpoint: string) {
+ if(this.web3 !== null) return;
+ this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);
+ this.web3 = new Web3(this.web3Provider);
+ }
+
+ async disconnectWeb3() {
+ if(this.web3 === null) return;
+ this.web3Provider?.connection.close();
+ this.web3 = null;
+ }
+}
+
\ No newline at end of file
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -25,6 +25,8 @@
import privateKey from './privateKey';
import promisifySubstrate from './promisify-substrate';
+import {SilentConsole} from '../util/playgrounds/unique.dev';
+
function defaultApiOptions(): ApiOptions {
@@ -75,26 +77,9 @@
settings = settings || defaultApiOptions();
const api: ApiPromise = new ApiPromise(settings);
let result: T = null as unknown as T;
-
- // TODO: Remove, this is temporary: Filter unneeded API output
- // (Jaco promised it will be removed in the next version)
- const consoleErr = console.error;
- const consoleLog = console.log;
- const consoleWarn = console.warn;
- const outFn = (printer: any) => (...args: any[]) => {
- for (const arg of args) {
- if (typeof arg !== 'string')
- continue;
- if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
- return;
- }
- printer(...args);
- };
-
- console.error = outFn(consoleErr.bind(console));
- console.log = outFn(consoleLog.bind(console));
- console.warn = outFn(consoleWarn.bind(console));
+ const silentConsole = new SilentConsole();
+ silentConsole.enable();
try {
await promisifySubstrate(api, async () => {
@@ -107,9 +92,7 @@
})();
} finally {
await api.disconnect();
- console.error = consoleErr;
- console.log = consoleLog;
- console.warn = consoleWarn;
+ silentConsole.disable();
}
return result as T;
}
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -4,55 +4,23 @@
import {IKeyringPair} from '@polkadot/types/types';
import config from '../../config';
import '../../interfaces/augment-api-events';
-import {DevUniqueHelper} from './unique.dev';
-
-
-class SilentLogger {
- log(msg: any, level: any): void { }
- level = {
- ERROR: 'ERROR' as const,
- WARNING: 'WARNING' as const,
- INFO: 'INFO' as const,
- };
-}
-
-
+import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
-export const usingPlaygrounds = async <T = void> (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<T>) => {
- // TODO: Remove, this is temporary: Filter unneeded API output
- // (Jaco promised it will be removed in the next version)
- const consoleErr = console.error;
- const consoleLog = console.log;
- const consoleWarn = console.warn;
- let result: T = null as unknown as T;
-
- const outFn = (printer: any) => (...args: any[]) => {
- for (const arg of args) {
- if (typeof arg !== 'string')
- continue;
- if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
- return;
- }
- printer(...args);
- };
+export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
+ const silentConsole = new SilentConsole();
+ silentConsole.enable();
- console.error = outFn(consoleErr.bind(console));
- console.log = outFn(consoleLog.bind(console));
- console.warn = outFn(consoleWarn.bind(console));
const helper = new DevUniqueHelper(new SilentLogger());
try {
await helper.connect(config.substrateUrl);
const ss58Format = helper.chain.getChainProperties().ss58Format;
const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);
- result = await code(helper, privateKey);
+ await code(helper, privateKey);
}
finally {
await helper.disconnect();
- console.error = consoleErr;
- console.log = consoleLog;
- console.warn = consoleWarn;
+ silentConsole.disable();
}
- return result as T;
-};
\ No newline at end of file
+};
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -8,6 +8,53 @@
import {IKeyringPair} from '@polkadot/types/types';
+export class SilentLogger {
+ log(_msg: any, _level: any): void { }
+ level = {
+ ERROR: 'ERROR' as const,
+ WARNING: 'WARNING' as const,
+ INFO: 'INFO' as const,
+ };
+}
+
+
+export class SilentConsole {
+ // TODO: Remove, this is temporary: Filter unneeded API output
+ // (Jaco promised it will be removed in the next version)
+ consoleErr: any;
+ consoleLog: any;
+ consoleWarn: any;
+
+ constructor() {
+ this.consoleErr = console.error;
+ this.consoleLog = console.log;
+ this.consoleWarn = console.warn;
+ }
+
+ enable() {
+ const outFn = (printer: any) => (...args: any[]) => {
+ for (const arg of args) {
+ if (typeof arg !== 'string')
+ continue;
+ if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
+ return;
+ }
+ printer(...args);
+ };
+
+ console.error = outFn(this.consoleErr.bind(console));
+ console.log = outFn(this.consoleLog.bind(console));
+ console.warn = outFn(this.consoleWarn.bind(console));
+ }
+
+ disable() {
+ console.error = this.consoleErr;
+ console.log = this.consoleLog;
+ console.warn = this.consoleWarn;
+ }
+}
+
+
export class DevUniqueHelper extends UniqueHelper {
/**
* Arrange methods for tests
@@ -19,7 +66,7 @@
this.arrange = new ArrangeGroup(this);
}
- async connect(wsEndpoint: string, listeners?: any): Promise<void> {
+ async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
const wsProvider = new WsProvider(wsEndpoint);
this.api = new ApiPromise({
provider: wsProvider,
@@ -85,7 +132,7 @@
}
}
- await Promise.all(transactions).catch(e => {});
+ await Promise.all(transactions).catch(_e => {});
//#region TODO remove this region, when nonce problem will be solved
const checkBalances = async () => {
@@ -186,6 +233,7 @@
* @returns
*/
async waitNewBlocks(blocksCount = 1): Promise<void> {
+ // eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
if (blocksCount > 0) {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 /**455 * Get number of blocks when sponsored transaction is available.456 *457 * @param collectionId ID of collection458 * @param tokenId ID of token459 * @param addressObj address for which the sponsorship is checked460 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});461 * @returns number of blocks or null if sponsorship hasn't been set462 */463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 /**468 * Get the number of created collections.469 * 470 * @returns number of created collections471 */472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 /**477 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.478 * 479 * @param collectionId ID of collection480 * @example await getData(2)481 * @returns collection information object482 */483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 /**512 * Get the normalized addresses of the collection's administrators.513 * 514 * @param collectionId ID of collection515 * @example await getAdmins(1)516 * @returns array of administrators517 */518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 /**528 * Get the normalized addresses added to the collection allow-list.529 * @param collectionId ID of collection530 * @example await getAllowList(1)531 * @returns array of allow-listed addresses532 */533 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {534 const normalized = [];535 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();536 for (const address of allowListed) {537 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});538 else normalized.push(address);539 }540 return normalized;541 }542543 /**544 * Get the effective limits of the collection instead of null for default values545 * 546 * @param collectionId ID of collection547 * @example await getEffectiveLimits(2)548 * @returns object of collection limits549 */550 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {551 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();552 }553554 /**555 * Burns the collection if the signer has sufficient permissions and collection is empty.556 * 557 * @param signer keyring of signer558 * @param collectionId ID of collection559 * @param label extra label for log560 * @example await helper.collection.burn(aliceKeyring, 3);561 * @returns ```true``` if extrinsic success, otherwise ```false```562 */563 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {564 if(typeof label === 'undefined') label = `collection #${collectionId}`;565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true, `Unable to burn collection for ${label}`,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);572 }573574 /**575 * Sets the sponsor for the collection (Requires the Substrate address).576 * 577 * @param signer keyring of signer578 * @param collectionId ID of collection579 * @param sponsorAddress Sponsor substrate address580 * @param label extra label for log581 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")582 * @returns ```true``` if extrinsic success, otherwise ```false```583 */584 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {585 if(typeof label === 'undefined') label = `collection #${collectionId}`;586 const result = await this.helper.executeExtrinsic(587 signer,588 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],589 true, `Unable to set collection sponsor for ${label}`,590 );591592 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);593 }594595 /**596 * Confirms consent to sponsor the collection on behalf of the signer.597 * 598 * @param signer keyring of signer599 * @param collectionId ID of collection600 * @param label extra label for log601 * @example confirmSponsorship(aliceKeyring, 10)602 * @returns ```true``` if extrinsic success, otherwise ```false```603 */604 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {605 if(typeof label === 'undefined') label = `collection #${collectionId}`;606 const result = await this.helper.executeExtrinsic(607 signer,608 'api.tx.unique.confirmSponsorship', [collectionId],609 true, `Unable to confirm collection sponsorship for ${label}`,610 );611612 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);613 }614615 /**616 * Sets the limits of the collection. At least one limit must be specified for a correct call.617 * 618 * @param signer keyring of signer619 * @param collectionId ID of collection620 * @param limits collection limits object621 * @param label extra label for log622 * @example623 * await setLimits(624 * aliceKeyring,625 * 10,626 * {627 * sponsorTransferTimeout: 0,628 * ownerCanDestroy: false629 * }630 * )631 * @returns ```true``` if extrinsic success, otherwise ```false```632 */633 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {634 if(typeof label === 'undefined') label = `collection #${collectionId}`;635 const result = await this.helper.executeExtrinsic(636 signer,637 'api.tx.unique.setCollectionLimits', [collectionId, limits],638 true, `Unable to set collection limits for ${label}`,639 );640641 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);642 }643644 /**645 * Changes the owner of the collection to the new Substrate address.646 * 647 * @param signer keyring of signer648 * @param collectionId ID of collection649 * @param ownerAddress substrate address of new owner650 * @param label extra label for log651 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")652 * @returns ```true``` if extrinsic success, otherwise ```false```653 */654 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {655 if(typeof label === 'undefined') label = `collection #${collectionId}`;656 const result = await this.helper.executeExtrinsic(657 signer,658 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],659 true, `Unable to change collection owner for ${label}`,660 );661662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);663 }664665 /**666 * Adds a collection administrator. 667 * 668 * @param signer keyring of signer669 * @param collectionId ID of collection670 * @param adminAddressObj Administrator address (substrate or ethereum)671 * @param label extra label for log672 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})673 * @returns ```true``` if extrinsic success, otherwise ```false```674 */675 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {676 if(typeof label === 'undefined') label = `collection #${collectionId}`;677 const result = await this.helper.executeExtrinsic(678 signer,679 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],680 true, `Unable to add collection admin for ${label}`,681 );682683 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);684 }685686 /**687 * Adds an address to allow list 688 * @param signer keyring of signer689 * @param collectionId ID of collection690 * @param addressObj address to add to the allow list691 * @param label extra label for log692 * @returns ```true``` if extrinsic success, otherwise ```false```693 */694 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {695 if(typeof label === 'undefined') label = `collection #${collectionId}`;696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.addToAllowList', [collectionId, addressObj],699 true, `Unable to add address to allow list for ${label}`,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');703 }704705 /**706 * Removes a collection administrator.707 * 708 * @param signer keyring of signer709 * @param collectionId ID of collection710 * @param adminAddressObj Administrator address (substrate or ethereum)711 * @param label extra label for log712 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})713 * @returns ```true``` if extrinsic success, otherwise ```false```714 */715 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {716 if(typeof label === 'undefined') label = `collection #${collectionId}`;717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],720 true, `Unable to remove collection admin for ${label}`,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);724 }725726 /**727 * Sets onchain permissions for selected collection.728 * 729 * @param signer keyring of signer730 * @param collectionId ID of collection731 * @param permissions collection permissions object732 * @param label extra label for log733 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});734 * @returns ```true``` if extrinsic success, otherwise ```false```735 */736 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {737 if(typeof label === 'undefined') label = `collection #${collectionId}`;738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],741 true, `Unable to set collection permissions for ${label}`,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);745 }746747 /**748 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.749 * 750 * @param signer keyring of signer751 * @param collectionId ID of collection752 * @param permissions nesting permissions object753 * @param label extra label for log754 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});755 * @returns ```true``` if extrinsic success, otherwise ```false```756 */757 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {758 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);759 }760761 /**762 * Disables nesting for selected collection.763 * 764 * @param signer keyring of signer765 * @param collectionId ID of collection766 * @param label extra label for log767 * @example disableNesting(aliceKeyring, 10);768 * @returns ```true``` if extrinsic success, otherwise ```false```769 */770 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);772 }773774 /**775 * Sets onchain properties to the collection.776 * 777 * @param signer keyring of signer778 * @param collectionId ID of collection779 * @param properties array of property objects780 * @param label extra label for log781 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);782 * @returns ```true``` if extrinsic success, otherwise ```false```783 */784 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {785 if(typeof label === 'undefined') label = `collection #${collectionId}`;786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionProperties', [collectionId, properties],789 true, `Unable to set collection properties for ${label}`,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);793 }794795 /**796 * Deletes onchain properties from the collection.797 * 798 * @param signer keyring of signer799 * @param collectionId ID of collection800 * @param propertyKeys array of property keys to delete801 * @param label802 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);803 * @returns ```true``` if extrinsic success, otherwise ```false```804 */805 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {806 if(typeof label === 'undefined') label = `collection #${collectionId}`;807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],810 true, `Unable to delete collection properties for ${label}`,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);814 }815816 /**817 * Changes the owner of the token.818 * 819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @param tokenId ID of token822 * @param addressObj address of a new owner823 * @param amount amount of tokens to be transfered. For NFT must be set to 1n824 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})825 * @returns true if the token success, otherwise false826 */827 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],831 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,832 );833834 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);835 }836837 /**838 * 839 * Change ownership of a token(s) on behalf of the owner. 840 * 841 * @param signer keyring of signer842 * @param collectionId ID of collection843 * @param tokenId ID of token844 * @param fromAddressObj address on behalf of which the token will be sent845 * @param toAddressObj new token owner846 * @param amount amount of tokens to be transfered. For NFT must be set to 1n847 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})848 * @returns true if the token success, otherwise false849 */850 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {851 const result = await this.helper.executeExtrinsic(852 signer,853 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],854 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,855 );856 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);857 }858859 /**860 * 861 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.862 * 863 * @param signer keyring of signer864 * @param collectionId ID of collection865 * @param tokenId ID of token866 * @param label 867 * @param amount amount of tokens to be burned. For NFT must be set to 1n868 * @example burnToken(aliceKeyring, 10, 5);869 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```870 */871 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{872 success: boolean,873 token: number | null874 }> {875 if(typeof label === 'undefined') label = `collection #${collectionId}`;876 const burnResult = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.burnItem', [collectionId, tokenId, amount],879 true, `Unable to burn token for ${label}`,880 );881 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);882 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');883 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};884 }885886 /**887 * Destroys a concrete instance of NFT on behalf of the owner888 * 889 * @param signer keyring of signer890 * @param collectionId ID of collection891 * @param fromAddressObj address on behalf of which the token will be burnt892 * @param tokenId ID of token893 * @param label 894 * @param amount amount of tokens to be burned. For NFT must be set to 1n895 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {899 if(typeof label === 'undefined') label = `collection #${collectionId}`;900 const burnResult = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],903 true, `Unable to burn token from for ${label}`,904 );905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);906 return burnedTokens.success && burnedTokens.tokens.length > 0;907 }908909 /**910 * Set, change, or remove approved address to transfer the ownership of the NFT.911 * 912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param tokenId ID of token915 * @param toAddressObj 916 * @param label 917 * @param amount amount of token to be approved. For NFT must be set to 1n918 * @returns ```true``` if extrinsic success, otherwise ```false```919 */920 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {921 if(typeof label === 'undefined') label = `collection #${collectionId}`;922 const approveResult = await this.helper.executeExtrinsic(923 signer, 924 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],925 true, `Unable to approve token for ${label}`,926 );927928 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);929 }930931 /**932 * Get the amount of token pieces approved to transfer933 * @param collectionId ID of collection934 * @param tokenId ID of token935 * @param toAccountObj 936 * @param fromAccountObj937 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})938 * @returns number of approved to transfer pieces939 */940 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {941 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();942 }943944 /**945 * Get the last created token id946 * @param collectionId ID of collection947 * @example getLastTokenId(10);948 * @returns id of the last created token949 */950 async getLastTokenId(collectionId: number): Promise<number> {951 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();952 }953954 /**955 * Check if token exists956 * @param collectionId ID of collection957 * @param tokenId ID of token958 * @example isTokenExists(10, 20);959 * @returns true if the token exists, otherwise false960 */961 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {962 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();963 }964}965966class NFTnRFT extends CollectionGroup {967 /**968 * Get tokens owned by account969 * 970 * @param collectionId ID of collection971 * @param addressObj tokens owner972 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})973 * @returns array of token ids owned by account974 */975 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {976 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();977 }978979 /**980 * Get token data981 * @param collectionId ID of collection982 * @param tokenId ID of token983 * @param blockHashAt 984 * @param propertyKeys985 * @example getToken(10, 5);986 * @returns human readable token data 987 */988 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{989 properties: IProperty[];990 owner: ICrossAccountId;991 normalizedOwner: ICrossAccountId;992 }| null> {993 let tokenData;994 if(typeof blockHashAt === 'undefined') {995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);996 }997 else {998 if(typeof propertyKeys === 'undefined') {999 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1000 if(!collection) return null;1001 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1002 }1003 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1004 }1005 tokenData = tokenData.toHuman();1006 if (tokenData === null || tokenData.owner === null) return null;1007 const owner = {} as any;1008 for (const key of Object.keys(tokenData.owner)) {1009 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1010 }1011 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1012 return tokenData;1013 }10141015 /**1016 * Set permissions to change token properties1017 * @param signer keyring of signer1018 * @param collectionId ID of collection1019 * @param permissions permissions to change a property by the collection owner or admin1020 * @param label 1021 * @example setTokenPropertyPermissions(1022 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1023 * )1024 * @returns true if extrinsic success otherwise false1025 */1026 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1027 if(typeof label === 'undefined') label = `collection #${collectionId}`;1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1031 true, `Unable to set token property permissions for ${label}`,1032 );10331034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1035 }10361037 /**1038 * Set token properties1039 * @param signer keyring of signer1040 * @param collectionId ID of collection1041 * @param tokenId ID of token1042 * @param properties 1043 * @param label 1044 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1048 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1049 const result = await this.helper.executeExtrinsic(1050 signer,1051 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1052 true, `Unable to set token properties for ${label}`,1053 );10541055 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1056 }10571058 /**1059 * Delete the provided properties of a token1060 * @param signer keyring of signer1061 * @param collectionId ID of collection1062 * @param tokenId ID of token1063 * @param propertyKeys property keys to be deleted 1064 * @param label 1065 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1069 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1070 const result = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1073 true, `Unable to delete token properties for ${label}`,1074 );10751076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1077 }10781079 /**1080 * Mint new collection1081 * @param signer keyring of signer1082 * @param collectionOptions basic collection options and properties 1083 * @param mode NFT or RFT type of a collection1084 * @param errorLabel 1085 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1086 * @returns object of the created collection1087 */1088 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1089 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1090 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1091 for (const key of ['name', 'description', 'tokenPrefix']) {1092 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);1093 }1094 const creationResult = await this.helper.executeExtrinsic(1095 signer,1096 'api.tx.unique.createCollectionEx', [collectionOptions],1097 true, errorLabel,1098 );1099 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1100 }11011102 getCollectionObject(collectionId: number): any {1103 return null;1104 }11051106 getTokenObject(collectionId: number, tokenId: number): any {1107 return null;1108 }1109}111011111112class NFTGroup extends NFTnRFT {1113 /**1114 * Get collection object1115 * @param collectionId ID of collection1116 * @example getCollectionObject(2);1117 * @returns instance of UniqueNFTCollection1118 */1119 getCollectionObject(collectionId: number): UniqueNFTCollection {1120 return new UniqueNFTCollection(collectionId, this.helper);1121 }11221123 /**1124 * Get token object1125 * @param collectionId ID of collection1126 * @param tokenId ID of token1127 * @example getTokenObject(10, 5);1128 * @returns instance of UniqueNFTToken1129 */1130 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1131 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1132 }11331134 /**1135 * Get token's owner1136 * @param collectionId ID of collection1137 * @param tokenId ID of token1138 * @param blockHashAt 1139 * @example getTokenOwner(10, 5);1140 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1141 */1142 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1143 let owner;1144 if (typeof blockHashAt === 'undefined') {1145 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1146 } else {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1148 }1149 return crossAccountIdFromLower(owner.toJSON());1150 }11511152 /**1153 * Is token approved to transfer1154 * @param collectionId ID of collection1155 * @param tokenId ID of token1156 * @param toAccountObj address to be approved1157 * @returns ```true``` if extrinsic success, otherwise ```false```1158 */1159 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1160 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1161 }11621163 /**1164 * Changes the owner of the token.1165 * 1166 * @param signer keyring of signer1167 * @param collectionId ID of collection1168 * @param tokenId ID of token1169 * @param addressObj address of a new owner1170 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171 * @returns ```true``` if extrinsic success, otherwise ```false```1172 */1173 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1174 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1175 }11761177 /**1178 * 1179 * Change ownership of a NFT on behalf of the owner. 1180 * 1181 * @param signer keyring of signer1182 * @param collectionId ID of collection1183 * @param tokenId ID of token1184 * @param fromAddressObj address on behalf of which the token will be sent1185 * @param toAddressObj new token owner1186 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1187 * @returns ```true``` if extrinsic success, otherwise ```false```1188 */1189 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1190 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1191 }11921193 /**1194 * Recursively find the address that owns the token1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param blockHashAt 1198 * @example getTokenTopmostOwner(10, 5);1199 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1200 */1201 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1202 let owner;1203 if (typeof blockHashAt === 'undefined') {1204 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1205 } else {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1207 }12081209 if (owner === null) return null;12101211 owner = owner.toHuman();12121213 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1214 }12151216 /**1217 * Get tokens nested in the provided token1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param blockHashAt 1221 * @example getTokenChildren(10, 5);1222 * @returns tokens whose depth of nesting is <= 5 1223 */1224 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1225 let children;1226 if(typeof blockHashAt === 'undefined') {1227 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1228 } else {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1230 }12311232 return children.toJSON().map((x: any) => {1233 return {collectionId: x.collection, tokenId: x.token};1234 });1235 }12361237 /**1238 * Nest one token into another1239 * @param signer keyring of signer1240 * @param tokenObj token to be nested1241 * @param rootTokenObj token to be parent1242 * @param label 1243 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1244 * @returns ```true``` if extrinsic success, otherwise ```false```1245 */1246 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1247 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1248 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1249 if(!result) {1250 throw Error(`Unable to nest token for ${label}`);1251 }1252 return result;1253 }12541255 /**1256 * Remove token from nested state1257 * @param signer keyring of signer1258 * @param tokenObj token to unnest1259 * @param rootTokenObj parent of a token1260 * @param toAddressObj address of a new token owner 1261 * @param label 1262 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1263 * @returns ```true``` if extrinsic success, otherwise ```false```1264 */1265 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1266 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1267 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1268 if(!result) {1269 throw Error(`Unable to unnest token for ${label}`);1270 }1271 return result;1272 }12731274 /**1275 * Mint new collection1276 * @param signer keyring of signer1277 * @param collectionOptions Collection options1278 * @param label 1279 * @example 1280 * mintCollection(aliceKeyring, {1281 * name: 'New',1282 * description: 'New collection',1283 * tokenPrefix: 'NEW',1284 * })1285 * @returns object of the created collection1286 */1287 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1288 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1289 }12901291 /**1292 * Mint new token1293 * @param signer keyring of signer1294 * @param data token data1295 * @param label 1296 * @returns created token object1297 */1298 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1299 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1303 nft: {1304 properties: data.properties,1305 },1306 }],1307 true, `Unable to mint NFT token for ${label}`,1308 );1309 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1310 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1311 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1312 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1313 }13141315 /**1316 * Mint multiple NFT tokens1317 * @param signer keyring of signer1318 * @param collectionId ID of collection1319 * @param tokens array of tokens with owner and properties1320 * @param label 1321 * @example 1322 * mintMultipleTokens(aliceKeyring, 10, [{1323 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1324 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1325 * },{1326 * owner: {Ethereum: "0x9F0583DbB855d..."},1327 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1328 * }]);1329 * @returns ```true``` if extrinsic success, otherwise ```false```1330 */1331 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1332 if(typeof label === 'undefined') label = `collection #${collectionId}`;1333 const creationResult = await this.helper.executeExtrinsic(1334 signer,1335 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1336 true, `Unable to mint NFT tokens for ${label}`,1337 );1338 const collection = this.getCollectionObject(collectionId);1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1340 }13411342 /**1343 * Mint multiple NFT tokens with one owner1344 * @param signer keyring of signer1345 * @param collectionId ID of collection1346 * @param owner tokens owner1347 * @param tokens array of tokens with owner and properties1348 * @param label 1349 * @example1350 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1351 * properties: [{1352 * key: "gender",1353 * value: "female",1354 * },{1355 * key: "age",1356 * value: "33",1357 * }],1358 * }]);1359 * @returns array of newly created tokens1360 */1361 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1362 if(typeof label === 'undefined') label = `collection #${collectionId}`;1363 const rawTokens = [];1364 for (const token of tokens) {1365 const raw = {NFT: {properties: token.properties}};1366 rawTokens.push(raw);1367 }1368 const creationResult = await this.helper.executeExtrinsic(1369 signer,1370 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1371 true, `Unable to mint NFT tokens for ${label}`,1372 );1373 const collection = this.getCollectionObject(collectionId);1374 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1375 }13761377 /**1378 * Destroys a concrete instance of NFT.1379 * @param signer keyring of signer1380 * @param collectionId ID of collection1381 * @param tokenId ID of token1382 * @param label 1383 * @example burnToken(aliceKeyring, 10, 5);1384 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1385 */1386 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1387 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1388 }13891390 /**1391 * Set, change, or remove approved address to transfer the ownership of the NFT.1392 * 1393 * @param signer keyring of signer1394 * @param collectionId ID of collection1395 * @param tokenId ID of token1396 * @param toAddressObj address to approve1397 * @param label 1398 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1399 * @returns ```true``` if extrinsic success, otherwise ```false```1400 */1401 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1402 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1403 }1404}140514061407class RFTGroup extends NFTnRFT {1408 /**1409 * Get collection object1410 * @param collectionId ID of collection1411 * @example getCollectionObject(2);1412 * @returns instance of UniqueRFTCollection1413 */1414 getCollectionObject(collectionId: number): UniqueRFTCollection {1415 return new UniqueRFTCollection(collectionId, this.helper);1416 }14171418 /**1419 * Get token object1420 * @param collectionId ID of collection1421 * @param tokenId ID of token1422 * @example getTokenObject(10, 5);1423 * @returns instance of UniqueNFTToken1424 */1425 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1426 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1427 }14281429 /**1430 * Get top 10 token owners with the largest number of pieces 1431 * @param collectionId ID of collection1432 * @param tokenId ID of token1433 * @example getTokenTop10Owners(10, 5);1434 * @returns array of top 10 owners1435 */1436 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1437 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1438 }14391440 /**1441 * Get number of pieces owned by address1442 * @param collectionId ID of collection1443 * @param tokenId ID of token1444 * @param addressObj address token owner1445 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1446 * @returns number of pieces ownerd by address1447 */1448 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1449 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1450 }14511452 /**1453 * Transfer pieces of token to another address1454 * @param signer keyring of signer1455 * @param collectionId ID of collection1456 * @param tokenId ID of token1457 * @param addressObj address of a new owner1458 * @param amount number of pieces to be transfered1459 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1463 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1464 }14651466 /**1467 * Change ownership of some pieces of RFT on behalf of the owner. 1468 * @param signer keyring of signer1469 * @param collectionId ID of collection1470 * @param tokenId ID of token1471 * @param fromAddressObj address on behalf of which the token will be sent1472 * @param toAddressObj new token owner1473 * @param amount number of pieces to be transfered1474 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1475 * @returns ```true``` if extrinsic success, otherwise ```false```1476 */1477 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1478 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1479 }14801481 /**1482 * Mint new collection1483 * @param signer keyring of signer1484 * @param collectionOptions Collection options1485 * @param label 1486 * @example1487 * mintCollection(aliceKeyring, {1488 * name: 'New',1489 * description: 'New collection',1490 * tokenPrefix: 'NEW',1491 * })1492 * @returns object of the created collection1493 */1494 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1495 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1496 }14971498 /**1499 * Mint new token1500 * @param signer keyring of signer1501 * @param data token data1502 * @param label 1503 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1504 * @returns created token object1505 */1506 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1507 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1508 const creationResult = await this.helper.executeExtrinsic(1509 signer,1510 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1511 refungible: {1512 pieces: data.pieces,1513 properties: data.properties,1514 },1515 }],1516 true, `Unable to mint RFT token for ${label}`,1517 );1518 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1519 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1520 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1521 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1522 }15231524 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1525 throw Error('Not implemented');1526 if(typeof label === 'undefined') label = `collection #${collectionId}`;1527 const creationResult = await this.helper.executeExtrinsic(1528 signer,1529 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1530 true, `Unable to mint RFT tokens for ${label}`,1531 );1532 const collection = this.getCollectionObject(collectionId);1533 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1534 }15351536 /**1537 * Mint multiple RFT tokens with one owner1538 * @param signer keyring of signer1539 * @param collectionId ID of collection1540 * @param owner tokens owner1541 * @param tokens array of tokens with properties and pieces1542 * @param label 1543 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1544 * @returns array of newly created RFT tokens1545 */1546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1547 if(typeof label === 'undefined') label = `collection #${collectionId}`;1548 const rawTokens = [];1549 for (const token of tokens) {1550 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1551 rawTokens.push(raw);1552 }1553 const creationResult = await this.helper.executeExtrinsic(1554 signer,1555 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1556 true, `Unable to mint RFT tokens for ${label}`,1557 );1558 const collection = this.getCollectionObject(collectionId);1559 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1560 }15611562 /**1563 * Destroys a concrete instance of RFT.1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @param label 1568 * @param amount number of pieces to be burnt1569 * @example burnToken(aliceKeyring, 10, 5);1570 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1571 */1572 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1573 return await super.burnToken(signer, collectionId, tokenId, label, amount);1574 }15751576 /**1577 * Set, change, or remove approved address to transfer the ownership of the RFT.1578 * 1579 * @param signer keyring of signer1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param toAddressObj address to approve1583 * @param label 1584 * @param amount number of pieces to be approved1585 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1586 * @returns true if the token success, otherwise false1587 */1588 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1589 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1590 }15911592 /**1593 * Get total number of pieces1594 * @param collectionId ID of collection1595 * @param tokenId ID of token1596 * @example getTokenTotalPieces(10, 5);1597 * @returns number of pieces1598 */1599 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1600 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1601 }16021603 /**1604 * Change number of token pieces. Signer must be the owner of all token pieces.1605 * @param signer keyring of signer1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param amount new number of pieces1609 * @param label 1610 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1611 * @returns true if the repartion was success, otherwise false1612 */1613 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1614 if(typeof label === 'undefined') label = `collection #${collectionId}`;1615 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1616 const repartitionResult = await this.helper.executeExtrinsic(1617 signer,1618 'api.tx.unique.repartition', [collectionId, tokenId, amount],1619 true, `Unable to repartition RFT token for ${label}`,1620 );1621 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1622 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1623 }1624}162516261627class FTGroup extends CollectionGroup {1628 /**1629 * Get collection object1630 * @param collectionId ID of collection1631 * @example getCollectionObject(2);1632 * @returns instance of UniqueFTCollection1633 */1634 getCollectionObject(collectionId: number): UniqueFTCollection {1635 return new UniqueFTCollection(collectionId, this.helper);1636 }16371638 /**1639 * Mint new fungible collection1640 * @param signer keyring of signer1641 * @param collectionOptions Collection options1642 * @param decimalPoints number of token decimals 1643 * @param errorLabel 1644 * @example1645 * mintCollection(aliceKeyring, {1646 * name: 'New',1647 * description: 'New collection',1648 * tokenPrefix: 'NEW',1649 * }, 18)1650 * @returns newly created fungible collection1651 */1652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1653 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1654 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1655 collectionOptions.mode = {fungible: decimalPoints};1656 for (const key of ['name', 'description', 'tokenPrefix']) {1657 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);1658 }1659 const creationResult = await this.helper.executeExtrinsic(1660 signer,1661 'api.tx.unique.createCollectionEx', [collectionOptions],1662 true, errorLabel,1663 );1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1665 }16661667 /**1668 * Mint tokens1669 * @param signer keyring of signer1670 * @param collectionId ID of collection1671 * @param owner address owner of new tokens1672 * @param amount amount of tokens to be meanted1673 * @param label 1674 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1675 * @returns ```true``` if extrinsic success, otherwise ```false``` 1676 */1677 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1678 if(typeof label === 'undefined') label = `collection #${collectionId}`;1679 const creationResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1682 fungible: {1683 value: amount,1684 },1685 }],1686 true, `Unable to mint fungible tokens for ${label}`,1687 );1688 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1689 }16901691 /**1692 * Mint multiple Fungible tokens with one owner1693 * @param signer keyring of signer1694 * @param collectionId ID of collection1695 * @param owner tokens owner1696 * @param tokens array of tokens with properties and pieces1697 * @param label 1698 * @returns ```true``` if extrinsic success, otherwise ```false``` 1699 */1700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1701 if(typeof label === 'undefined') label = `collection #${collectionId}`;1702 const rawTokens = [];1703 for (const token of tokens) {1704 const raw = {Fungible: {Value: token.value}};1705 rawTokens.push(raw);1706 }1707 const creationResult = await this.helper.executeExtrinsic(1708 signer,1709 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1710 true, `Unable to mint RFT tokens for ${label}`,1711 );1712 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1713 }17141715 /**1716 * Get the top 10 owners with the largest balance for the Fungible collection 1717 * @param collectionId ID of collection1718 * @example getTop10Owners(10);1719 * @returns array of ```ICrossAccountId```1720 */1721 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1722 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1723 }17241725 /**1726 * Get account balance1727 * @param collectionId ID of collection1728 * @param addressObj address of owner1729 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1730 * @returns amount of fungible tokens owned by address1731 */1732 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1733 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1734 }17351736 /**1737 * Transfer tokens to address1738 * @param signer keyring of signer1739 * @param collectionId ID of collection1740 * @param toAddressObj address recepient1741 * @param amount amount of tokens to be sent1742 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1743 * @returns ```true``` if extrinsic success, otherwise ```false``` 1744 */1745 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1746 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1747 }17481749 /**1750 * Transfer some tokens on behalf of the owner.1751 * @param signer keyring of signer1752 * @param collectionId ID of collection1753 * @param fromAddressObj address on behalf of which tokens will be sent1754 * @param toAddressObj address where token to be sent1755 * @param amount number of tokens to be sent1756 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1757 * @returns ```true``` if extrinsic success, otherwise ```false``` 1758 */1759 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1760 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Destroy some amount of tokens1765 * @param signer keyring of signer1766 * @param collectionId ID of collection1767 * @param amount amount of tokens to be destroyed1768 * @param label 1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @param label 1783 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1784 * @returns ```true``` if extrinsic success, otherwise ```false``` 1785 */1786 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1787 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1788 }17891790 /**1791 * Get total collection supply1792 * @param collectionId 1793 * @returns 1794 */1795 async getTotalPieces(collectionId: number): Promise<bigint> {1796 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1797 }17981799 /**1800 * Set, change, or remove approved address to transfer tokens.1801 * 1802 * @param signer keyring of signer1803 * @param collectionId ID of collection1804 * @param toAddressObj address to be approved1805 * @param amount amount of tokens to be approved1806 * @param label 1807 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1808 * @returns ```true``` if extrinsic success, otherwise ```false``` 1809 */1810 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1811 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1812 }18131814 /**1815 * Get amount of fungible tokens approved to transfer1816 * @param collectionId ID of collection1817 * @param fromAddressObj owner of tokens1818 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1819 * @returns number of tokens approved for the transfer1820 */1821 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1822 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1823 }1824}182518261827class ChainGroup extends HelperGroup {1828 /**1829 * Get system properties of a chain1830 * @example getChainProperties();1831 * @returns ss58Format, token decimals, and token symbol1832 */1833 getChainProperties(): IChainProperties {1834 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1835 return {1836 ss58Format: properties.ss58Format.toJSON(),1837 tokenDecimals: properties.tokenDecimals.toJSON(),1838 tokenSymbol: properties.tokenSymbol.toJSON(),1839 };1840 }18411842 /**1843 * Get chain header1844 * @example getLatestBlockNumber();1845 * @returns the number of the last block1846 */1847 async getLatestBlockNumber(): Promise<number> {1848 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1849 }18501851 /**1852 * Get block hash by block number1853 * @param blockNumber number of block1854 * @example getBlockHashByNumber(12345);1855 * @returns hash of a block1856 */1857 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1858 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1859 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1860 return blockHash;1861 }18621863 // TODO add docs1864 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1865 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1866 if (!blockHash) return null;1867 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1868 }18691870 /**1871 * Get account nonce1872 * @param address substrate address1873 * @example getNonce("5GrwvaEF5zXb26Fz...");1874 * @returns number, account's nonce1875 */1876 async getNonce(address: TSubstrateAccount): Promise<number> {1877 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1878 }1879}188018811882class BalanceGroup extends HelperGroup {1883 /**1884 * Representation of the native token in the smallest unit1885 * @example getOneTokenNominal()1886 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1887 */1888 getOneTokenNominal(): bigint {1889 const chainProperties = this.helper.chain.getChainProperties();1890 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1891 }18921893 /**1894 * Get substrate address balance1895 * @param address substrate address1896 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1897 * @returns amount of tokens on address1898 */1899 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1900 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1901 }19021903 /**1904 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1905 * @param address substrate address1906 * @returns 1907 */1908 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1909 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1910 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1911 }19121913 /**1914 * Get ethereum address balance1915 * @param address ethereum address1916 * @example getEthereum("0x9F0583DbB855d...")1917 * @returns amount of tokens on address1918 */1919 async getEthereum(address: TEthereumAccount): Promise<bigint> {1920 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1921 }19221923 /**1924 * Transfer tokens to substrate address1925 * @param signer keyring of signer1926 * @param address substrate address of a recepient1927 * @param amount amount of tokens to be transfered1928 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1929 * @returns ```true``` if extrinsic success, otherwise ```false```1930 */1931 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1932 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}`);19331934 let transfer = {from: null, to: null, amount: 0n} as any;1935 result.result.events.forEach(({event: {data, method, section}}) => {1936 if ((section === 'balances') && (method === 'Transfer')) {1937 transfer = {1938 from: this.helper.address.normalizeSubstrate(data[0]),1939 to: this.helper.address.normalizeSubstrate(data[1]),1940 amount: BigInt(data[2]),1941 };1942 }1943 });1944 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1945 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1946 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1947 return isSuccess;1948 }1949}195019511952class AddressGroup extends HelperGroup {1953 /**1954 * Normalizes the address to the specified ss58 format, by default ```42```.1955 * @param address substrate address1956 * @param ss58Format format for address conversion, by default ```42```1957 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1958 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1959 */1960 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1961 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1962 }19631964 /**1965 * Get address in the connected chain format1966 * @param address substrate address1967 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1968 * @returns address in chain format1969 */1970 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1971 const info = this.helper.chain.getChainProperties();1972 return encodeAddress(decodeAddress(address), info.ss58Format);1973 }19741975 /**1976 * Get substrate mirror of an ethereum address1977 * @param ethAddress ethereum address1978 * @param toChainFormat false for normalized account1979 * @example ethToSubstrate('0x9F0583DbB855d...')1980 * @returns substrate mirror of a provided ethereum address1981 */1982 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1983 if(!toChainFormat) return evmToAddress(ethAddress);1984 const info = this.helper.chain.getChainProperties();1985 return evmToAddress(ethAddress, info.ss58Format);1986 }19871988 /**1989 * Get ethereum mirror of a substrate address1990 * @param subAddress substrate account1991 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1992 * @returns ethereum mirror of a provided substrate address1993 */1994 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1995 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1996 }1997}19981999class StakingGroup extends HelperGroup {2000 /**2001 * Stake tokens for App Promotion2002 * @param signer keyring of signer2003 * @param amountToStake amount of tokens to stake2004 * @param label extra label for log2005 * @returns2006 */2007 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2008 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2009 const stakeResult = await this.helper.executeExtrinsic(2010 signer,2011 'api.tx.appPromotion.stake', [amountToStake],2012 true, `stake failed for ${label}`,2013 );2014 // TODO extract info from stakeResult2015 return true;2016 }20172018 /**2019 * Unstake tokens for App Promotion2020 * @param signer keyring of signer2021 * @param amountToUnstake amount of tokens to unstake2022 * @param label extra label for log2023 * @returns 2024 */2025 async unstake(signer: TSigner, label?: string): Promise<boolean> {2026 if(typeof label === 'undefined') label = `${signer.address}`;2027 const unstakeResult = await this.helper.executeExtrinsic(2028 signer,2029 'api.tx.appPromotion.unstake', [],2030 true, `unstake failed for ${label}`,2031 );2032 // TODO extract info from unstakeResult2033 return true;2034 }20352036 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2037 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2038 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2039 }20402041 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2042 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();2043 }20442045 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2046 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2047 }20482049 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2050 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2051 }2052 2053 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2054 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2055 }2056}20572058export class UniqueHelper extends ChainHelperBase {2059 chain: ChainGroup;2060 balance: BalanceGroup;2061 address: AddressGroup;2062 collection: CollectionGroup;2063 nft: NFTGroup;2064 rft: RFTGroup;2065 ft: FTGroup;2066 staking: StakingGroup;20672068 constructor(logger?: ILogger) {2069 super(logger);2070 this.chain = new ChainGroup(this);2071 this.balance = new BalanceGroup(this);2072 this.address = new AddressGroup(this);2073 this.collection = new CollectionGroup(this);2074 this.nft = new NFTGroup(this);2075 this.rft = new RFTGroup(this);2076 this.ft = new FTGroup(this);2077 this.staking = new StakingGroup(this);2078 } 2079}208020812082class UniqueCollectionBase {2083 helper: UniqueHelper;2084 collectionId: number;20852086 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2087 this.collectionId = collectionId;2088 this.helper = uniqueHelper;2089 }20902091 async getData() {2092 return await this.helper.collection.getData(this.collectionId);2093 }20942095 async getLastTokenId() {2096 return await this.helper.collection.getLastTokenId(this.collectionId);2097 }20982099 async isTokenExists(tokenId: number) {2100 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2101 }21022103 async getAdmins() {2104 return await this.helper.collection.getAdmins(this.collectionId);2105 }21062107 async getAllowList() {2108 return await this.helper.collection.getAllowList(this.collectionId);2109 }21102111 async getEffectiveLimits() {2112 return await this.helper.collection.getEffectiveLimits(this.collectionId);2113 }21142115 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2116 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2117 }21182119 async confirmSponsorship(signer: TSigner, label?: string) {2120 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2121 }21222123 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2124 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2125 }21262127 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2128 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2129 }21302131 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2132 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2133 }21342135 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2136 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2137 }21382139 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2140 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2141 }21422143 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2144 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2145 }21462147 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2148 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2149 }21502151 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2152 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2153 }21542155 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2156 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2157 }21582159 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2160 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2161 }21622163 async disableNesting(signer: TSigner, label?: string) {2164 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2165 }21662167 async burn(signer: TSigner, label?: string) {2168 return await this.helper.collection.burn(signer, this.collectionId, label);2169 }2170}217121722173class UniqueNFTCollection extends UniqueCollectionBase {2174 getTokenObject(tokenId: number) {2175 return new UniqueNFTToken(tokenId, this);2176 }21772178 async getTokensByAddress(addressObj: ICrossAccountId) {2179 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2180 }21812182 async getToken(tokenId: number, blockHashAt?: string) {2183 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2184 }21852186 async getTokenOwner(tokenId: number, blockHashAt?: string) {2187 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2188 }21892190 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2191 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2192 }21932194 async getTokenChildren(tokenId: number, blockHashAt?: string) {2195 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2196 }21972198 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2199 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2200 }22012202 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2203 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2204 }22052206 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2207 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2208 }22092210 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2211 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2212 }22132214 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2215 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2216 }22172218 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2219 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2220 }22212222 async burnToken(signer: TSigner, tokenId: number, label?: string) {2223 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2224 }22252226 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2227 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2228 }22292230 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2231 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2232 }22332234 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2235 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2236 }22372238 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2239 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2240 }22412242 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2243 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2244 }2245}224622472248class UniqueRFTCollection extends UniqueCollectionBase {2249 getTokenObject(tokenId: number) {2250 return new UniqueRFTToken(tokenId, this);2251 }22522253 async getTokensByAddress(addressObj: ICrossAccountId) {2254 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2255 }22562257 async getTop10TokenOwners(tokenId: number) {2258 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2259 }22602261 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2262 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2263 }22642265 async getTokenTotalPieces(tokenId: number) {2266 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2267 }22682269 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2270 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2271 }22722273 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2274 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2275 }22762277 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2278 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2279 }22802281 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2282 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2283 }22842285 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2286 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2287 }22882289 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2290 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2291 }22922293 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2294 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2295 }22962297 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2298 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2299 }23002301 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2302 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2303 }23042305 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2306 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2307 }23082309 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2310 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2311 }2312}231323142315class UniqueFTCollection extends UniqueCollectionBase {2316 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2317 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2318 }23192320 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2321 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2322 }23232324 async getBalance(addressObj: ICrossAccountId) {2325 return await this.helper.ft.getBalance(this.collectionId, addressObj);2326 }23272328 async getTop10Owners() {2329 return await this.helper.ft.getTop10Owners(this.collectionId);2330 }23312332 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2333 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2334 }23352336 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2337 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2338 }23392340 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2341 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2342 }23432344 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2345 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2346 }23472348 async getTotalPieces() {2349 return await this.helper.ft.getTotalPieces(this.collectionId);2350 }23512352 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2353 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2354 }23552356 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2357 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2358 }2359}236023612362class UniqueTokenBase implements IToken {2363 collection: UniqueNFTCollection | UniqueRFTCollection;2364 collectionId: number;2365 tokenId: number;23662367 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2368 this.collection = collection;2369 this.collectionId = collection.collectionId;2370 this.tokenId = tokenId;2371 }23722373 async getNextSponsored(addressObj: ICrossAccountId) {2374 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2375 }23762377 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2378 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2379 }23802381 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2382 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2383 }2384}238523862387class UniqueNFTToken extends UniqueTokenBase {2388 collection: UniqueNFTCollection;23892390 constructor(tokenId: number, collection: UniqueNFTCollection) {2391 super(tokenId, collection);2392 this.collection = collection;2393 }23942395 async getData(blockHashAt?: string) {2396 return await this.collection.getToken(this.tokenId, blockHashAt);2397 }23982399 async getOwner(blockHashAt?: string) {2400 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2401 }24022403 async getTopmostOwner(blockHashAt?: string) {2404 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2405 }24062407 async getChildren(blockHashAt?: string) {2408 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2409 }24102411 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2412 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2413 }24142415 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2416 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2417 }24182419 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2420 return await this.collection.transferToken(signer, this.tokenId, addressObj);2421 }24222423 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2424 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2425 }24262427 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2428 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2429 }24302431 async isApproved(toAddressObj: ICrossAccountId) {2432 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2433 }24342435 async burn(signer: TSigner, label?: string) {2436 return await this.collection.burnToken(signer, this.tokenId, label);2437 }2438}24392440class UniqueRFTToken extends UniqueTokenBase {2441 collection: UniqueRFTCollection;24422443 constructor(tokenId: number, collection: UniqueRFTCollection) {2444 super(tokenId, collection);2445 this.collection = collection;2446 }24472448 async getTop10Owners() {2449 return await this.collection.getTop10TokenOwners(this.tokenId);2450 }24512452 async getBalance(addressObj: ICrossAccountId) {2453 return await this.collection.getTokenBalance(this.tokenId, addressObj);2454 }24552456 async getTotalPieces() {2457 return await this.collection.getTokenTotalPieces(this.tokenId);2458 }24592460 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2461 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2462 }24632464 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2465 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2466 }24672468 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2469 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2470 }24712472 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2473 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2474 }24752476 async repartition(signer: TSigner, amount: bigint, label?: string) {2477 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2478 }24792480 async burn(signer: TSigner, amount=100n, label?: string) {2481 return await this.collection.burnToken(signer, this.tokenId, amount, label);2482 }2483}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error('Unable to create collection!');97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error('No CollectionCreated event was found!');108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult) {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error('Unable to create tokens!');116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult) {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error('Unable to burn tokens!');136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event was found!`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 // eslint-disable-next-line no-async-promise-executor321 return new Promise(async (resolve, reject) => {322 try {323 const unsub = await sign((result: any) => {324 const status = this.getTransactionStatus(result);325326 if (status === this.transactionStatus.SUCCESS) {327 this.logger.log(`${label} successful`);328 unsub();329 resolve({result, status});330 } else if (status === this.transactionStatus.FAIL) {331 let moduleError = null;332333 if (result.hasOwnProperty('dispatchError')) {334 const dispatchError = result['dispatchError'];335336 if (dispatchError && dispatchError.isModule) {337 const modErr = dispatchError.asModule;338 const errorMeta = dispatchError.registry.findMetaError(modErr);339340 moduleError = `${errorMeta.section}.${errorMeta.name}`;341 }342 else {343 this.logger.log(result, this.logger.level.ERROR);344 }345 }346347 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);348 unsub();349 reject({status, moduleError, result});350 }351 });352 } catch (e) {353 this.logger.log(e, this.logger.level.ERROR);354 reject(e);355 }356 });357 }358359 constructApiCall(apiCall: string, params: any[]) {360 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);361 let call = this.api as any;362 for(const part of apiCall.slice(4).split('.')) {363 call = call[part];364 }365 return call(...params);366 }367368 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {369 if(this.api === null) throw Error('API not initialized');370 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);371372 const startTime = (new Date()).getTime();373 let result: ITransactionResult;374 let events = [];375 try {376 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;377 events = result.result.events.map((x: any) => x.toHuman());378 }379 catch(e) {380 if(!(e as object).hasOwnProperty('status')) throw e;381 result = e as ITransactionResult;382 }383384 const endTime = (new Date()).getTime();385386 const log = {387 executedAt: endTime,388 executionTime: endTime - startTime,389 type: this.chainLogType.EXTRINSIC,390 status: result.status,391 call: extrinsic,392 signer: this.getSignerAddress(sender),393 params,394 } as IUniqueHelperLog;395396 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;397 if(events.length > 0) log.events = events;398399 this.chainLog.push(log);400401 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);402 return result;403 }404405 async callRpc(rpc: string, params?: any[]) {406 if(typeof params === 'undefined') params = [];407 if(this.api === null) throw Error('API not initialized');408 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);409410 const startTime = (new Date()).getTime();411 let result;412 let error = null;413 const log = {414 type: this.chainLogType.RPC,415 call: rpc,416 params,417 } as IUniqueHelperLog;418419 try {420 result = await this.constructApiCall(rpc, params);421 }422 catch(e) {423 error = e;424 }425426 const endTime = (new Date()).getTime();427428 log.executedAt = endTime;429 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';430 log.executionTime = endTime - startTime;431432 this.chainLog.push(log);433434 if(error !== null) throw error;435436 return result;437 }438439 getSignerAddress(signer: IKeyringPair | string): string {440 if(typeof signer === 'string') return signer;441 return signer.address;442 }443}444445446class HelperGroup {447 helper: UniqueHelper;448449 constructor(uniqueHelper: UniqueHelper) {450 this.helper = uniqueHelper;451 }452}453454455class CollectionGroup extends HelperGroup {456 /**457 * Get number of blocks when sponsored transaction is available.458 *459 * @param collectionId ID of collection460 * @param tokenId ID of token461 * @param addressObj address for which the sponsorship is checked462 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});463 * @returns number of blocks or null if sponsorship hasn't been set464 */465 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {466 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();467 }468469 /**470 * Get the number of created collections.471 * 472 * @returns number of created collections473 */474 async getTotalCount(): Promise<number> {475 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();476 }477478 /**479 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.480 * 481 * @param collectionId ID of collection482 * @example await getData(2)483 * @returns collection information object484 */485 async getData(collectionId: number): Promise<{486 id: number;487 name: string;488 description: string;489 tokensCount: number;490 admins: ICrossAccountId[];491 normalizedOwner: TSubstrateAccount;492 raw: any493 } | null> {494 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);495 const humanCollection = collection.toHuman(), collectionData = {496 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],497 raw: humanCollection,498 } as any, jsonCollection = collection.toJSON();499 if (humanCollection === null) return null;500 collectionData.raw.limits = jsonCollection.limits;501 collectionData.raw.permissions = jsonCollection.permissions;502 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);503 for (const key of ['name', 'description']) {504 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);505 }506507 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;508 collectionData.admins = await this.getAdmins(collectionId);509510 return collectionData;511 }512513 /**514 * Get the normalized addresses of the collection's administrators.515 * 516 * @param collectionId ID of collection517 * @example await getAdmins(1)518 * @returns array of administrators519 */520 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {521 const normalized = [];522 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {523 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});524 else normalized.push(admin);525 }526 return normalized;527 }528529 /**530 * Get the normalized addresses added to the collection allow-list.531 * @param collectionId ID of collection532 * @example await getAllowList(1)533 * @returns array of allow-listed addresses534 */535 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {536 const normalized = [];537 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();538 for (const address of allowListed) {539 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});540 else normalized.push(address);541 }542 return normalized;543 }544545 /**546 * Get the effective limits of the collection instead of null for default values547 * 548 * @param collectionId ID of collection549 * @example await getEffectiveLimits(2)550 * @returns object of collection limits551 */552 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {553 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();554 }555556 /**557 * Burns the collection if the signer has sufficient permissions and collection is empty.558 * 559 * @param signer keyring of signer560 * @param collectionId ID of collection561 * @example await helper.collection.burn(aliceKeyring, 3);562 * @returns ```true``` if extrinsic success, otherwise ```false```563 */564 async burn(signer: TSigner, collectionId: number): Promise<boolean> {565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');572 }573574 /**575 * Sets the sponsor for the collection (Requires the Substrate address).576 * 577 * @param signer keyring of signer578 * @param collectionId ID of collection579 * @param sponsorAddress Sponsor substrate address580 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")581 * @returns ```true``` if extrinsic success, otherwise ```false```582 */583 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');591 }592593 /**594 * Confirms consent to sponsor the collection on behalf of the signer.595 * 596 * @param signer keyring of signer597 * @param collectionId ID of collection598 * @example confirmSponsorship(aliceKeyring, 10)599 * @returns ```true``` if extrinsic success, otherwise ```false```600 */601 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {602 const result = await this.helper.executeExtrinsic(603 signer,604 'api.tx.unique.confirmSponsorship', [collectionId],605 true,606 );607608 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');609 }610611 /**612 * Sets the limits of the collection. At least one limit must be specified for a correct call.613 * 614 * @param signer keyring of signer615 * @param collectionId ID of collection616 * @param limits collection limits object617 * @example618 * await setLimits(619 * aliceKeyring,620 * 10,621 * {622 * sponsorTransferTimeout: 0,623 * ownerCanDestroy: false624 * }625 * )626 * @returns ```true``` if extrinsic success, otherwise ```false```627 */628 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {629 const result = await this.helper.executeExtrinsic(630 signer,631 'api.tx.unique.setCollectionLimits', [collectionId, limits],632 true,633 );634635 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');636 }637638 /**639 * Changes the owner of the collection to the new Substrate address.640 * 641 * @param signer keyring of signer642 * @param collectionId ID of collection643 * @param ownerAddress substrate address of new owner644 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")645 * @returns ```true``` if extrinsic success, otherwise ```false```646 */647 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {648 const result = await this.helper.executeExtrinsic(649 signer,650 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],651 true,652 );653654 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');655 }656657 /**658 * Adds a collection administrator. 659 * 660 * @param signer keyring of signer661 * @param collectionId ID of collection662 * @param adminAddressObj Administrator address (substrate or ethereum)663 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})664 * @returns ```true``` if extrinsic success, otherwise ```false```665 */666 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {667 const result = await this.helper.executeExtrinsic(668 signer,669 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],670 true,671 );672673 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');674 }675676 /**677 * Removes a collection administrator.678 * 679 * @param signer keyring of signer680 * @param collectionId ID of collection681 * @param adminAddressObj Administrator address (substrate or ethereum)682 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})683 * @returns ```true``` if extrinsic success, otherwise ```false```684 */685 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {686 const result = await this.helper.executeExtrinsic(687 signer,688 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],689 true,690 );691692 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');693 }694695 /**696 * Adds an address to allow list 697 * @param signer keyring of signer698 * @param collectionId ID of collection699 * @param addressObj address to add to the allow list700 * @returns ```true``` if extrinsic success, otherwise ```false```701 */702 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {703 const result = await this.helper.executeExtrinsic(704 signer,705 'api.tx.unique.addToAllowList', [collectionId, addressObj],706 true,707 );708709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');710 }711712 /**713 * Removes an address from allow list 714 * 715 * @param signer keyring of signer716 * @param collectionId ID of collection717 * @param addressObj address to remove from the allow list718 * @returns ```true``` if extrinsic success, otherwise ```false```719 */720 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {721 const result = await this.helper.executeExtrinsic(722 signer,723 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],724 true,725 );726727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');728 }729730 /**731 * Sets onchain permissions for selected collection.732 * 733 * @param signer keyring of signer734 * @param collectionId ID of collection735 * @param permissions collection permissions object736 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});737 * @returns ```true``` if extrinsic success, otherwise ```false```738 */739 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');747 }748749 /**750 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.751 * 752 * @param signer keyring of signer753 * @param collectionId ID of collection754 * @param permissions nesting permissions object755 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});756 * @returns ```true``` if extrinsic success, otherwise ```false```757 */758 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {759 return await this.setPermissions(signer, collectionId, {nesting: permissions});760 }761762 /**763 * Disables nesting for selected collection.764 * 765 * @param signer keyring of signer766 * @param collectionId ID of collection767 * @example disableNesting(aliceKeyring, 10);768 * @returns ```true``` if extrinsic success, otherwise ```false```769 */770 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});772 }773774 /**775 * Sets onchain properties to the collection.776 * 777 * @param signer keyring of signer778 * @param collectionId ID of collection779 * @param properties array of property objects780 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);781 * @returns ```true``` if extrinsic success, otherwise ```false```782 */783 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {784 const result = await this.helper.executeExtrinsic(785 signer,786 'api.tx.unique.setCollectionProperties', [collectionId, properties],787 true,788 );789790 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');791 }792793 /**794 * Deletes onchain properties from the collection.795 * 796 * @param signer keyring of signer797 * @param collectionId ID of collection798 * @param propertyKeys array of property keys to delete799 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);800 * @returns ```true``` if extrinsic success, otherwise ```false```801 */802 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {803 const result = await this.helper.executeExtrinsic(804 signer,805 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],806 true,807 );808809 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');810 }811812 /**813 * Changes the owner of the token.814 * 815 * @param signer keyring of signer816 * @param collectionId ID of collection817 * @param tokenId ID of token818 * @param addressObj address of a new owner819 * @param amount amount of tokens to be transfered. For NFT must be set to 1n820 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})821 * @returns true if the token success, otherwise false822 */823 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {824 const result = await this.helper.executeExtrinsic(825 signer,826 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],827 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,828 );829830 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);831 }832833 /**834 * 835 * Change ownership of a token(s) on behalf of the owner. 836 * 837 * @param signer keyring of signer838 * @param collectionId ID of collection839 * @param tokenId ID of token840 * @param fromAddressObj address on behalf of which the token will be sent841 * @param toAddressObj new token owner842 * @param amount amount of tokens to be transfered. For NFT must be set to 1n843 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})844 * @returns true if the token success, otherwise false845 */846 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {847 const result = await this.helper.executeExtrinsic(848 signer,849 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],850 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,851 );852 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);853 }854855 /**856 * 857 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.858 * 859 * @param signer keyring of signer860 * @param collectionId ID of collection861 * @param tokenId ID of token862 * @param amount amount of tokens to be burned. For NFT must be set to 1n863 * @example burnToken(aliceKeyring, 10, 5);864 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```865 */866 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{867 success: boolean,868 token: number | null869 }> {870 const burnResult = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.burnItem', [collectionId, tokenId, amount],873 true, // `Unable to burn token for ${label}`,874 );875 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);876 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');877 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};878 }879880 /**881 * Destroys a concrete instance of NFT on behalf of the owner882 * 883 * @param signer keyring of signer884 * @param collectionId ID of collection885 * @param fromAddressObj address on behalf of which the token will be burnt886 * @param tokenId ID of token887 * @param amount amount of tokens to be burned. For NFT must be set to 1n888 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})889 * @returns ```true``` if extrinsic success, otherwise ```false```890 */891 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {892 const burnResult = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],895 true, // `Unable to burn token from for ${label}`,896 );897 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);898 return burnedTokens.success && burnedTokens.tokens.length > 0;899 }900901 /**902 * Set, change, or remove approved address to transfer the ownership of the NFT.903 * 904 * @param signer keyring of signer905 * @param collectionId ID of collection906 * @param tokenId ID of token907 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens908 * @param amount amount of token to be approved. For NFT must be set to 1n909 * @returns ```true``` if extrinsic success, otherwise ```false```910 */911 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {912 const approveResult = await this.helper.executeExtrinsic(913 signer, 914 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],915 true, // `Unable to approve token for ${label}`,916 );917918 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');919 }920921 /**922 * Get the amount of token pieces approved to transfer or burn. Normally 0.923 * 924 * @param collectionId ID of collection925 * @param tokenId ID of token926 * @param toAccountObj address which is approved to use token pieces927 * @param fromAccountObj address which may have allowed the use of its owned tokens928 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})929 * @returns number of approved to transfer pieces930 */931 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {932 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();933 }934935 /**936 * Get the last created token ID in a collection937 * 938 * @param collectionId ID of collection939 * @example getLastTokenId(10);940 * @returns id of the last created token941 */942 async getLastTokenId(collectionId: number): Promise<number> {943 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();944 }945946 /**947 * Check if token exists948 * 949 * @param collectionId ID of collection950 * @param tokenId ID of token951 * @example isTokenExists(10, 20);952 * @returns true if the token exists, otherwise false953 */954 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {955 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();956 }957}958959class NFTnRFT extends CollectionGroup {960 /**961 * Get tokens owned by account962 * 963 * @param collectionId ID of collection964 * @param addressObj tokens owner965 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})966 * @returns array of token ids owned by account967 */968 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {969 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();970 }971972 /**973 * Get token data974 * 975 * @param collectionId ID of collection976 * @param tokenId ID of token977 * @param propertyKeys optionally filter the token properties to only these keys978 * @param blockHashAt optionally query the data at some block with this hash979 * @example getToken(10, 5);980 * @returns human readable token data 981 */982 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{983 properties: IProperty[];984 owner: ICrossAccountId;985 normalizedOwner: ICrossAccountId;986 }| null> {987 let tokenData;988 if(typeof blockHashAt === 'undefined') {989 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);990 }991 else {992 if(propertyKeys.length == 0) {993 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();994 if(!collection) return null;995 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);996 }997 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);998 }999 tokenData = tokenData.toHuman();1000 if (tokenData === null || tokenData.owner === null) return null;1001 const owner = {} as any;1002 for (const key of Object.keys(tokenData.owner)) {1003 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1004 }1005 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1006 return tokenData;1007 }10081009 /**1010 * Set permissions to change token properties1011 * 1012 * @param signer keyring of signer1013 * @param collectionId ID of collection1014 * @param permissions permissions to change a property by the collection owner or admin1015 * @example setTokenPropertyPermissions(1016 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1017 * )1018 * @returns true if extrinsic success otherwise false1019 */1020 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1021 const result = await this.helper.executeExtrinsic(1022 signer,1023 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1024 true,1025 );10261027 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1028 }10291030 /**1031 * Set token properties1032 * 1033 * @param signer keyring of signer1034 * @param collectionId ID of collection1035 * @param tokenId ID of token1036 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1037 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1038 * @returns ```true``` if extrinsic success, otherwise ```false```1039 */1040 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1048 }10491050 /**1051 * Delete the provided properties of a token1052 * @param signer keyring of signer1053 * @param collectionId ID of collection1054 * @param tokenId ID of token1055 * @param propertyKeys property keys to be deleted 1056 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1057 * @returns ```true``` if extrinsic success, otherwise ```false```1058 */1059 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1067 }10681069 /**1070 * Mint new collection1071 * 1072 * @param signer keyring of signer1073 * @param collectionOptions basic collection options and properties 1074 * @param mode NFT or RFT type of a collection1075 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1076 * @returns object of the created collection1077 */1078 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1079 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1080 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1081 for (const key of ['name', 'description', 'tokenPrefix']) {1082 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);1083 }1084 const creationResult = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.createCollectionEx', [collectionOptions],1087 true, // errorLabel,1088 );1089 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1090 }10911092 getCollectionObject(_collectionId: number): any {1093 return null;1094 }10951096 getTokenObject(_collectionId: number, _tokenId: number): any {1097 return null;1098 }1099}110011011102class NFTGroup extends NFTnRFT {1103 /**1104 * Get collection object1105 * @param collectionId ID of collection1106 * @example getCollectionObject(2);1107 * @returns instance of UniqueNFTCollection1108 */1109 getCollectionObject(collectionId: number): UniqueNFTCollection {1110 return new UniqueNFTCollection(collectionId, this.helper);1111 }11121113 /**1114 * Get token object1115 * @param collectionId ID of collection1116 * @param tokenId ID of token1117 * @example getTokenObject(10, 5);1118 * @returns instance of UniqueNFTToken1119 */1120 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1121 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1122 }11231124 /**1125 * Get token's owner1126 * @param collectionId ID of collection1127 * @param tokenId ID of token1128 * @param blockHashAt optionally query the data at the block with this hash1129 * @example getTokenOwner(10, 5);1130 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1131 */1132 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1133 let owner;1134 if (typeof blockHashAt === 'undefined') {1135 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1136 } else {1137 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1138 }1139 return crossAccountIdFromLower(owner.toJSON());1140 }11411142 /**1143 * Is token approved to transfer1144 * @param collectionId ID of collection1145 * @param tokenId ID of token1146 * @param toAccountObj address to be approved1147 * @returns ```true``` if extrinsic success, otherwise ```false```1148 */1149 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1150 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1151 }11521153 /**1154 * Changes the owner of the token.1155 * 1156 * @param signer keyring of signer1157 * @param collectionId ID of collection1158 * @param tokenId ID of token1159 * @param addressObj address of a new owner1160 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1161 * @returns ```true``` if extrinsic success, otherwise ```false```1162 */1163 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1164 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1165 }11661167 /**1168 * 1169 * Change ownership of a NFT on behalf of the owner. 1170 * 1171 * @param signer keyring of signer1172 * @param collectionId ID of collection1173 * @param tokenId ID of token1174 * @param fromAddressObj address on behalf of which the token will be sent1175 * @param toAddressObj new token owner1176 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1177 * @returns ```true``` if extrinsic success, otherwise ```false```1178 */1179 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1180 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1181 }11821183 /**1184 * Recursively find the address that owns the token1185 * @param collectionId ID of collection1186 * @param tokenId ID of token1187 * @param blockHashAt 1188 * @example getTokenTopmostOwner(10, 5);1189 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1190 */1191 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1192 let owner;1193 if (typeof blockHashAt === 'undefined') {1194 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1195 } else {1196 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1197 }11981199 if (owner === null) return null;12001201 owner = owner.toHuman();12021203 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1204 }12051206 /**1207 * Get tokens nested in the provided token1208 * @param collectionId ID of collection1209 * @param tokenId ID of token1210 * @param blockHashAt optionally query the data at the block with this hash1211 * @example getTokenChildren(10, 5);1212 * @returns tokens whose depth of nesting is <= 5 1213 */1214 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1215 let children;1216 if(typeof blockHashAt === 'undefined') {1217 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1218 } else {1219 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1220 }12211222 return children.toJSON().map((x: any) => {1223 return {collectionId: x.collection, tokenId: x.token};1224 });1225 }12261227 /**1228 * Nest one token into another1229 * @param signer keyring of signer1230 * @param tokenObj token to be nested1231 * @param rootTokenObj token to be parent1232 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1233 * @returns ```true``` if extrinsic success, otherwise ```false```1234 */1235 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1236 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1237 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1238 if(!result) {1239 throw Error('Unable to nest token!');1240 }1241 return result;1242 }12431244 /**1245 * Remove token from nested state1246 * @param signer keyring of signer1247 * @param tokenObj token to unnest1248 * @param rootTokenObj parent of a token1249 * @param toAddressObj address of a new token owner 1250 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1251 * @returns ```true``` if extrinsic success, otherwise ```false```1252 */1253 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1254 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1255 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1256 if(!result) {1257 throw Error('Unable to unnest token!');1258 }1259 return result;1260 }12611262 /**1263 * Mint new collection1264 * @param signer keyring of signer1265 * @param collectionOptions Collection options1266 * @example 1267 * mintCollection(aliceKeyring, {1268 * name: 'New',1269 * description: 'New collection',1270 * tokenPrefix: 'NEW',1271 * })1272 * @returns object of the created collection1273 */1274 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1275 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1276 }12771278 /**1279 * Mint new token1280 * @param signer keyring of signer1281 * @param data token data1282 * @returns created token object1283 */1284 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1285 const creationResult = await this.helper.executeExtrinsic(1286 signer,1287 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1288 nft: {1289 properties: data.properties,1290 },1291 }],1292 true,1293 );1294 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1295 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1296 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1297 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1298 }12991300 /**1301 * Mint multiple NFT tokens1302 * @param signer keyring of signer1303 * @param collectionId ID of collection1304 * @param tokens array of tokens with owner and properties1305 * @example 1306 * mintMultipleTokens(aliceKeyring, 10, [{1307 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1308 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1309 * },{1310 * owner: {Ethereum: "0x9F0583DbB855d..."},1311 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1312 * }]);1313 * @returns ```true``` if extrinsic success, otherwise ```false```1314 */1315 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1316 const creationResult = await this.helper.executeExtrinsic(1317 signer,1318 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1319 true,1320 );1321 const collection = this.getCollectionObject(collectionId);1322 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1323 }13241325 /**1326 * Mint multiple NFT tokens with one owner1327 * @param signer keyring of signer1328 * @param collectionId ID of collection1329 * @param owner tokens owner1330 * @param tokens array of tokens with owner and properties1331 * @example1332 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1333 * properties: [{1334 * key: "gender",1335 * value: "female",1336 * },{1337 * key: "age",1338 * value: "33",1339 * }],1340 * }]);1341 * @returns array of newly created tokens1342 */1343 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1344 const rawTokens = [];1345 for (const token of tokens) {1346 const raw = {NFT: {properties: token.properties}};1347 rawTokens.push(raw);1348 }1349 const creationResult = await this.helper.executeExtrinsic(1350 signer,1351 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1352 true,1353 );1354 const collection = this.getCollectionObject(collectionId);1355 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1356 }13571358 /**1359 * Destroys a concrete instance of NFT.1360 * @param signer keyring of signer1361 * @param collectionId ID of collection1362 * @param tokenId ID of token1363 * @example burnToken(aliceKeyring, 10, 5);1364 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1365 */1366 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1367 return await super.burnToken(signer, collectionId, tokenId, 1n);1368 }13691370 /**1371 * Set, change, or remove approved address to transfer the ownership of the NFT.1372 * 1373 * @param signer keyring of signer1374 * @param collectionId ID of collection1375 * @param tokenId ID of token1376 * @param toAddressObj address to approve1377 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1378 * @returns ```true``` if extrinsic success, otherwise ```false```1379 */1380 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1381 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1382 }1383}138413851386class RFTGroup extends NFTnRFT {1387 /**1388 * Get collection object1389 * @param collectionId ID of collection1390 * @example getCollectionObject(2);1391 * @returns instance of UniqueRFTCollection1392 */1393 getCollectionObject(collectionId: number): UniqueRFTCollection {1394 return new UniqueRFTCollection(collectionId, this.helper);1395 }13961397 /**1398 * Get token object1399 * @param collectionId ID of collection1400 * @param tokenId ID of token1401 * @example getTokenObject(10, 5);1402 * @returns instance of UniqueNFTToken1403 */1404 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1405 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1406 }14071408 /**1409 * Get top 10 token owners with the largest number of pieces 1410 * @param collectionId ID of collection1411 * @param tokenId ID of token1412 * @example getTokenTop10Owners(10, 5);1413 * @returns array of top 10 owners1414 */1415 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1416 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1417 }14181419 /**1420 * Get number of pieces owned by address1421 * @param collectionId ID of collection1422 * @param tokenId ID of token1423 * @param addressObj address token owner1424 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1425 * @returns number of pieces ownerd by address1426 */1427 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1428 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1429 }14301431 /**1432 * Transfer pieces of token to another address1433 * @param signer keyring of signer1434 * @param collectionId ID of collection1435 * @param tokenId ID of token1436 * @param addressObj address of a new owner1437 * @param amount number of pieces to be transfered1438 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1439 * @returns ```true``` if extrinsic success, otherwise ```false```1440 */1441 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1442 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1443 }14441445 /**1446 * Change ownership of some pieces of RFT on behalf of the owner. 1447 * @param signer keyring of signer1448 * @param collectionId ID of collection1449 * @param tokenId ID of token1450 * @param fromAddressObj address on behalf of which the token will be sent1451 * @param toAddressObj new token owner1452 * @param amount number of pieces to be transfered1453 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1454 * @returns ```true``` if extrinsic success, otherwise ```false```1455 */1456 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1457 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1458 }14591460 /**1461 * Mint new collection1462 * @param signer keyring of signer1463 * @param collectionOptions Collection options1464 * @example1465 * mintCollection(aliceKeyring, {1466 * name: 'New',1467 * description: 'New collection',1468 * tokenPrefix: 'NEW',1469 * })1470 * @returns object of the created collection1471 */1472 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1473 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1474 }14751476 /**1477 * Mint new token1478 * @param signer keyring of signer1479 * @param data token data1480 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1481 * @returns created token object1482 */1483 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1484 const creationResult = await this.helper.executeExtrinsic(1485 signer,1486 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1487 refungible: {1488 pieces: data.pieces,1489 properties: data.properties,1490 },1491 }],1492 true,1493 );1494 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1495 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1496 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1497 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1498 }14991500 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1501 throw Error('Not implemented');1502 const creationResult = await this.helper.executeExtrinsic(1503 signer,1504 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1505 true, // `Unable to mint RFT tokens for ${label}`,1506 );1507 const collection = this.getCollectionObject(collectionId);1508 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1509 }15101511 /**1512 * Mint multiple RFT tokens with one owner1513 * @param signer keyring of signer1514 * @param collectionId ID of collection1515 * @param owner tokens owner1516 * @param tokens array of tokens with properties and pieces1517 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1518 * @returns array of newly created RFT tokens1519 */1520 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1521 const rawTokens = [];1522 for (const token of tokens) {1523 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1524 rawTokens.push(raw);1525 }1526 const creationResult = await this.helper.executeExtrinsic(1527 signer,1528 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1529 true,1530 );1531 const collection = this.getCollectionObject(collectionId);1532 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1533 }15341535 /**1536 * Destroys a concrete instance of RFT.1537 * @param signer keyring of signer1538 * @param collectionId ID of collection1539 * @param tokenId ID of token1540 * @param amount number of pieces to be burnt1541 * @example burnToken(aliceKeyring, 10, 5);1542 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1543 */1544 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1545 return await super.burnToken(signer, collectionId, tokenId, amount);1546 }15471548 /**1549 * Set, change, or remove approved address to transfer the ownership of the RFT.1550 * 1551 * @param signer keyring of signer1552 * @param collectionId ID of collection1553 * @param tokenId ID of token1554 * @param toAddressObj address to approve1555 * @param amount number of pieces to be approved1556 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1557 * @returns true if the token success, otherwise false1558 */1559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1561 }15621563 /**1564 * Get total number of pieces1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @example getTokenTotalPieces(10, 5);1568 * @returns number of pieces1569 */1570 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1571 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1572 }15731574 /**1575 * Change number of token pieces. Signer must be the owner of all token pieces.1576 * @param signer keyring of signer1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param amount new number of pieces1580 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1581 * @returns true if the repartion was success, otherwise false1582 */1583 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1584 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1585 const repartitionResult = await this.helper.executeExtrinsic(1586 signer,1587 'api.tx.unique.repartition', [collectionId, tokenId, amount],1588 true,1589 );1590 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1591 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1592 }1593}159415951596class FTGroup extends CollectionGroup {1597 /**1598 * Get collection object1599 * @param collectionId ID of collection1600 * @example getCollectionObject(2);1601 * @returns instance of UniqueFTCollection1602 */1603 getCollectionObject(collectionId: number): UniqueFTCollection {1604 return new UniqueFTCollection(collectionId, this.helper);1605 }16061607 /**1608 * Mint new fungible collection1609 * @param signer keyring of signer1610 * @param collectionOptions Collection options1611 * @param decimalPoints number of token decimals 1612 * @example1613 * mintCollection(aliceKeyring, {1614 * name: 'New',1615 * description: 'New collection',1616 * tokenPrefix: 'NEW',1617 * }, 18)1618 * @returns newly created fungible collection1619 */1620 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1621 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1622 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1623 collectionOptions.mode = {fungible: decimalPoints};1624 for (const key of ['name', 'description', 'tokenPrefix']) {1625 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);1626 }1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createCollectionEx', [collectionOptions],1630 true,1631 );1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1633 }16341635 /**1636 * Mint tokens1637 * @param signer keyring of signer1638 * @param collectionId ID of collection1639 * @param owner address owner of new tokens1640 * @param amount amount of tokens to be meanted1641 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1642 * @returns ```true``` if extrinsic success, otherwise ```false``` 1643 */1644 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1645 const creationResult = await this.helper.executeExtrinsic(1646 signer,1647 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1648 fungible: {1649 value: amount,1650 },1651 }],1652 true, // `Unable to mint fungible tokens for ${label}`,1653 );1654 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1655 }16561657 /**1658 * Mint multiple Fungible tokens with one owner1659 * @param signer keyring of signer1660 * @param collectionId ID of collection1661 * @param owner tokens owner1662 * @param tokens array of tokens with properties and pieces1663 * @returns ```true``` if extrinsic success, otherwise ```false``` 1664 */1665 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1666 const rawTokens = [];1667 for (const token of tokens) {1668 const raw = {Fungible: {Value: token.value}};1669 rawTokens.push(raw);1670 }1671 const creationResult = await this.helper.executeExtrinsic(1672 signer,1673 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1674 true,1675 );1676 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1677 }16781679 /**1680 * Get the top 10 owners with the largest balance for the Fungible collection 1681 * @param collectionId ID of collection1682 * @example getTop10Owners(10);1683 * @returns array of ```ICrossAccountId```1684 */1685 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1686 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1687 }16881689 /**1690 * Get account balance1691 * @param collectionId ID of collection1692 * @param addressObj address of owner1693 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1694 * @returns amount of fungible tokens owned by address1695 */1696 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1697 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1698 }16991700 /**1701 * Transfer tokens to address1702 * @param signer keyring of signer1703 * @param collectionId ID of collection1704 * @param toAddressObj address recipient1705 * @param amount amount of tokens to be sent1706 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1707 * @returns ```true``` if extrinsic success, otherwise ```false``` 1708 */1709 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1710 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1711 }17121713 /**1714 * Transfer some tokens on behalf of the owner.1715 * @param signer keyring of signer1716 * @param collectionId ID of collection1717 * @param fromAddressObj address on behalf of which tokens will be sent1718 * @param toAddressObj address where token to be sent1719 * @param amount number of tokens to be sent1720 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1721 * @returns ```true``` if extrinsic success, otherwise ```false``` 1722 */1723 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1724 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1725 }17261727 /**1728 * Destroy some amount of tokens1729 * @param signer keyring of signer1730 * @param collectionId ID of collection1731 * @param amount amount of tokens to be destroyed1732 * @example burnTokens(aliceKeyring, 10, 1000n);1733 * @returns ```true``` if extrinsic success, otherwise ```false``` 1734 */1735 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1736 return (await super.burnToken(signer, collectionId, 0, amount)).success;1737 }17381739 /**1740 * Burn some tokens on behalf of the owner.1741 * @param signer keyring of signer1742 * @param collectionId ID of collection1743 * @param fromAddressObj address on behalf of which tokens will be burnt1744 * @param amount amount of tokens to be burnt1745 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1746 * @returns ```true``` if extrinsic success, otherwise ```false``` 1747 */1748 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1749 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1750 }17511752 /**1753 * Get total collection supply1754 * @param collectionId 1755 * @returns 1756 */1757 async getTotalPieces(collectionId: number): Promise<bigint> {1758 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1759 }17601761 /**1762 * Set, change, or remove approved address to transfer tokens.1763 * 1764 * @param signer keyring of signer1765 * @param collectionId ID of collection1766 * @param toAddressObj address to be approved1767 * @param amount amount of tokens to be approved1768 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1769 * @returns ```true``` if extrinsic success, otherwise ```false``` 1770 */1771 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1772 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1773 }17741775 /**1776 * Get amount of fungible tokens approved to transfer1777 * @param collectionId ID of collection1778 * @param fromAddressObj owner of tokens1779 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1780 * @returns number of tokens approved for the transfer1781 */1782 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1783 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1784 }1785}178617871788class ChainGroup extends HelperGroup {1789 /**1790 * Get system properties of a chain1791 * @example getChainProperties();1792 * @returns ss58Format, token decimals, and token symbol1793 */1794 getChainProperties(): IChainProperties {1795 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1796 return {1797 ss58Format: properties.ss58Format.toJSON(),1798 tokenDecimals: properties.tokenDecimals.toJSON(),1799 tokenSymbol: properties.tokenSymbol.toJSON(),1800 };1801 }18021803 /**1804 * Get chain header1805 * @example getLatestBlockNumber();1806 * @returns the number of the last block1807 */1808 async getLatestBlockNumber(): Promise<number> {1809 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1810 }18111812 /**1813 * Get block hash by block number1814 * @param blockNumber number of block1815 * @example getBlockHashByNumber(12345);1816 * @returns hash of a block1817 */1818 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1819 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1820 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1821 return blockHash;1822 }18231824 // TODO add docs1825 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1826 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1827 if (!blockHash) return null;1828 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1829 }18301831 /**1832 * Get account nonce1833 * @param address substrate address1834 * @example getNonce("5GrwvaEF5zXb26Fz...");1835 * @returns number, account's nonce1836 */1837 async getNonce(address: TSubstrateAccount): Promise<number> {1838 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1839 }1840}184118421843class BalanceGroup extends HelperGroup {1844 /**1845 * Representation of the native token in the smallest unit1846 * @example getOneTokenNominal()1847 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1848 */1849 getOneTokenNominal(): bigint {1850 const chainProperties = this.helper.chain.getChainProperties();1851 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1852 }18531854 /**1855 * Get substrate address balance1856 * @param address substrate address1857 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1858 * @returns amount of tokens on address1859 */1860 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1861 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1862 }18631864 /**1865 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1866 * @param address substrate address1867 * @returns 1868 */1869 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1870 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1871 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1872 }18731874 /**1875 * Get ethereum address balance1876 * @param address ethereum address1877 * @example getEthereum("0x9F0583DbB855d...")1878 * @returns amount of tokens on address1879 */1880 async getEthereum(address: TEthereumAccount): Promise<bigint> {1881 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1882 }18831884 /**1885 * Transfer tokens to substrate address1886 * @param signer keyring of signer1887 * @param address substrate address of a recipient1888 * @param amount amount of tokens to be transfered1889 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1890 * @returns ```true``` if extrinsic success, otherwise ```false```1891 */1892 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1893 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}`*/);18941895 let transfer = {from: null, to: null, amount: 0n} as any;1896 result.result.events.forEach(({event: {data, method, section}}) => {1897 if ((section === 'balances') && (method === 'Transfer')) {1898 transfer = {1899 from: this.helper.address.normalizeSubstrate(data[0]),1900 to: this.helper.address.normalizeSubstrate(data[1]),1901 amount: BigInt(data[2]),1902 };1903 }1904 });1905 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1906 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1907 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1908 return isSuccess;1909 }1910}191119121913class AddressGroup extends HelperGroup {1914 /**1915 * Normalizes the address to the specified ss58 format, by default ```42```.1916 * @param address substrate address1917 * @param ss58Format format for address conversion, by default ```42```1918 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1919 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1920 */1921 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1922 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1923 }19241925 /**1926 * Get address in the connected chain format1927 * @param address substrate address1928 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1929 * @returns address in chain format1930 */1931 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1932 const info = this.helper.chain.getChainProperties();1933 return encodeAddress(decodeAddress(address), info.ss58Format);1934 }19351936 /**1937 * Get substrate mirror of an ethereum address1938 * @param ethAddress ethereum address1939 * @param toChainFormat false for normalized account1940 * @example ethToSubstrate('0x9F0583DbB855d...')1941 * @returns substrate mirror of a provided ethereum address1942 */1943 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1944 if(!toChainFormat) return evmToAddress(ethAddress);1945 const info = this.helper.chain.getChainProperties();1946 return evmToAddress(ethAddress, info.ss58Format);1947 }19481949 /**1950 * Get ethereum mirror of a substrate address1951 * @param subAddress substrate account1952 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1953 * @returns ethereum mirror of a provided substrate address1954 */1955 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1956 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1957 }1958}19591960class StakingGroup extends HelperGroup {1961 /**1962 * Stake tokens for App Promotion1963 * @param signer keyring of signer1964 * @param amountToStake amount of tokens to stake1965 * @param label extra label for log1966 * @returns1967 */1968 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {1969 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;1970 const stakeResult = await this.helper.executeExtrinsic(1971 signer, 'api.tx.appPromotion.stake',1972 [amountToStake], true,1973 );1974 // TODO extract info from stakeResult1975 return true;1976 }19771978 /**1979 * Unstake tokens for App Promotion1980 * @param signer keyring of signer1981 * @param amountToUnstake amount of tokens to unstake1982 * @param label extra label for log1983 * @returns 1984 */1985 async unstake(signer: TSigner, label?: string): Promise<boolean> {1986 if(typeof label === 'undefined') label = `${signer.address}`;1987 const unstakeResult = await this.helper.executeExtrinsic(1988 signer, 'api.tx.appPromotion.unstake', 1989 [], true,1990 );1991 // TODO extract info from unstakeResult1992 return true;1993 }19941995 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {1996 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();1997 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();1998 }19992000 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2001 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();2002 }20032004 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2005 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2006 }20072008 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2009 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2010 }2011 2012 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2013 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2014 }2015}20162017export class UniqueHelper extends ChainHelperBase {2018 chain: ChainGroup;2019 balance: BalanceGroup;2020 address: AddressGroup;2021 collection: CollectionGroup;2022 nft: NFTGroup;2023 rft: RFTGroup;2024 ft: FTGroup;2025 staking: StakingGroup;20262027 constructor(logger?: ILogger) {2028 super(logger);2029 this.chain = new ChainGroup(this);2030 this.balance = new BalanceGroup(this);2031 this.address = new AddressGroup(this);2032 this.collection = new CollectionGroup(this);2033 this.nft = new NFTGroup(this);2034 this.rft = new RFTGroup(this);2035 this.ft = new FTGroup(this);2036 this.staking = new StakingGroup(this);2037 } 2038}203920402041class UniqueCollectionBase {2042 helper: UniqueHelper;2043 collectionId: number;20442045 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2046 this.collectionId = collectionId;2047 this.helper = uniqueHelper;2048 }20492050 async getData() {2051 return await this.helper.collection.getData(this.collectionId);2052 }20532054 async getLastTokenId() {2055 return await this.helper.collection.getLastTokenId(this.collectionId);2056 }20572058 async isTokenExists(tokenId: number) {2059 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2060 }20612062 async getAdmins() {2063 return await this.helper.collection.getAdmins(this.collectionId);2064 }20652066 async getAllowList() {2067 return await this.helper.collection.getAllowList(this.collectionId);2068 }20692070 async getEffectiveLimits() {2071 return await this.helper.collection.getEffectiveLimits(this.collectionId);2072 }20732074 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2075 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2076 }20772078 async confirmSponsorship(signer: TSigner) {2079 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2080 }20812082 async setLimits(signer: TSigner, limits: ICollectionLimits) {2083 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2084 }20852086 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2087 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2088 }20892090 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2091 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2092 }20932094 async enableAllowList(signer: TSigner, value = true/*: 'Normal' | 'AllowList' = 'AllowList'*/) {2095 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});2096 }20972098 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2099 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2100 }21012102 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2103 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2104 }21052106 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2107 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2108 }21092110 async setProperties(signer: TSigner, properties: IProperty[]) {2111 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2112 }21132114 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2115 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2116 }21172118 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2119 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2120 }21212122 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2123 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2124 }21252126 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2127 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2128 }21292130 async disableNesting(signer: TSigner) {2131 return await this.helper.collection.disableNesting(signer, this.collectionId);2132 }21332134 async burn(signer: TSigner) {2135 return await this.helper.collection.burn(signer, this.collectionId);2136 }2137}213821392140class UniqueNFTCollection extends UniqueCollectionBase {2141 getTokenObject(tokenId: number) {2142 return new UniqueNFTToken(tokenId, this);2143 }21442145 async getTokensByAddress(addressObj: ICrossAccountId) {2146 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2147 }21482149 async getToken(tokenId: number, blockHashAt?: string) {2150 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2151 }21522153 async getTokenOwner(tokenId: number, blockHashAt?: string) {2154 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2155 }21562157 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2158 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2159 }21602161 async getTokenChildren(tokenId: number, blockHashAt?: string) {2162 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2163 }21642165 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2166 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2167 }21682169 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2170 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2171 }21722173 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2174 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2175 }21762177 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2178 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2179 }21802181 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2182 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2183 }21842185 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2186 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2187 }21882189 async burnToken(signer: TSigner, tokenId: number) {2190 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2191 }21922193 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2194 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2195 }21962197 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2198 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2199 }22002201 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2202 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2203 }22042205 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2206 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2207 }22082209 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2210 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2211 }2212}221322142215class UniqueRFTCollection extends UniqueCollectionBase {2216 getTokenObject(tokenId: number) {2217 return new UniqueRFTToken(tokenId, this);2218 }22192220 async getTokensByAddress(addressObj: ICrossAccountId) {2221 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2222 }22232224 async getTop10TokenOwners(tokenId: number) {2225 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2226 }22272228 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2229 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2230 }22312232 async getTokenTotalPieces(tokenId: number) {2233 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2234 }22352236 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2237 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2238 }22392240 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2241 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2242 }22432244 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2245 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2246 }22472248 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2249 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2250 }22512252 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2253 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2254 }22552256 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2257 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2258 }22592260 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2261 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2262 }22632264 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2265 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2266 }22672268 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2269 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2270 }22712272 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2273 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2274 }22752276 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2277 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2278 }2279}228022812282class UniqueFTCollection extends UniqueCollectionBase {2283 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2284 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2285 }22862287 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2288 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2289 }22902291 async getBalance(addressObj: ICrossAccountId) {2292 return await this.helper.ft.getBalance(this.collectionId, addressObj);2293 }22942295 async getTop10Owners() {2296 return await this.helper.ft.getTop10Owners(this.collectionId);2297 }22982299 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2300 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2301 }23022303 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2304 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2305 }23062307 async burnTokens(signer: TSigner, amount=1n) {2308 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2309 }23102311 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2312 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2313 }23142315 async getTotalPieces() {2316 return await this.helper.ft.getTotalPieces(this.collectionId);2317 }23182319 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2320 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2321 }23222323 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2324 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2325 }2326}232723282329class UniqueTokenBase implements IToken {2330 collection: UniqueNFTCollection | UniqueRFTCollection;2331 collectionId: number;2332 tokenId: number;23332334 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2335 this.collection = collection;2336 this.collectionId = collection.collectionId;2337 this.tokenId = tokenId;2338 }23392340 async getNextSponsored(addressObj: ICrossAccountId) {2341 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2342 }23432344 async setProperties(signer: TSigner, properties: IProperty[]) {2345 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2346 }23472348 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2349 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2350 }2351}235223532354class UniqueNFTToken extends UniqueTokenBase {2355 collection: UniqueNFTCollection;23562357 constructor(tokenId: number, collection: UniqueNFTCollection) {2358 super(tokenId, collection);2359 this.collection = collection;2360 }23612362 async getData(blockHashAt?: string) {2363 return await this.collection.getToken(this.tokenId, blockHashAt);2364 }23652366 async getOwner(blockHashAt?: string) {2367 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2368 }23692370 async getTopmostOwner(blockHashAt?: string) {2371 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2372 }23732374 async getChildren(blockHashAt?: string) {2375 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2376 }23772378 async nest(signer: TSigner, toTokenObj: IToken) {2379 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2380 }23812382 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2383 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2384 }23852386 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2387 return await this.collection.transferToken(signer, this.tokenId, addressObj);2388 }23892390 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2391 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2392 }23932394 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2395 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2396 }23972398 async isApproved(toAddressObj: ICrossAccountId) {2399 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2400 }24012402 async burn(signer: TSigner) {2403 return await this.collection.burnToken(signer, this.tokenId);2404 }2405}24062407class UniqueRFTToken extends UniqueTokenBase {2408 collection: UniqueRFTCollection;24092410 constructor(tokenId: number, collection: UniqueRFTCollection) {2411 super(tokenId, collection);2412 this.collection = collection;2413 }24142415 async getTop10Owners() {2416 return await this.collection.getTop10TokenOwners(this.tokenId);2417 }24182419 async getBalance(addressObj: ICrossAccountId) {2420 return await this.collection.getTokenBalance(this.tokenId, addressObj);2421 }24222423 async getTotalPieces() {2424 return await this.collection.getTokenTotalPieces(this.tokenId);2425 }24262427 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2428 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2429 }24302431 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2432 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2433 }24342435 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2436 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2437 }24382439 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2440 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2441 }24422443 async repartition(signer: TSigner, amount: bigint) {2444 return await this.collection.repartitionToken(signer, this.tokenId, amount);2445 }24462447 async burn(signer: TSigner, amount=1n) {2448 return await this.collection.burnToken(signer, this.tokenId, amount);2449 }2450}