difftreelog
Merge pull request #632 from UniqueNetwork/tests/playgrounds-cleanup
in: master
Tests/playgrounds cleanup
69 files changed
tests/src/.outdated/addToContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/addToContractAllowList.test.ts
+++ b/tests/src/.outdated/addToContractAllowList.test.ts
@@ -17,12 +17,8 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import {
- deployFlipper,
-} from '../util/contracthelpers';
-import {
- getGenericResult,
-} from '../util/helpers';
+import {deployFlipper} from '../deprecated-helpers/contracthelpers';
+import {getGenericResult} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/.outdated/contracts.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/contracts.test.ts
+++ b/tests/src/.outdated/contracts.test.ts
@@ -19,11 +19,7 @@
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
import fs from 'fs';
import {Abi, ContractPromise as Contract} from '@polkadot/api-contract';
-import {
- deployFlipper,
- getFlipValue,
- deployTransferContract,
-} from '../util/contracthelpers';
+import {deployFlipper, getFlipValue, deployTransferContract} from '../deprecated-helpers/contracthelpers';
import {
addToAllowListExpectSuccess,
@@ -37,7 +33,7 @@
isAllowlisted,
transferFromExpectSuccess,
getTokenOwner,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
tests/src/.outdated/enableContractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/enableContractSponsoring.test.ts
+++ b/tests/src/.outdated/enableContractSponsoring.test.ts
@@ -18,13 +18,13 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import usingApi from '../substrate/substrate-api';
-import {deployFlipper, getFlipValue, toggleFlipValueExpectSuccess} from '../util/contracthelpers';
+import {deployFlipper, getFlipValue, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
import {
enableContractSponsoringExpectFailure,
enableContractSponsoringExpectSuccess,
findUnusedAddress,
setContractSponsoringRateLimitExpectSuccess,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/.outdated/eth/scheduling.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/eth/scheduling.test.ts
@@ -0,0 +1,59 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from '../../deprecated-helpers/eth/helpers';
+import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../../deprecated-helpers/helpers';
+
+// TODO mrshiposha update this test in #581
+describe.skip('Scheduing EVM smart contracts', () => {
+ before(async function() {
+ await requirePallets(this, [Pallets.Scheduler]);
+ });
+
+ itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3, privateKeyWrapper}) => {
+ const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const flipper = await deployFlipper(web3, deployer);
+ const initialValue = await flipper.methods.getValue().call();
+ const alice = privateKeyWrapper('//Alice');
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+ {
+ const tx = api.tx.evm.call(
+ subToEth(alice.address),
+ flipper.options.address,
+ flipper.methods.flip().encodeABI(),
+ '0',
+ GAS_ARGS.gas,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const waitForBlocks = 4;
+ const periodBlocks = 2;
+
+ await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+
+ await waitNewBlocks(waitForBlocks - 1);
+ expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+
+ await waitNewBlocks(periodBlocks);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+ }
+ });
+});
tests/src/.outdated/overflow.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/overflow.test.ts
+++ b/tests/src/.outdated/overflow.test.ts
@@ -18,7 +18,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import usingApi from '../substrate/substrate-api';
-import {approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getBalance, transferExpectFailure, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX} from '../util/helpers';
+import {approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getBalance, transferExpectFailure, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/.outdated/removeFromContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/removeFromContractAllowList.test.ts
+++ b/tests/src/.outdated/removeFromContractAllowList.test.ts
@@ -15,8 +15,8 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import usingApi from '../substrate/substrate-api';
-import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../util/contracthelpers';
-import {addToContractAllowListExpectSuccess, isAllowlistedInContract, removeFromContractAllowListExpectFailure, removeFromContractAllowListExpectSuccess, toggleContractAllowlistExpectSuccess} from '../util/helpers';
+import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
+import {addToContractAllowListExpectSuccess, isAllowlistedInContract, removeFromContractAllowListExpectFailure, removeFromContractAllowListExpectSuccess, toggleContractAllowlistExpectSuccess} from '../deprecated-helpers/helpers';
import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
tests/src/.outdated/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/scheduler.test.ts
+++ b/tests/src/.outdated/scheduler.test.ts
@@ -39,7 +39,7 @@
getFreeBalance,
confirmSponsorshipByKeyExpectSuccess,
scheduleExpectFailure,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
import {IKeyringPair} from '@polkadot/types/types';
chai.use(chaiAsPromised);
tests/src/.outdated/setChainLimits.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/setChainLimits.test.ts
+++ b/tests/src/.outdated/setChainLimits.test.ts
@@ -21,7 +21,7 @@
addCollectionAdminExpectSuccess,
setChainLimitsExpectFailure,
IChainLimits,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
// todo:playgrounds skipped ~ postponed
describe.skip('Negative Integration Test setChainLimits', () => {
tests/src/.outdated/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/setContractSponsoringRateLimit.test.ts
+++ b/tests/src/.outdated/setContractSponsoringRateLimit.test.ts
@@ -17,13 +17,13 @@
import {IKeyringPair} from '@polkadot/types/types';
import usingApi from '../substrate/substrate-api';
import waitNewBlocks from '../substrate/wait-new-blocks';
-import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../util/contracthelpers';
+import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
import {
enableContractSponsoringExpectSuccess,
findUnusedAddress,
setContractSponsoringRateLimitExpectFailure,
setContractSponsoringRateLimitExpectSuccess,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
// todo:playgrounds skipped~postponed test
describe.skip('Integration Test setContractSponsoringRateLimit', () => {
tests/src/.outdated/toggleContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/toggleContractAllowList.test.ts
+++ b/tests/src/.outdated/toggleContractAllowList.test.ts
@@ -20,10 +20,10 @@
import {
deployFlipper,
getFlipValue,
-} from '../util/contracthelpers';
+} from '../deprecated-helpers/contracthelpers';
import {
getGenericResult,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/.outdated/xcmTransfer.test.tsdiffbeforeafterboth--- a/tests/src/.outdated/xcmTransfer.test.ts
+++ b/tests/src/.outdated/xcmTransfer.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult} from '../util/helpers';
+import {getGenericResult} from '../deprecated-helpers/helpers';
import waitNewBlocks from '../substrate/wait-new-blocks';
import getBalance from '../substrate/get-balance';
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -110,7 +110,7 @@
const [alice, ...accounts] = await helper.arrange.createAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
+ const chainAdminLimit = (helper.getApi().consts.common.collectionAdminsLimit as any).toNumber();
expect(chainAdminLimit).to.be.equal(5);
for (let i = 0; i < chainAdminLimit; i++) {
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -15,17 +15,11 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {
- normalizeAccountId,
- getModuleNames,
- Pallets,
-} from './util/helpers';
-import {itSub, usingPlaygrounds} from './util/playgrounds';
+import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
import {encodeAddress} from '@polkadot/util-crypto';
import {stringToU8a} from '@polkadot/util';
-import {SponsoringMode} from './eth/util/helpers';
import {DevUniqueHelper} from './util/playgrounds/unique.dev';
-import {itEth, expect} from './eth/util/playgrounds';
+import {itEth, expect, SponsoringMode} from './eth/util/playgrounds';
let alice: IKeyringPair;
let palletAdmin: IKeyringPair;
@@ -42,10 +36,11 @@
describe('App promotion', () => {
before(async function () {
await usingPlaygrounds(async (helper, privateKey) => {
- if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+ requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
alice = privateKey('//Alice');
palletAdmin = privateKey('//Charlie'); // TODO use custom address
- await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ const api = helper.getApi();
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
nominal = helper.balance.getOneTokenNominal();
await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
@@ -231,54 +226,59 @@
describe('admin adress', () => {
itSub('can be set by sudo only', async ({helper}) => {
+ const api = helper.getApi();
const nonAdmin = accounts.pop()!;
// nonAdmin can not set admin not from himself nor as a sudo
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
// Alice can
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
});
itSub('can be any valid CrossAccountId', async ({helper}) => {
// We are not going to set an eth address as a sponsor,
// but we do want to check, it doesn't break anything;
+ const api = helper.getApi();
const account = accounts.pop()!;
const ethAccount = helper.address.substrateToEth(account.address);
// Alice sets Ethereum address as a sudo. Then Substrate address back...
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
// ...It doesn't break anything;
const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
itSub('can be reassigned', async ({helper}) => {
+ const api = helper.getApi();
const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
- await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
});
});
describe('collection sponsoring', () => {
before(async function () {
await usingPlaygrounds(async (helper) => {
- const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
+ const api = helper.getApi();
+ const tx = api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
await helper.signTransaction(alice, tx);
});
});
itSub('should actually sponsor transactions', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));
const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
await token.transfer(tokenSender, {Substrate: receiver.address});
@@ -291,41 +291,44 @@
});
itSub('can not be set by non admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
});
itSub('should set pallet address as confirmed admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
// Can set sponsoring for collection without sponsor
const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with unconfirmed sponsor
const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with confirmed sponsor
const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
itSub('can be overwritten by collection owner', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
const collectionId = collection.collectionId;
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
// Collection limits still can be changed by the owner
expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
@@ -338,44 +341,48 @@
});
itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
+ const api = helper.getApi();
const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
});
itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
+ const api = helper.getApi();
const collectionOwner = accounts.pop()!;
// collection has never existed
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
// collection has been burned
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
await collection.burn(collectionOwner);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
});
describe('stopSponsoringCollection', () => {
- itSub('can not be called by non-admin', async ({helper}) => {
+ itSub('can not be called by non-admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
itSub('should set sponsoring as disabled', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
@@ -387,11 +394,12 @@
});
itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
+ const api = helper.getApi();
const collectionOwner = accounts.pop()!;
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
await collection.confirmSponsorship(collectionOwner);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
});
@@ -415,8 +423,8 @@
await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
substrate: palletAddress,
},
@@ -431,7 +439,7 @@
await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
// Contract is self sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -462,8 +470,8 @@
await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -482,7 +490,7 @@
await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
// contract still self-sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -505,7 +513,7 @@
await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
// Set promotion to the Flipper
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
// Caller calls Flipper
await flipper.methods.flip().send({from: caller});
@@ -536,8 +544,8 @@
await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
disabled: null,
});
@@ -717,7 +725,7 @@
// Wait while promotion period less than specified block, to avoid boundary cases
// 0 if this should be the beginning of the period.
async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {
- const relayBlockNumber = (await helper.api!.query.parachainSystem.validationData()).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
+ const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;
if (currentPeriodBlock > waitBlockLessThan) {
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -60,7 +60,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
});
@@ -275,7 +275,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
const transferTokenFromTx = async () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
await expect(transferTokenFromTx()).to.be.rejected;
@@ -328,7 +328,7 @@
itSub('1 for NFT', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTx = async () => helper.signTransaction(bob, helper.api?.tx.unique.approve({Substrate: charlie.address}, collectionId, tokenId, 2));
+ const approveTx = async () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
await expect(approveTx()).to.be.rejected;
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
});
tests/src/block-production.test.tsdiffbeforeafterboth--- a/tests/src/block-production.test.ts
+++ b/tests/src/block-production.test.ts
@@ -37,7 +37,7 @@
describe('Block Production smoke test', () => {
itSub('Node produces new blocks', async ({helper}) => {
- const blocks: number[] | undefined = await getBlocks(helper.api!);
+ const blocks: number[] | undefined = await getBlocks(helper.getApi());
expect(blocks[0]).to.be.lessThan(blocks[1]);
});
});
tests/src/calibrate.tsdiffbeforeafterboth--- a/tests/src/calibrate.ts
+++ b/tests/src/calibrate.ts
@@ -1,11 +1,8 @@
-import {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
-import Web3 from 'web3';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, recordEthFee, usingWeb3} from './eth/util/helpers';
-import usingApi, {executeTransaction} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, UNIQUE, waitNewBlocks} from './util/helpers';
-import nonFungibleAbi from './eth/nonFungibleAbi.json';
+import {usingEthPlaygrounds, EthUniqueHelper} from './eth/util/playgrounds';
+
+
function linearRegression(points: { x: bigint, y: bigint }[]) {
let sumxy = 0n;
let sumx = 0n;
@@ -59,32 +56,33 @@
}).reduce((a, b) => a + b, 0n) / BigInt(points.length));
}
-async function calibrateWeightToFee(api: ApiPromise, privateKey: (account: string) => IKeyringPair) {
+async function calibrateWeightToFee(helper: EthUniqueHelper, privateKey: (account: string) => IKeyringPair) {
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const dataPoints = [];
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
- console.log(`Original price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE)} UNQ`);
+ console.log(`Original price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
+ const api = helper.getApi();
const defaultCoeff = (api.consts.configuration.defaultWeightToFeeCoefficient as any).toBigInt();
for (let i = -5; i < 5; i++) {
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(defaultCoeff + defaultCoeff / 1000n * BigInt(i))));
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(defaultCoeff + defaultCoeff / 1000n * BigInt(i))));
const coefficient = (await api.query.configuration.weightToFeeCoefficientOverride() as any).toBigInt();
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
const transferPrice = aliceBalanceBefore - aliceBalanceAfter;
@@ -94,52 +92,53 @@
// console.log(`Error: ${error(dataPoints, x => a*x+b)}`);
- const perfectValue = a * UNIQUE / 10n + b;
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(perfectValue.toString())));
+ const perfectValue = a * helper.balance.getOneTokenNominal() / 10n + b;
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(perfectValue.toString())));
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
- console.log(`Calibrated price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE)} UNQ`);
+ console.log(`Calibrated price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
}
-async function calibrateMinGasPrice(api: ApiPromise, web3: Web3, privateKey: (account: string) => IKeyringPair) {
+async function calibrateMinGasPrice(helper: EthUniqueHelper, privateKey: (account: string) => IKeyringPair) {
const alice = privateKey('//Alice');
- const caller = await createEthAccountWithBalance(api, web3, privateKey);
- const receiver = createEthAccount(web3);
+ const caller = await helper.eth.createAccountWithBalance(alice);
+ const receiver = helper.eth.createAccount();
const dataPoints = [];
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS}));
- console.log(`Original price: ${Number(cost) / Number(UNIQUE)} UNQ`);
+ console.log(`Original price: ${Number(cost) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
+ const api = helper.getApi();
const defaultCoeff = (api.consts.configuration.defaultMinGasPrice as any).toBigInt();
for (let i = -8; i < 8; i++) {
const gasPrice = defaultCoeff + defaultCoeff / 100000n * BigInt(i);
const gasPriceStr = '0x' + gasPrice.toString(16);
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(gasPrice)));
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(gasPrice)));
const coefficient = (await api.query.configuration.minGasPriceOverride() as any).toBigInt();
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, gasPrice: gasPriceStr, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const transferPrice = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const transferPrice = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gasPrice: gasPriceStr, gas: helper.eth.DEFAULT_GAS}));
dataPoints.push({x: transferPrice, y: coefficient});
}
@@ -149,34 +148,30 @@
// console.log(`Error: ${error(dataPoints, x => a*x+b)}`);
// * 0.15 = * 10000 / 66666
- const perfectValue = a * UNIQUE * 1000000n / 6666666n + b;
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(perfectValue.toString())));
+ const perfectValue = a * helper.balance.getOneTokenNominal() * 1000000n / 6666666n + b;
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(perfectValue.toString())));
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS}));
- console.log(`Calibrated price: ${Number(cost) / Number(UNIQUE)} UNQ`);
+ console.log(`Calibrated price: ${Number(cost) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
}
(async () => {
- await usingApi(async (api, privateKey) => {
+ await usingEthPlaygrounds(async (helper: EthUniqueHelper, privateKey) => {
// Second run slightly reduces error sometimes, as price line is not actually straight, this is a curve
- await calibrateWeightToFee(api, privateKey);
- await calibrateWeightToFee(api, privateKey);
+ await calibrateWeightToFee(helper, privateKey);
+ await calibrateWeightToFee(helper, privateKey);
- await usingWeb3(async web3 => {
- await calibrateMinGasPrice(api, web3, privateKey);
- await calibrateMinGasPrice(api, web3, privateKey);
- });
-
- await api.disconnect();
+ await calibrateMinGasPrice(helper, privateKey);
+ await calibrateMinGasPrice(helper, privateKey);
});
})();
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -178,13 +178,12 @@
tokenPrefix: 'COL',
}, 0);
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx',[collection.collectionId, {
Fungible: new Map([
[JSON.stringify({Substrate: alice.address}), 50],
[JSON.stringify({Substrate: bob.address}), 100],
]),
- }));
+ }], true);
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(50n);
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(100n);
@@ -200,8 +199,7 @@
],
});
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleOwners: {
users: new Map([
[JSON.stringify({Substrate: alice.address}), 1],
@@ -211,7 +209,7 @@
{key: 'k', value: 'v'},
],
},
- }));
+ }], true);
const tokenId = await collection.getLastTokenId();
expect(tokenId).to.be.equal(1);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
@@ -228,9 +226,7 @@
],
});
- const api = helper.api;
-
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleItems: [
{
user: {Substrate: alice.address}, pieces: 1,
@@ -245,7 +241,7 @@
],
},
],
- }));
+ }], true);
expect(await collection.getLastTokenId()).to.be.equal(2);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -29,7 +29,7 @@
/*eslint no-async-promise-executor: "off"*/
function skipInflationBlock(api: ApiPromise): Promise<void> {
const promise = new Promise<void>(async (resolve) => {
- const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();
+ const blockInterval = api.consts.inflation.inflationBlockInterval.toNumber();
const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
const currentBlock = head.number.toNumber();
if (currentBlock % blockInterval < blockInterval - 10) {
@@ -56,21 +56,21 @@
});
itSub('Total issuance does not change', async ({helper}) => {
- const api = helper.api!;
+ const api = helper.getApi();
await skipInflationBlock(api);
await helper.wait.newBlocks(1);
- const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
+ const totalBefore = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();
await helper.balance.transferToSubstrate(alice, bob.address, 1n);
- const totalAfter = (await api.query.balances.totalIssuance()).toBigInt();
+ const totalAfter = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();
expect(totalAfter).to.be.equal(totalBefore);
});
itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -89,7 +89,7 @@
});
itSub('Treasury balance increased by failed tx fee', async ({helper}) => {
- const api = helper.api!;
+ const api = helper.getApi();
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -107,7 +107,7 @@
});
itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -125,7 +125,7 @@
itSub('Fees are sane', async ({helper}) => {
const unique = helper.balance.getOneTokenNominal();
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -140,7 +140,7 @@
});
itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const collection = await helper.nft.mintCollection(alice, {
tests/src/deprecated-helpers/contracthelpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/contracthelpers.ts
@@ -0,0 +1,114 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import fs from 'fs';
+import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
+import {IKeyringPair} from '@polkadot/types/types';
+import {ApiPromise} from '@polkadot/api';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+import {findUnusedAddress, getGenericResult} from './helpers';
+
+const value = 0;
+const gasLimit = '200000000000';
+const endowment = '100000000000000000';
+
+/* eslint no-async-promise-executor: "off" */
+function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {
+ return new Promise<Contract>(async (resolve) => {
+ const unsub = await (code as any)
+ .tx[constructor]({value: endowment, gasLimit}, ...args)
+ .signAndSend(alice, (result: any) => {
+ if (result.status.isInBlock || result.status.isFinalized) {
+ // here we have an additional field in the result, containing the blueprint
+ resolve((result as any).contract);
+ unsub();
+ }
+ });
+ });
+}
+
+async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
+ // Find unused address
+ const deployer = await findUnusedAddress(api, privateKeyWrapper);
+
+ // Transfer balance to it
+ const alice = privateKeyWrapper('//Alice');
+ const amount = BigInt(endowment) + 10n**15n;
+ const tx = api.tx.balances.transfer(deployer.address, amount);
+ await submitTransactionAsync(alice, tx);
+
+ return deployer;
+}
+
+export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
+ const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
+ const abi = new Abi(metadata);
+
+ const deployer = await prepareDeployer(api, privateKeyWrapper);
+
+ const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
+
+ const code = new CodePromise(api, abi, wasm);
+
+ const contract = (await deployContract(deployer, code, 'new', true)) as Contract;
+
+ const initialGetResponse = await getFlipValue(contract, deployer);
+ expect(initialGetResponse).to.be.true;
+
+ return [contract, deployer];
+}
+
+export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
+ const result = await contract.query.get(deployer.address, {value, gasLimit});
+
+ if(!result.result.isOk) {
+ throw 'Failed to get flipper value';
+ }
+ return (result.result.asOk.data[0] == 0x00) ? false : true;
+}
+
+export async function toggleFlipValueExpectSuccess(sender: IKeyringPair, contract: Contract) {
+ const tx = contract.tx.flip({value, gasLimit});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+}
+
+export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
+ const tx = contract.tx.flip({value, gasLimit});
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+}
+
+export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
+ const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
+ const abi = new Abi(metadata);
+
+ const deployer = await prepareDeployer(api, privateKeyWrapper);
+
+ const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
+
+ const code = new CodePromise(api, abi, wasm);
+
+ const contract = await deployContract(deployer, code);
+
+ return [contract, deployer];
+}
tests/src/deprecated-helpers/eth/helpers.d.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/eth/helpers.d.ts
@@ -0,0 +1,17 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+declare module 'solc';
\ No newline at end of file
tests/src/deprecated-helpers/eth/helpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/eth/helpers.ts
@@ -0,0 +1,451 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+/// <reference path="helpers.d.ts" />
+
+import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';
+import {expect} from 'chai';
+import * as solc from 'solc';
+import Web3 from 'web3';
+import config from '../../config';
+import getBalance from '../../substrate/get-balance';
+import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
+import waitNewBlocks from '../../substrate/wait-new-blocks';
+import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../helpers';
+import collectionHelpersAbi from '../../eth/collectionHelpersAbi.json';
+import fungibleAbi from '../../eth/fungibleAbi.json';
+import nonFungibleAbi from '../../eth/nonFungibleAbi.json';
+import refungibleAbi from '../../eth/reFungibleAbi.json';
+import refungibleTokenAbi from '../../eth/reFungibleTokenAbi.json';
+import contractHelpersAbi from '../../eth/util/contractHelpersAbi.json';
+
+export const GAS_ARGS = {gas: 2500000};
+
+export enum SponsoringMode {
+ Disabled = 0,
+ Allowlisted = 1,
+ Generous = 2,
+}
+
+let web3Connected = false;
+export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {
+ if (web3Connected) throw new Error('do not nest usingWeb3 calls');
+ web3Connected = true;
+
+ const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);
+ const web3 = new Web3(provider);
+
+ try {
+ return await cb(web3);
+ } finally {
+ // provider.disconnect(3000, 'normal disconnect');
+ provider.connection.close();
+ web3Connected = false;
+ }
+}
+
+function encodeIntBE(v: number): number[] {
+ if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
+ return [
+ v >> 24,
+ (v >> 16) & 0xff,
+ (v >> 8) & 0xff,
+ v & 0xff,
+ ];
+}
+
+export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
+ const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = collectionIdFromAddress(collectionIdAddress);
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ return {collectionIdAddress, collectionId, collection};
+}
+
+export function collectionIdToAddress(collection: number): string {
+ const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
+ ...encodeIntBE(collection),
+ ]);
+ return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+export function collectionIdFromAddress(address: string): number {
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return Number('0x' + address.substring(address.length - 8));
+}
+
+export function normalizeAddress(address: string): string {
+ return '0x' + address.substring(address.length - 40);
+}
+
+export function tokenIdToAddress(collection: number, token: number): string {
+ const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+ ...encodeIntBE(collection),
+ ...encodeIntBE(token),
+ ]);
+ return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+
+export function tokenIdFromAddress(address: string) {
+ 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)),
+ };
+}
+
+export function tokenIdToCross(collection: number, token: number): CrossAccountId {
+ return {
+ Ethereum: tokenIdToAddress(collection, token),
+ };
+}
+
+export function createEthAccount(web3: Web3) {
+ const account = web3.eth.accounts.create();
+ web3.eth.accounts.wallet.add(account.privateKey);
+ return account.address;
+}
+
+export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {
+ const alice = privateKeyWrapper('//Alice');
+ const account = createEthAccount(web3);
+ await transferBalanceToEth(api, alice, account);
+
+ return account;
+}
+
+export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
+ const tx = api.tx.balances.transfer(evmToAddress(target), amount);
+ const events = await submitTransactionAsync(source, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+}
+
+export async function createRFTCollection(api: ApiPromise, web3: Web3, owner: string) {
+ const collectionHelper = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelper.methods
+ .createRFTCollection('A', 'B', 'C')
+ .send({value: Number(2n * UNIQUE)});
+ return await getCollectionAddressFromResult(api, result);
+}
+
+
+export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
+ const collectionHelper = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelper.methods
+ .createNonfungibleCollection('A', 'B', 'C')
+ .send({value: Number(2n * UNIQUE)});
+ return await getCollectionAddressFromResult(api, result);
+}
+
+export function uniqueNFT(web3: Web3, address: string, owner: string) {
+ return new web3.eth.Contract(nonFungibleAbi as any, address, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
+ return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
+ return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: 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 usingApi(async (api, privateKeyWrapper) => {
+ await usingWeb3(async web3 => {
+ await cb({api, web3, privateKeyWrapper});
+ });
+ });
+ });
+}
+itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});
+itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});
+
+export async function generateSubstrateEthPair(web3: Web3) {
+ const account = web3.eth.accounts.create();
+ evmToAddress(account.address);
+}
+
+type NormalizedEvent = {
+ address: string,
+ event: string,
+ args: { [key: string]: string }
+};
+
+export function normalizeEvents(events: any): NormalizedEvent[] {
+ const output = [];
+ for (const key of Object.keys(events)) {
+ if (key.match(/^[0-9]+$/)) {
+ output.push(events[key]);
+ } else if (Array.isArray(events[key])) {
+ output.push(...events[key]);
+ } else {
+ output.push(events[key]);
+ }
+ }
+ output.sort((a, b) => a.logIndex - b.logIndex);
+ return output.map(({address, event, returnValues}) => {
+ const args: { [key: string]: string } = {};
+ for (const key of Object.keys(returnValues)) {
+ if (!key.match(/^[0-9]+$/)) {
+ args[key] = returnValues[key];
+ }
+ }
+ return {
+ address,
+ event,
+ args,
+ };
+ });
+}
+
+export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {
+ const out: any = [];
+ contract.events.allEvents((_: any, event: any) => {
+ out.push(event);
+ });
+ await action();
+ return normalizeEvents(out);
+}
+
+export function subToEthLowercase(eth: string): string {
+ const bytes = addressToEvm(eth);
+ return '0x' + Buffer.from(bytes).toString('hex');
+}
+
+export function subToEth(eth: string): string {
+ return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
+}
+
+export interface CompiledContract {
+ abi: any,
+ object: string,
+}
+
+export function compileContract(name: string, src: string) : CompiledContract {
+ const out = JSON.parse(solc.compile(JSON.stringify({
+ language: 'Solidity',
+ sources: {
+ [`${name}.sol`]: {
+ content: `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ ${src}
+ `,
+ },
+ },
+ settings: {
+ outputSelection: {
+ '*': {
+ '*': ['*'],
+ },
+ },
+ },
+ }))).contracts[`${name}.sol`][name];
+
+ return {
+ abi: out.abi,
+ object: '0x' + out.evm.bytecode.object,
+ };
+}
+
+export async function deployFlipper(web3: Web3, deployer: string) {
+ const compiled = compileContract('Flipper', `
+ contract Flipper {
+ bool value = false;
+ function flip() public {
+ value = !value;
+ }
+ function getValue() public view returns (bool) {
+ return value;
+ }
+ }
+ `);
+ const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {
+ data: compiled.object,
+ from: deployer,
+ ...GAS_ARGS,
+ });
+ const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});
+
+ return flipper;
+}
+
+export async function deployCollector(web3: Web3, deployer: string) {
+ const compiled = compileContract('Collector', `
+ 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;
+ }
+ }
+ `);
+ const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {
+ data: compiled.object,
+ from: deployer,
+ ...GAS_ARGS,
+ });
+ const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});
+
+ return collector;
+}
+
+/**
+ * pallet evm_contract_helpers
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function contractHelpers(web3: Web3, caller: string) {
+ return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection helper
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollectionHelpers(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {
+ let abi;
+ switch (mode.type) {
+ case 'Fungible':
+ abi = fungibleAbi;
+ break;
+
+ case 'NFT':
+ abi = nonFungibleAbi;
+ break;
+
+ case 'ReFungible':
+ abi = refungibleAbi;
+ break;
+
+ default:
+ throw 'Bad collection mode';
+ }
+ const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});
+ return contract;
+}
+
+/**
+ * Execute ethereum method call using substrate account
+ * @param to target contract
+ * @param mkTx - closure, receiving `contract.methods`, and returning method call,
+ * to be used as following (assuming `to` = erc20 contract):
+ * `m => m.transfer(to, amount)`
+ *
+ * # Example
+ * ```ts
+ * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
+ * ```
+ */
+export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {
+ const tx = api.tx.evm.call(
+ subToEth(from.address),
+ to.options.address,
+ mkTx(to.methods).encodeABI(),
+ value,
+ GAS_ARGS.gas,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const events = await submitTransactionAsync(from, tx);
+ expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;
+}
+
+export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
+ return (await getBalance(api, [evmToAddress(address)]))[0];
+}
+
+/**
+ * Measure how much gas given closure consumes
+ *
+ * @param user which user balance will be checked
+ */
+export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
+ const before = await ethBalanceViaSub(api, user);
+
+ await call();
+
+ // In dev mode, the transaction might not finish processing in time
+ await waitNewBlocks(api, 1);
+ const after = await ethBalanceViaSub(api, user);
+
+ // Can't use .to.be.less, because chai doesn't supports bigint
+ expect(after < before).to.be.true;
+
+ return before - after;
+}
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+// I want a fancier api, not a memory efficiency
+export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+ if(args.length === 0) {
+ yield internalRest as any;
+ return;
+ }
+ for(const value of args[0]) {
+ yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+ }
+}
\ No newline at end of file
tests/src/deprecated-helpers/helpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/helpers.ts
@@ -0,0 +1,1879 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import '../interfaces/augment-api-rpc';
+import '../interfaces/augment-api-query';
+import {ApiPromise, Keyring} from '@polkadot/api';
+import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';
+import type {GenericEventData} from '@polkadot/types';
+import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';
+import {evmToAddress} from '@polkadot/util-crypto';
+import {AnyNumber} from '@polkadot/types-codec/types';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import {hexToStr, strToUTF16, utf16ToStr} from './util';
+import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
+import {UpDataStructsTokenChild} from '../interfaces';
+import {Context} from 'mocha';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+export type CrossAccountId = {
+ Substrate: string,
+} | {
+ Ethereum: string,
+};
+
+
+export enum Pallets {
+ Inflation = 'inflation',
+ RmrkCore = 'rmrkcore',
+ RmrkEquip = 'rmrkequip',
+ ReFungible = 'refungible',
+ Fungible = 'fungible',
+ NFT = 'nonfungible',
+ Scheduler = 'scheduler',
+ AppPromotion = 'apppromotion',
+}
+
+export async function isUnique(): Promise<boolean> {
+ return usingApi(async api => {
+ const chain = await api.rpc.system.chain();
+
+ return chain.eq('UNIQUE');
+ });
+}
+
+export async function isQuartz(): Promise<boolean> {
+ return usingApi(async api => {
+ const chain = await api.rpc.system.chain();
+
+ return chain.eq('QUARTZ');
+ });
+}
+
+let modulesNames: any;
+export function getModuleNames(api: ApiPromise): string[] {
+ if (typeof modulesNames === 'undefined')
+ modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
+ return modulesNames;
+}
+
+export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
+ return await usingApi(async api => {
+ const pallets = getModuleNames(api);
+
+ return requiredPallets.filter(p => !pallets.includes(p));
+ });
+}
+
+export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {
+ return (await missingRequiredPallets(requiredPallets)).length == 0;
+}
+
+export async function requirePallets(mocha: Context, requiredPallets: string[]) {
+ const missingPallets = await missingRequiredPallets(requiredPallets);
+
+ if (missingPallets.length > 0) {
+ const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
+ const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
+ const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
+
+ console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
+
+ mocha.skip();
+ }
+}
+
+export function bigIntToSub(api: ApiPromise, number: bigint) {
+ return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
+}
+
+export function bigIntToDecimals(number: bigint, decimals = 18): string {
+ const numberStr = number.toString();
+ const dotPos = numberStr.length - decimals;
+
+ if (dotPos <= 0) {
+ return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
+ } else {
+ const intPart = numberStr.substring(0, dotPos);
+ const fractPart = numberStr.substring(dotPos);
+ return intPart + '.' + fractPart;
+ }
+}
+
+export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
+ if (typeof input === 'string') {
+ if (input.length >= 47) {
+ return {Substrate: input};
+ } else if (input.length === 42 && input.startsWith('0x')) {
+ return {Ethereum: input.toLowerCase()};
+ } else if (input.length === 40 && !input.startsWith('0x')) {
+ return {Ethereum: '0x' + input.toLowerCase()};
+ } else {
+ throw new Error(`Unknown address format: "${input}"`);
+ }
+ }
+ if ('address' in input) {
+ return {Substrate: input.address};
+ }
+ if ('Ethereum' in input) {
+ return {
+ Ethereum: input.Ethereum.toLowerCase(),
+ };
+ } else if ('ethereum' in input) {
+ return {
+ Ethereum: (input as any).ethereum.toLowerCase(),
+ };
+ } else if ('Substrate' in input) {
+ return input;
+ } else if ('substrate' in input) {
+ return {
+ Substrate: (input as any).substrate,
+ };
+ }
+
+ // AccountId
+ return {Substrate: input.toString()};
+}
+export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {
+ input = normalizeAccountId(input);
+ if ('Substrate' in input) {
+ return input.Substrate;
+ } else {
+ return evmToAddress(input.Ethereum);
+ }
+}
+
+export const U128_MAX = (1n << 128n) - 1n;
+
+const MICROUNIQUE = 1_000_000_000_000n;
+const MILLIUNIQUE = 1_000n * MICROUNIQUE;
+const CENTIUNIQUE = 10n * MILLIUNIQUE;
+export const UNIQUE = 100n * CENTIUNIQUE;
+
+interface GenericResult<T> {
+ success: boolean;
+ data: T | null;
+}
+
+interface CreateCollectionResult {
+ success: boolean;
+ collectionId: number;
+}
+
+interface CreateItemResult {
+ success: boolean;
+ collectionId: number;
+ itemId: number;
+ recipient?: CrossAccountId;
+ amount?: number;
+}
+
+interface DestroyItemResult {
+ success: boolean;
+ collectionId: number;
+ itemId: number;
+ owner: CrossAccountId;
+ amount: number;
+}
+
+interface TransferResult {
+ collectionId: number;
+ itemId: number;
+ sender?: CrossAccountId;
+ recipient?: CrossAccountId;
+ value: bigint;
+}
+
+interface IReFungibleOwner {
+ fraction: BN;
+ owner: number[];
+}
+
+interface IGetMessage {
+ checkMsgUnqMethod: string;
+ checkMsgTrsMethod: string;
+ checkMsgSysMethod: string;
+}
+
+export interface IFungibleTokenDataType {
+ value: number;
+}
+
+export interface IChainLimits {
+ collectionNumbersLimit: number;
+ accountTokenOwnershipLimit: number;
+ collectionsAdminsLimit: number;
+ customDataLimit: number;
+ nftSponsorTransferTimeout: number;
+ fungibleSponsorTransferTimeout: number;
+ refungibleSponsorTransferTimeout: number;
+ //offchainSchemaLimit: number;
+ //constOnChainSchemaLimit: number;
+}
+
+export interface IReFungibleTokenDataType {
+ owner: IReFungibleOwner[];
+}
+
+export function uniqueEventMessage(events: EventRecord[]): IGetMessage {
+ let checkMsgUnqMethod = '';
+ let checkMsgTrsMethod = '';
+ let checkMsgSysMethod = '';
+ events.forEach(({event: {method, section}}) => {
+ if (section === 'common') {
+ checkMsgUnqMethod = method;
+ } else if (section === 'treasury') {
+ checkMsgTrsMethod = method;
+ } else if (section === 'system') {
+ checkMsgSysMethod = method;
+ } else { return null; }
+ });
+ const result: IGetMessage = {
+ checkMsgUnqMethod,
+ checkMsgTrsMethod,
+ checkMsgSysMethod,
+ };
+ return result;
+}
+
+export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {
+ const event = events.find(r => check(r.event));
+ if (!event) return;
+ return event.event as T;
+}
+
+export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;
+export function getGenericResult<T>(
+ events: EventRecord[],
+ expectSection: string,
+ expectMethod: string,
+ extractAction: (data: GenericEventData) => T
+): GenericResult<T>;
+
+export function getGenericResult<T>(
+ events: EventRecord[],
+ expectSection?: string,
+ expectMethod?: string,
+ extractAction?: (data: GenericEventData) => T,
+): GenericResult<T> {
+ let success = false;
+ let successData = null;
+
+ events.forEach(({event: {data, method, section}}) => {
+ // console.log(` ${phase}: ${section}.${method}:: ${data}`);
+ if (method === 'ExtrinsicSuccess') {
+ success = true;
+ } else if ((expectSection == section) && (expectMethod == method)) {
+ successData = extractAction!(data as any);
+ }
+ });
+
+ const result: GenericResult<T> = {
+ success,
+ data: successData,
+ };
+ return result;
+}
+
+export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
+ const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));
+ const result: CreateCollectionResult = {
+ success: genericResult.success,
+ collectionId: genericResult.data ?? 0,
+ };
+ return result;
+}
+
+export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {
+ const results: CreateItemResult[] = [];
+
+ const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {
+ const collectionId = parseInt(data[0].toString(), 10);
+ const itemId = parseInt(data[1].toString(), 10);
+ const recipient = normalizeAccountId(data[2].toJSON() as any);
+ const amount = parseInt(data[3].toString(), 10);
+
+ const itemRes: CreateItemResult = {
+ success: true,
+ collectionId,
+ itemId,
+ recipient,
+ amount,
+ };
+
+ results.push(itemRes);
+ return results;
+ });
+
+ if (!genericResult.success) return [];
+ return results;
+}
+
+export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
+ const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
+
+ if (genericResult.data == null)
+ return {
+ success: genericResult.success,
+ collectionId: 0,
+ itemId: 0,
+ amount: 0,
+ };
+ else
+ return {
+ success: genericResult.success,
+ collectionId: genericResult.data[0] as number,
+ itemId: genericResult.data[1] as number,
+ recipient: normalizeAccountId(genericResult.data![2] as any),
+ amount: genericResult.data[3] as number,
+ };
+}
+
+export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
+ const results: DestroyItemResult[] = [];
+
+ const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {
+ const collectionId = parseInt(data[0].toString(), 10);
+ const itemId = parseInt(data[1].toString(), 10);
+ const owner = normalizeAccountId(data[2].toJSON() as any);
+ const amount = parseInt(data[3].toString(), 10);
+
+ const itemRes: DestroyItemResult = {
+ success: true,
+ collectionId,
+ itemId,
+ owner,
+ amount,
+ };
+
+ results.push(itemRes);
+ return results;
+ });
+
+ if (!genericResult.success) return [];
+ return results;
+}
+
+export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {
+ for (const {event} of events) {
+ if (api.events.common.Transfer.is(event)) {
+ const [collection, token, sender, recipient, value] = event.data;
+ return {
+ collectionId: collection.toNumber(),
+ itemId: token.toNumber(),
+ sender: normalizeAccountId(sender.toJSON() as any),
+ recipient: normalizeAccountId(recipient.toJSON() as any),
+ value: value.toBigInt(),
+ };
+ }
+ }
+ throw new Error('no transfer event');
+}
+
+interface Nft {
+ type: 'NFT';
+}
+
+interface Fungible {
+ type: 'Fungible';
+ decimalPoints: number;
+}
+
+interface ReFungible {
+ type: 'ReFungible';
+}
+
+export type CollectionMode = Nft | Fungible | ReFungible;
+
+export type Property = {
+ key: any,
+ value: any,
+};
+
+type Permission = {
+ mutable: boolean;
+ collectionAdmin: boolean;
+ tokenOwner: boolean;
+}
+
+type PropertyPermission = {
+ key: any;
+ permission: Permission;
+}
+
+export type CreateCollectionParams = {
+ mode: CollectionMode,
+ name: string,
+ description: string,
+ tokenPrefix: string,
+ properties?: Array<Property>,
+ propPerm?: Array<PropertyPermission>
+};
+
+const defaultCreateCollectionParams: CreateCollectionParams = {
+ description: 'description',
+ mode: {type: 'NFT'},
+ name: 'name',
+ tokenPrefix: 'prefix',
+};
+
+export async function
+createCollection(
+ api: ApiPromise,
+ sender: IKeyringPair,
+ params: Partial<CreateCollectionParams> = {},
+): Promise<CreateCollectionResult> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({
+ name: strToUTF16(name),
+ description: strToUTF16(description),
+ tokenPrefix: strToUTF16(tokenPrefix),
+ mode: modeprm as any,
+ });
+ const events = await executeTransaction(api, sender, tx);
+ return getCreateCollectionResult(events);
+}
+
+export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let collectionId = 0;
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ const result = await createCollection(api, alicePrivateKey, params);
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(result.collectionId).to.be.equal(collectionCountAfter);
+ // tslint:disable-next-line:no-unused-expression
+ expect(collection).to.be.not.null;
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
+ expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
+ expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
+ expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
+ expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
+
+ collectionId = result.collectionId;
+ });
+
+ return collectionId;
+}
+
+export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let collectionId = 0;
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getCreateCollectionResult(events);
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(result.collectionId).to.be.equal(collectionCountAfter);
+ // tslint:disable-next-line:no-unused-expression
+ expect(collection).to.be.not.null;
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
+ expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
+ expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
+ expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
+ expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
+
+
+ collectionId = result.collectionId;
+ });
+
+ return collectionId;
+}
+
+export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
+ });
+}
+
+export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // What to expect
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
+ });
+}
+
+export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
+ let bal = 0n;
+ let unused;
+ do {
+ const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
+ unused = privateKeyWrapper(`//${randomSeed}`);
+ bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
+ } while (bal !== 0n);
+ return unused;
+}
+
+export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {
+ return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();
+}
+
+export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
+ return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
+}
+
+export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
+ const totalNumber = await getCreatedCollectionCount(api);
+ const newCollection: number = totalNumber + 1;
+ return newCollection;
+}
+
+function getDestroyResult(events: EventRecord[]): boolean {
+ let success = false;
+ events.forEach(({event: {method}}) => {
+ if (method == 'ExtrinsicSuccess') {
+ success = true;
+ }
+ });
+ return success;
+}
+
+export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Run the DestroyCollection transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.destroyCollection(collectionId);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Run the DestroyCollection transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.destroyCollection(collectionId);
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getDestroyResult(events);
+ expect(result).to.be.true;
+
+ // What to expect
+ expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
+ });
+}
+
+export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {
+ await usingApi(async(api) => {
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+};
+
+export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const senderPrivateKey = privateKeyWrapper(sender);
+ const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
+ const events = await submitTransactionAsync(senderPrivateKey, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.deep.equal({
+ unconfirmed: sponsor,
+ });
+ });
+}
+
+export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(sender);
+ const tx = api.tx.unique.removeCollectionSponsor(collectionId);
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});
+ });
+}
+
+export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.removeCollectionSponsor(collectionId);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const sender = privateKeyWrapper(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.confirmSponsorship(collectionId);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.be.deep.equal({
+ confirmed: sender.address,
+ });
+ });
+}
+
+
+export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const sender = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.confirmSponsorship(collectionId);
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ });
+}
+
+export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function getNextSponsored(
+ api: ApiPromise,
+ collectionId: number,
+ account: string | CrossAccountId,
+ tokenId: number,
+): Promise<number> {
+ return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
+}
+
+export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
+ let allowlisted = false;
+ await usingApi(async (api) => {
+ allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;
+ });
+ return allowlisted;
+}
+
+export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export interface CreateFungibleData {
+ readonly Value: bigint;
+}
+
+export interface CreateReFungibleData { }
+export interface CreateNftData { }
+
+export type CreateItemData = {
+ NFT: CreateNftData;
+} | {
+ Fungible: CreateFungibleData;
+} | {
+ ReFungible: CreateReFungibleData;
+};
+
+export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {
+ const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
+ const events = await submitTransactionAsync(sender, tx);
+ return getGenericResult(events).success;
+}
+
+export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
+ // if burning token by admin - use adminButnItemExpectSuccess
+ expect(balanceBefore >= BigInt(value)).to.be.true;
+
+ expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;
+
+ const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
+ expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);
+ });
+}
+
+export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);
+ const events = await submitTransactionAsync(sender, tx);
+ return getGenericResult(events).success;
+ });
+}
+
+export async function
+approve(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,
+) {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(owner, approveUniqueTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+approveExpectSuccess(
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const result = await approve(api, collectionId, tokenId, owner, approved, amount);
+ expect(result).to.be.true;
+
+ expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
+ });
+}
+
+export async function adminApproveFromExpectSuccess(
+ collectionId: number,
+ tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(admin, approveUniqueTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
+ });
+}
+
+export async function
+transferFrom(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair | CrossAccountId,
+ accountTo: IKeyringPair | CrossAccountId,
+ value: number | bigint,
+) {
+ const from = normalizeAccountId(accountFrom);
+ const to = normalizeAccountId(accountTo);
+ const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);
+ const events = await submitTransactionAsync(accountApproved, transferFromTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+transferFromExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair | CrossAccountId,
+ accountTo: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+ type = 'NFT',
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const from = normalizeAccountId(accountFrom);
+ const to = normalizeAccountId(accountTo);
+ let balanceBefore = 0n;
+ if (type === 'Fungible' || type === 'ReFungible') {
+ balanceBefore = await getBalance(api, collectionId, to, tokenId);
+ }
+ expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;
+ if (type === 'NFT') {
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
+ }
+ if (type === 'Fungible') {
+ const balanceAfter = await getBalance(api, collectionId, to, tokenId);
+ if (JSON.stringify(to) !== JSON.stringify(from)) {
+ expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
+ } else {
+ expect(balanceAfter).to.be.equal(balanceBefore);
+ }
+ }
+ if (type === 'ReFungible') {
+ expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));
+ }
+ });
+}
+
+export async function
+transferFromExpectFail(
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair,
+ accountTo: IKeyringPair,
+ value: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);
+ const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+/* eslint no-async-promise-executor: "off" */
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
+ return new Promise<number>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
+ unsubscribe();
+ resolve(head.number.toNumber());
+ });
+ });
+}
+
+export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {
+ await usingApi(async (api) => {
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, changeAdminTx);
+ const result = getCreateCollectionResult(events);
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function adminApproveFromExpectFail(
+ collectionId: number,
+ tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;
+ const result = getGenericResult(events);
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function
+getFreeBalance(account: IKeyringPair): Promise<bigint> {
+ let balance = 0n;
+ await usingApi(async (api) => {
+ balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
+ });
+
+ return balance;
+}
+
+export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {
+ return usingApi(async api => {
+ // We are getting a *sibling* parachain sovereign account,
+ // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
+ const siblingPrefix = '0x7369626c';
+
+ const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);
+ const suffix = '000000000000000000000000000000000000000000000000';
+
+ return siblingPrefix + encodedParaId + suffix;
+ });
+}
+
+export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
+ const tx = api.tx.balances.transfer(target, amount);
+ const events = await submitTransactionAsync(source, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+}
+
+export async function
+scheduleExpectSuccess(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions > 1 ? [period, repetitions] : null,
+ 0,
+ {Value: operationTx as any},
+ );
+
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function
+scheduleExpectFailure(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions <= 1 ? null : [period, repetitions],
+ 0,
+ {Value: operationTx as any},
+ );
+
+ //const events =
+ await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
+ //expect(getGenericResult(events).success).to.be.false;
+ });
+}
+
+export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
+
+ const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ // sleep for n + 1 blocks
+ await waitNewBlocks(blockSchedule + 1);
+
+ const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
+ expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ });
+}
+
+export async function
+scheduleTransferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
+
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+
+ const balanceBefore = await getFreeBalance(recipient);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
+
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
+ });
+}
+
+export async function
+transfer(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint,
+) : Promise<boolean> {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await executeTransaction(api, sender, transferTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+transferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+ type = 'NFT',
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const from = normalizeAccountId(sender);
+ const to = normalizeAccountId(recipient);
+
+ let balanceBefore = 0n;
+ if (type === 'Fungible' || type === 'ReFungible') {
+ balanceBefore = await getBalance(api, collectionId, to, tokenId);
+ }
+
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await executeTransaction(api, sender, transferTx);
+ const result = getTransferResult(api, events);
+
+ expect(result.collectionId).to.be.equal(collectionId);
+ expect(result.itemId).to.be.equal(tokenId);
+ expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));
+ expect(result.recipient).to.be.deep.equal(to);
+ expect(result.value).to.be.equal(BigInt(value));
+
+ if (type === 'NFT') {
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
+ }
+ if (type === 'Fungible' || type === 'ReFungible') {
+ const balanceAfter = await getBalance(api, collectionId, to, tokenId);
+ if (JSON.stringify(to) !== JSON.stringify(from)) {
+ expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
+ } else {
+ expect(balanceAfter).to.be.equal(balanceBefore);
+ }
+ }
+ });
+}
+
+export async function
+transferExpectFailure(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;
+ const result = getGenericResult(events);
+ // if (events && Array.isArray(events)) {
+ // const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ //}
+ });
+}
+
+export async function
+approveExpectFail(
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);
+ const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function getBalance(
+ api: ApiPromise,
+ collectionId: number,
+ owner: string | CrossAccountId | IKeyringPair,
+ token: number,
+): Promise<bigint> {
+ return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();
+}
+export async function getTokenOwner(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<CrossAccountId> {
+ const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;
+ if (owner == null) throw new Error('owner == null');
+ return normalizeAccountId(owner);
+}
+export async function getTopmostTokenOwner(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<CrossAccountId> {
+ const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;
+ if (owner == null) throw new Error('owner == null');
+ return normalizeAccountId(owner);
+}
+export async function getTokenChildren(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+): Promise<UpDataStructsTokenChild[]> {
+ return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
+}
+export async function isTokenExists(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<boolean> {
+ return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();
+}
+export async function getLastTokenId(
+ api: ApiPromise,
+ collectionId: number,
+): Promise<number> {
+ return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();
+}
+export async function getAdminList(
+ api: ApiPromise,
+ collectionId: number,
+): Promise<string[]> {
+ return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;
+}
+export async function getTokenProperties(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ propertyKeys: string[],
+): Promise<UpDataStructsProperty[]> {
+ return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;
+}
+
+export async function createFungibleItemExpectSuccess(
+ sender: IKeyringPair,
+ collectionId: number,
+ data: CreateFungibleData,
+ owner: CrossAccountId | string = sender.address,
+) {
+ return await usingApi(async (api) => {
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.true;
+ return result.itemId;
+ });
+}
+
+export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const res of result) {
+ expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
+ }
+ });
+}
+
+export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const res of result) {
+ expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
+ }
+ });
+}
+
+export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
+ let newItemId = 0;
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const itemCountBefore = await getLastTokenId(api, collectionId);
+ const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
+
+ let tx;
+ if (createMode === 'Fungible') {
+ const createData = {fungible: {value: 10}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else if (createMode === 'ReFungible') {
+ const createData = {refungible: {pieces: 100}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else {
+ const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});
+ tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);
+ }
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemResult(events);
+
+ const itemCountAfter = await getLastTokenId(api, collectionId);
+ const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
+
+ if (createMode === 'NFT') {
+ expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;
+ }
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ if (createMode === 'Fungible') {
+ expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
+ } else {
+ expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
+ }
+ expect(collectionId).to.be.equal(result.collectionId);
+ expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
+ expect(to).to.be.deep.equal(result.recipient);
+ newItemId = result.itemId;
+ });
+ return newItemId;
+}
+
+export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+
+ let tx;
+ if (createMode === 'NFT') {
+ const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;
+ tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);
+ } else {
+ tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
+ }
+
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
+ let newItemId = 0;
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const itemCountBefore = await getLastTokenId(api, collectionId);
+ const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
+
+ let tx;
+ if (createMode === 'Fungible') {
+ const createData = {fungible: {value: 10}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else if (createMode === 'ReFungible') {
+ const createData = {refungible: {pieces: 100}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else {
+ const createData = {nft: {}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ }
+
+ const events = await executeTransaction(api, sender, tx);
+ const result = getCreateItemResult(events);
+
+ const itemCountAfter = await getLastTokenId(api, collectionId);
+ const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ if (createMode === 'Fungible') {
+ expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
+ } else {
+ expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
+ }
+ expect(collectionId).to.be.equal(result.collectionId);
+ expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
+ expect(to).to.be.deep.equal(result.recipient);
+ newItemId = result.itemId;
+ });
+ return newItemId;
+}
+
+export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {
+ const createData = {refungible: {pieces: amount}};
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);
+
+ const events = await submitTransactionAsync(sender, tx);
+ return getCreateItemResult(events);
+}
+
+export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setPublicAccessModeExpectSuccess(
+ sender: IKeyringPair, collectionId: number,
+ accessMode: 'Normal' | 'AllowList',
+) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);
+ });
+}
+
+export async function setPublicAccessModeExpectFail(
+ sender: IKeyringPair, collectionId: number,
+ accessMode: 'Normal' | 'AllowList',
+) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
+}
+
+export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
+}
+
+export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
+}
+
+export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);
+ });
+}
+
+export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setMintPermissionExpectSuccess(sender, collectionId, true);
+}
+
+export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.setChainLimits(limits);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
+ return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
+}
+
+export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
+ await usingApi(async (api) => {
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+ });
+}
+
+export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+ await usingApi(async (api) => {
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+ });
+}
+
+export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
+ : Promise<UpDataStructsRpcCollection | null> => {
+ return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);
+};
+
+export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
+ // set global object - collectionsCount
+ return (await api.rpc.unique.collectionStats()).created.toNumber();
+};
+
+export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {
+ return (await api.rpc.unique.collectionById(collectionId)).unwrap();
+}
+
+export const describe_xcm = (
+ process.env.RUN_XCM_TESTS
+ ? describe
+ : describe.skip
+);
+
+export async function waitNewBlocks(blocksCount = 1): Promise<void> {
+ await usingApi(async (api) => {
+ const promise = new Promise<void>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {
+ if (blocksCount > 0) {
+ blocksCount--;
+ } else {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
+ return promise;
+ });
+}
+
+export async function waitEvent(
+ api: ApiPromise,
+ maxBlocksToWait: number,
+ eventSection: string,
+ eventMethod: string,
+): Promise<EventRecord | null> {
+
+ const promise = new Promise<EventRecord | null>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {
+ const blockNumber = header.number.toHuman();
+ const blockHash = header.hash;
+ const eventIdStr = `${eventSection}.${eventMethod}`;
+ const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
+
+ console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
+
+ const apiAt = await api.at(blockHash);
+ const eventRecords = await apiAt.query.system.events();
+
+ const neededEvent = eventRecords.find(r => {
+ return r.event.section == eventSection && r.event.method == eventMethod;
+ });
+
+ if (neededEvent) {
+ unsubscribe();
+ resolve(neededEvent);
+ } else if (maxBlocksToWait > 0) {
+ maxBlocksToWait--;
+ } else {
+ console.log(`Event \`${eventIdStr}\` is NOT found`);
+
+ unsubscribe();
+ resolve(null);
+ }
+ });
+ });
+ return promise;
+}
+
+export async function repartitionRFT(
+ api: ApiPromise,
+ collectionId: number,
+ sender: IKeyringPair,
+ tokenId: number,
+ amount: bigint,
+): Promise<boolean> {
+ const tx = api.tx.unique.repartition(collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ return result.success;
+}
+
+export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: 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 usingApi(async (api, privateKeyWrapper) => {
+ await cb({api, privateKeyWrapper});
+ });
+ });
+}
+
+itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});
+itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
+
+let accountSeed = 10000;
+export function generateKeyringPair(keyring: Keyring) {
+ const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;
+ return keyring.addFromUri(privateKey);
+}
+
+export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {
+ const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
+ const subEvents = (await api.query.system.events.at(blockHash))
+ .filter(x => x.event.section === section)
+ .map((x) => x.toHuman());
+ const events = methods.map((m) => {
+ return {
+ event: {
+ method: m,
+ section,
+ },
+ };
+ });
+ if (!dryRun) {
+ expect(subEvents).to.be.like(events);
+ }
+ return subEvents;
+}
tests/src/deprecated-helpers/util.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/util.ts
@@ -0,0 +1,46 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+export function strToUTF16(str: string): any {
+ const buf: number[] = [];
+ for (let i=0, strLen=str.length; i < strLen; i++) {
+ buf.push(str.charCodeAt(i));
+ }
+ return buf;
+}
+
+export function utf16ToStr(buf: number[]): string {
+ let str = '';
+ for (let i=0, strLen=buf.length; i < strLen; i++) {
+ if (buf[i] != 0) str += String.fromCharCode(buf[i]);
+ else break;
+ }
+ return str;
+}
+
+export function hexToStr(buf: string): string {
+ let str = '';
+ let hexStart = buf.indexOf('0x');
+ if (hexStart < 0) hexStart = 0;
+ else hexStart = 2;
+ for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
+ const ch = buf[i] + buf[i+1];
+ const num = parseInt(ch, 16);
+ if (num != 0) str += String.fromCharCode(num);
+ else break;
+ }
+ return str;
+}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -14,16 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {
- ethBalanceViaSub,
- GAS_ARGS,
- recordEthFee,
-} from './util/helpers';
import {Contract} from 'web3-eth-contract';
import {IKeyringPair} from '@polkadot/types/types';
import {EthUniqueHelper, itEth, usingEthPlaygrounds, expect} from './util/playgrounds';
+
describe('Contract calls', () => {
let donor: IKeyringPair;
@@ -37,15 +33,15 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const flipper = await helper.eth.deployFlipper(deployer);
- const cost = await recordEthFee(helper.api!, deployer, () => flipper.methods.flip().send({from: deployer}));
+ const cost = await helper.eth.calculateFee({Ethereum: deployer}, () => flipper.methods.flip().send({from: deployer}));
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
itEth('Balance transfer fee is less than 0.2 UNQ', async ({helper}) => {
const userA = await helper.eth.createAccountWithBalance(donor);
const userB = helper.eth.createAccount();
- const cost = await recordEthFee(helper.api!, userA, () => helper.web3!.eth.sendTransaction({from: userA, to: userB, value: '1000000', ...GAS_ARGS}));
- const balanceB = await ethBalanceViaSub(helper.api!, userB);
+ const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({from: userA, to: userB, value: '1000000', gas: helper.eth.DEFAULT_GAS}));
+ const balanceB = await helper.balance.getEthereum(userB);
expect(cost - balanceB < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
@@ -60,7 +56,7 @@
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(helper.api!, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, tokenId).send(caller));
const fee = Number(cost) / Number(helper.balance.getOneTokenNominal());
const expectedFee = 0.15;
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -17,8 +17,8 @@
import {evmToAddress} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
-import {UNIQUE} from '../util/helpers';
+
describe('Create NFT collection from EVM', () => {
let donor: IKeyringPair;
@@ -65,7 +65,7 @@
await collectionHelpers.methods
.createNonfungibleCollection('A', 'A', 'A')
- .send({value: Number(2n * UNIQUE)});
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
@@ -147,10 +147,12 @@
describe('(!negative tests!) Create NFT collection from EVM', () => {
let donor: IKeyringPair;
+ let nominal: bigint;
before(async function() {
- await usingEthPlaygrounds(async (_helper, privateKey) => {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
donor = privateKey('//Alice');
+ nominal = helper.balance.getOneTokenNominal();
});
});
@@ -165,7 +167,7 @@
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
{
@@ -175,7 +177,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
const MAX_TOKEN_PREFIX_LENGTH = 16;
@@ -184,7 +186,7 @@
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -193,7 +195,7 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
.createNonfungibleCollection('Peasantry', 'absolutely anything', 'CVE')
- .call({value: Number(1n * UNIQUE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -18,8 +18,8 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';
import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
-import {UNIQUE} from '../util/helpers';
+
describe('Create RFT collection from EVM', () => {
let donor: IKeyringPair;
@@ -66,7 +66,7 @@
await collectionHelpers.methods
.createRFTCollection('A', 'A', 'A')
- .send({value: Number(2n * UNIQUE)});
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
@@ -148,11 +148,13 @@
describe('(!negative tests!) Create RFT collection from EVM', () => {
let donor: IKeyringPair;
+ let nominal: bigint;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
donor = privateKey('//Alice');
+ nominal = helper.balance.getOneTokenNominal();
});
});
@@ -167,7 +169,7 @@
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
{
const MAX_DESCRIPTION_LENGTH = 256;
@@ -176,7 +178,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
const MAX_TOKEN_PREFIX_LENGTH = 16;
@@ -185,7 +187,7 @@
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -194,7 +196,7 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
.createRFTCollection('Peasantry', 'absolutely anything', 'TWIW')
- .call({value: Number(1n * UNIQUE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -17,8 +17,8 @@
import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
-import {UNIQUE} from '../util/helpers';
+
describe('NFT: Information getting', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
@@ -84,7 +84,7 @@
const receiver = helper.eth.createAccount();
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * UNIQUE)});
+ let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
tests/src/eth/proxy/fungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/fungibleProxy.test.ts
+++ b/tests/src/eth/proxy/fungibleProxy.test.ts
@@ -14,7 +14,6 @@
// 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 {GAS_ARGS, normalizeEvents} from '../util/helpers';
import {expect} from 'chai';
import {readFile} from 'fs/promises';
import {IKeyringPair} from '@polkadot/types/types';
@@ -26,7 +25,7 @@
const web3 = helper.getWeb3();
const proxyContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/UniqueFungibleProxy.abi`)).toString()), undefined, {
from: owner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const proxy = await proxyContract.deploy({data: (await readFile(`${__dirname}/UniqueFungibleProxy.bin`)).toString(), arguments: [wrapped.options.address]}).send({from: owner});
return proxy;
@@ -94,7 +93,7 @@
{
const result = await contract.methods.approve(spender, 100).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -131,7 +130,7 @@
{
const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
@@ -177,7 +176,7 @@
{
const result = await contract.methods.transfer(receiver, 50).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -14,11 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';
-import {expect} from 'chai';
import {readFile} from 'fs/promises';
import {IKeyringPair} from '@polkadot/types/types';
-import {EthUniqueHelper, itEth, usingEthPlaygrounds} from '../util/playgrounds';
+import {EthUniqueHelper, itEth, usingEthPlaygrounds, expect} from '../util/playgrounds';
+
async function proxyWrap(helper: EthUniqueHelper, wrapped: any, donor: IKeyringPair) {
// Proxy owner has no special privilegies, we don't need to reuse them
@@ -26,7 +25,7 @@
const web3 = helper.getWeb3();
const proxyContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/UniqueNFTProxy.abi`)).toString()), undefined, {
from: owner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const proxy = await proxyContract.deploy({data: (await readFile(`${__dirname}/UniqueNFTProxy.bin`)).toString(), arguments: [wrapped.options.address]}).send({from: owner});
return proxy;
@@ -119,7 +118,7 @@
nextTokenId,
'Test URI',
).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
events[0].address = events[0].address.toLocaleLowerCase();
expect(events).to.be.deep.equal([
@@ -139,20 +138,16 @@
});
//TODO: CORE-302 add eth methods
- itWeb3.skip('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {
- /*
- const collection = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- });
- const alice = privateKeyWrapper('//Alice');
+ itEth.skip('Can perform mintBulk()', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(donor, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const receiver = createEthAccount(web3);
+ const caller = await helper.eth.createAccountWithBalance(donor, 30n);
+ const receiver = helper.eth.createAccount();
- const address = collectionIdToAddress(collection);
- const contract = await proxyWrap(api, web3, new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS}), privateKeyWrapper);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collection, {Ethereum: contract.options.address});
- await submitTransactionAsync(alice, changeAdminTx);
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const evmCollection = helper.ethNativeContract.collection(address, 'nft', caller);
+ const contract = await proxyWrap(helper, evmCollection, donor);
+ await collection.addAdmin(donor, {Ethereum: contract.options.address});
{
const nextTokenId = await contract.methods.nextTokenId().call();
@@ -165,7 +160,7 @@
[+nextTokenId + 2, 'Test URI 2'],
],
).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -201,7 +196,6 @@
expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
}
- */
});
itEth('Can perform burn()', async ({helper}) => {
@@ -216,7 +210,7 @@
{
const result = await contract.methods.burn(tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -243,8 +237,8 @@
const {tokenId} = await collection.mintToken(alice, {Ethereum: contract.options.address});
{
- const result = await contract.methods.approve(spender, tokenId).send({from: caller, ...GAS_ARGS});
- const events = normalizeEvents(result.events);
+ const result = await contract.methods.approve(spender, tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS});
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -276,7 +270,7 @@
{
const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
@@ -313,7 +307,7 @@
{
const result = await contract.methods.transfer(receiver, tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -18,8 +18,8 @@
import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
-import {UNIQUE} from '../util/helpers';
+
describe('Refungible token: Information getting', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
@@ -81,7 +81,7 @@
const receiver = helper.eth.createAccount();
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * UNIQUE)});
+ let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- a/tests/src/eth/scheduling.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {expect} from 'chai';
-import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
-import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../util/helpers';
-
-// TODO mrshiposha update this test in #581
-describe.skip('Scheduing EVM smart contracts', () => {
- before(async function() {
- await requirePallets(this, [Pallets.Scheduler]);
- });
-
- itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3, privateKeyWrapper}) => {
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, deployer);
- const initialValue = await flipper.methods.getValue().call();
- const alice = privateKeyWrapper('//Alice');
- await transferBalanceToEth(api, alice, subToEth(alice.address));
-
- {
- const tx = api.tx.evm.call(
- subToEth(alice.address),
- flipper.options.address,
- flipper.methods.flip().encodeABI(),
- '0',
- GAS_ARGS.gas,
- await web3.eth.getGasPrice(),
- null,
- null,
- [],
- );
- const waitForBlocks = 4;
- const periodBlocks = 2;
-
- await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
- expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
-
- await waitNewBlocks(waitForBlocks - 1);
- expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
-
- await waitNewBlocks(periodBlocks);
- expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
- }
- });
-});
tests/src/eth/util/helpers.d.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.d.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-declare module 'solc';
\ No newline at end of file
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// eslint-disable-next-line @typescript-eslint/triple-slash-reference
-/// <reference path="helpers.d.ts" />
-
-import {ApiPromise} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';
-import {expect} from 'chai';
-import * as solc from 'solc';
-import Web3 from 'web3';
-import config from '../../config';
-import getBalance from '../../substrate/get-balance';
-import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
-import waitNewBlocks from '../../substrate/wait-new-blocks';
-import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';
-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';
-
-export const GAS_ARGS = {gas: 2500000};
-
-export enum SponsoringMode {
- Disabled = 0,
- Allowlisted = 1,
- Generous = 2,
-}
-
-let web3Connected = false;
-export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {
- if (web3Connected) throw new Error('do not nest usingWeb3 calls');
- web3Connected = true;
-
- const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);
- const web3 = new Web3(provider);
-
- try {
- return await cb(web3);
- } finally {
- // provider.disconnect(3000, 'normal disconnect');
- provider.connection.close();
- web3Connected = false;
- }
-}
-
-function encodeIntBE(v: number): number[] {
- if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
- return [
- v >> 24,
- (v >> 16) & 0xff,
- (v >> 8) & 0xff,
- v & 0xff,
- ];
-}
-
-export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
- const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = collectionIdFromAddress(collectionIdAddress);
- const collection = (await getDetailedCollectionInfo(api, collectionId))!;
- return {collectionIdAddress, collectionId, collection};
-}
-
-export function collectionIdToAddress(collection: number): string {
- const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
- ...encodeIntBE(collection),
- ]);
- return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-export function collectionIdFromAddress(address: string): number {
- if (!address.startsWith('0x'))
- throw 'address not starts with "0x"';
- if (address.length > 42)
- throw 'address length is more than 20 bytes';
- return Number('0x' + address.substring(address.length - 8));
-}
-
-export function normalizeAddress(address: string): string {
- return '0x' + address.substring(address.length - 40);
-}
-
-export function tokenIdToAddress(collection: number, token: number): string {
- const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
- ...encodeIntBE(collection),
- ...encodeIntBE(token),
- ]);
- return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-
-export function tokenIdFromAddress(address: string) {
- 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)),
- };
-}
-
-export function tokenIdToCross(collection: number, token: number): CrossAccountId {
- return {
- Ethereum: tokenIdToAddress(collection, token),
- };
-}
-
-export function createEthAccount(web3: Web3) {
- const account = web3.eth.accounts.create();
- web3.eth.accounts.wallet.add(account.privateKey);
- return account.address;
-}
-
-export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {
- const alice = privateKeyWrapper('//Alice');
- const account = createEthAccount(web3);
- await transferBalanceToEth(api, alice, account);
-
- return account;
-}
-
-export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
- const tx = api.tx.balances.transfer(evmToAddress(target), amount);
- const events = await submitTransactionAsync(source, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-}
-
-export async function createRFTCollection(api: ApiPromise, web3: Web3, owner: string) {
- const collectionHelper = evmCollectionHelpers(web3, owner);
- const result = await collectionHelper.methods
- .createRFTCollection('A', 'B', 'C')
- .send({value: Number(2n * UNIQUE)});
- return await getCollectionAddressFromResult(api, result);
-}
-
-
-export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
- const collectionHelper = evmCollectionHelpers(web3, owner);
- const result = await collectionHelper.methods
- .createNonfungibleCollection('A', 'B', 'C')
- .send({value: Number(2n * UNIQUE)});
- return await getCollectionAddressFromResult(api, result);
-}
-
-export function uniqueNFT(web3: Web3, address: string, owner: string) {
- return new web3.eth.Contract(nonFungibleAbi as any, address, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
- return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
- return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: 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 usingApi(async (api, privateKeyWrapper) => {
- await usingWeb3(async web3 => {
- await cb({api, web3, privateKeyWrapper});
- });
- });
- });
-}
-itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});
-itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});
-
-export async function generateSubstrateEthPair(web3: Web3) {
- const account = web3.eth.accounts.create();
- evmToAddress(account.address);
-}
-
-type NormalizedEvent = {
- address: string,
- event: string,
- args: { [key: string]: string }
-};
-
-export function normalizeEvents(events: any): NormalizedEvent[] {
- const output = [];
- for (const key of Object.keys(events)) {
- if (key.match(/^[0-9]+$/)) {
- output.push(events[key]);
- } else if (Array.isArray(events[key])) {
- output.push(...events[key]);
- } else {
- output.push(events[key]);
- }
- }
- output.sort((a, b) => a.logIndex - b.logIndex);
- return output.map(({address, event, returnValues}) => {
- const args: { [key: string]: string } = {};
- for (const key of Object.keys(returnValues)) {
- if (!key.match(/^[0-9]+$/)) {
- args[key] = returnValues[key];
- }
- }
- return {
- address,
- event,
- args,
- };
- });
-}
-
-export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {
- const out: any = [];
- contract.events.allEvents((_: any, event: any) => {
- out.push(event);
- });
- await action();
- return normalizeEvents(out);
-}
-
-export function subToEthLowercase(eth: string): string {
- const bytes = addressToEvm(eth);
- return '0x' + Buffer.from(bytes).toString('hex');
-}
-
-export function subToEth(eth: string): string {
- return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
-}
-
-export interface CompiledContract {
- abi: any,
- object: string,
-}
-
-export function compileContract(name: string, src: string) : CompiledContract {
- const out = JSON.parse(solc.compile(JSON.stringify({
- language: 'Solidity',
- sources: {
- [`${name}.sol`]: {
- content: `
- // SPDX-License-Identifier: UNLICENSED
- pragma solidity ^0.8.6;
-
- ${src}
- `,
- },
- },
- settings: {
- outputSelection: {
- '*': {
- '*': ['*'],
- },
- },
- },
- }))).contracts[`${name}.sol`][name];
-
- return {
- abi: out.abi,
- object: '0x' + out.evm.bytecode.object,
- };
-}
-
-export async function deployFlipper(web3: Web3, deployer: string) {
- const compiled = compileContract('Flipper', `
- contract Flipper {
- bool value = false;
- function flip() public {
- value = !value;
- }
- function getValue() public view returns (bool) {
- return value;
- }
- }
- `);
- const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {
- data: compiled.object,
- from: deployer,
- ...GAS_ARGS,
- });
- const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});
-
- return flipper;
-}
-
-export async function deployCollector(web3: Web3, deployer: string) {
- const compiled = compileContract('Collector', `
- 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;
- }
- }
- `);
- const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {
- data: compiled.object,
- from: deployer,
- ...GAS_ARGS,
- });
- const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});
-
- return collector;
-}
-
-/**
- * pallet evm_contract_helpers
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function contractHelpers(web3: Web3, caller: string) {
- return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
-}
-
-/**
- * evm collection helper
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function evmCollectionHelpers(web3: Web3, caller: string) {
- return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
-}
-
-/**
- * evm collection
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {
- let abi;
- switch (mode.type) {
- case 'Fungible':
- abi = fungibleAbi;
- break;
-
- case 'NFT':
- abi = nonFungibleAbi;
- break;
-
- case 'ReFungible':
- abi = refungibleAbi;
- break;
-
- default:
- throw 'Bad collection mode';
- }
- const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});
- return contract;
-}
-
-/**
- * Execute ethereum method call using substrate account
- * @param to target contract
- * @param mkTx - closure, receiving `contract.methods`, and returning method call,
- * to be used as following (assuming `to` = erc20 contract):
- * `m => m.transfer(to, amount)`
- *
- * # Example
- * ```ts
- * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
- * ```
- */
-export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {
- const tx = api.tx.evm.call(
- subToEth(from.address),
- to.options.address,
- mkTx(to.methods).encodeABI(),
- value,
- GAS_ARGS.gas,
- await web3.eth.getGasPrice(),
- null,
- null,
- [],
- );
- const events = await submitTransactionAsync(from, tx);
- expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;
-}
-
-export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
- return (await getBalance(api, [evmToAddress(address)]))[0];
-}
-
-/**
- * Measure how much gas given closure consumes
- *
- * @param user which user balance will be checked
- */
-export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
- const before = await ethBalanceViaSub(api, user);
-
- await call();
-
- // In dev mode, the transaction might not finish processing in time
- await waitNewBlocks(api, 1);
- const after = await ethBalanceViaSub(api, user);
-
- // Can't use .to.be.less, because chai doesn't supports bigint
- expect(after < before).to.be.true;
-
- return before - after;
-}
-
-type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
-// I want a fancier api, not a memory efficiency
-export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
- if(args.length === 0) {
- yield internalRest as any;
- return;
- }
- for(const value of args[0]) {
- yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
- }
-}
\ No newline at end of file
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -27,7 +27,7 @@
import refungibleAbi from '../../reFungibleAbi.json';
import refungibleTokenAbi from '../../reFungibleTokenAbi.json';
import contractHelpersAbi from './../contractHelpersAbi.json';
-import {TEthereumAccount} from '../../../util/playgrounds/types';
+import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';
class EthGroupBase {
helper: EthUniqueHelper;
@@ -279,6 +279,15 @@
};
});
}
+
+ async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {
+ const wrappedCode = async () => {
+ await code();
+ // In dev mode, the transaction might not finish processing in time
+ await this.helper.wait.newBlocks(1);
+ };
+ return await this.helper.arrange.calculcateFee(address, wrappedCode);
+ }
}
class EthAddressGroup extends EthGroupBase {
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -40,9 +40,9 @@
const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
- const blockInterval = (helper.api!.consts.inflation.inflationBlockInterval as any).toBigInt();
- const totalIssuanceStart = ((await helper.api!.query.inflation.startingYearTotalIssuance()) as any).toBigInt();
- const blockInflation = (await helper.api!.query.inflation.blockInflation() as any).toBigInt();
+ const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
+ const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
+ const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
const YEAR = 5259600n; // 6-second block. Blocks in one year
// const YEAR = 2629800n; // 12-second block. Blocks in one year
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -276,7 +276,7 @@
itSub('Reads access rights to properties of a collection', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
- const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();
+ const propertyRights = (await helper.callRpc('api.query.common.collectionPropertyPermissions', [collection.collectionId])).toJSON();
expect(propertyRights).to.be.empty;
});
@@ -817,7 +817,7 @@
).to.be.fulfilled;
}
- const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const originalSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
return originalSpace;
}
@@ -840,7 +840,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -875,7 +875,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -911,7 +911,7 @@
expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -951,7 +951,7 @@
])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -59,7 +59,7 @@
describe('Pallet presence', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- const chain = await helper.api!.rpc.system.chain();
+ const chain = await helper.callRpc('api.rpc.system.chain', []);
const refungible = 'refungible';
const scheduler = 'scheduler';
tests/src/rmrk/acceptNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/acceptNft.test.ts
+++ b/tests/src/rmrk/acceptNft.test.ts
@@ -8,7 +8,7 @@
} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: accept NFT', () => {
let api: any;
tests/src/rmrk/addResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addResource.test.ts
+++ b/tests/src/rmrk/addResource.test.ts
@@ -12,7 +12,7 @@
addNftComposableResource,
} from './util/tx';
import {RmrkTraitsResourceResourceInfo as ResourceInfo} from '@polkadot/types/lookup';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: add NFT resource', () => {
const Alice = '//Alice';
tests/src/rmrk/addTheme.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addTheme.test.ts
+++ b/tests/src/rmrk/addTheme.test.ts
@@ -3,7 +3,7 @@
import {createBase, addTheme} from './util/tx';
import {expectTxFailure} from './util/helpers';
import {getThemeNames} from './util/fetch';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: add Theme to Base', () => {
let api: any;
tests/src/rmrk/burnNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/burnNft.test.ts
+++ b/tests/src/rmrk/burnNft.test.ts
@@ -5,7 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/rmrk/changeCollectionIssuer.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/changeCollectionIssuer.test.ts
+++ b/tests/src/rmrk/changeCollectionIssuer.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {
changeIssuer,
tests/src/rmrk/createBase.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createBase.test.ts
+++ b/tests/src/rmrk/createBase.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {createCollection, createBase} from './util/tx';
describe('integration test: create new Base', () => {
tests/src/rmrk/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createCollection.test.ts
+++ b/tests/src/rmrk/createCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {createCollection} from './util/tx';
describe('Integration test: create new collection', () => {
tests/src/rmrk/deleteCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/deleteCollection.test.ts
+++ b/tests/src/rmrk/deleteCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, deleteCollection} from './util/tx';
tests/src/rmrk/equipNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/equipNft.test.ts
+++ b/tests/src/rmrk/equipNft.test.ts
@@ -1,7 +1,7 @@
import {ApiPromise} from '@polkadot/api';
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft, getParts, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
tests/src/rmrk/getOwnedNfts.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/getOwnedNfts.test.ts
+++ b/tests/src/rmrk/getOwnedNfts.test.ts
@@ -1,6 +1,6 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getOwnedNfts} from './util/fetch';
import {mintNft, createCollection} from './util/tx';
tests/src/rmrk/lockCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/lockCollection.test.ts
+++ b/tests/src/rmrk/lockCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, lockCollection, mintNft} from './util/tx';
tests/src/rmrk/mintNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/mintNft.test.ts
+++ b/tests/src/rmrk/mintNft.test.ts
@@ -1,6 +1,6 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft} from './util/tx';
tests/src/rmrk/rejectNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rejectNft.test.ts
+++ b/tests/src/rmrk/rejectNft.test.ts
@@ -8,7 +8,7 @@
} from './util/tx';
import {getChildren, NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: reject NFT', () => {
let api: any;
tests/src/rmrk/removeResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/removeResource.test.ts
+++ b/tests/src/rmrk/removeResource.test.ts
@@ -1,7 +1,7 @@
import {expect} from 'chai';
import privateKey from '../substrate/privateKey';
import {executeTransaction, getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
tests/src/rmrk/rmrkIsolation.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rmrkIsolation.test.ts
+++ b/tests/src/rmrk/rmrkIsolation.test.ts
@@ -9,7 +9,7 @@
requirePallets,
normalizeAccountId,
Pallets,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
import {IKeyringPair} from '@polkadot/types/types';
import {ApiPromise} from '@polkadot/api';
import {it} from 'mocha';
tests/src/rmrk/sendNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/sendNft.test.ts
+++ b/tests/src/rmrk/sendNft.test.ts
@@ -3,7 +3,7 @@
import {createCollection, mintNft, sendNft} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: send NFT', () => {
let api: any;
tests/src/rmrk/setCollectionProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setCollectionProperty.test.ts
+++ b/tests/src/rmrk/setCollectionProperty.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, setPropertyCollection} from './util/tx';
tests/src/rmrk/setEquippableList.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setEquippableList.test.ts
+++ b/tests/src/rmrk/setEquippableList.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, createBase, setEquippableList} from './util/tx';
tests/src/rmrk/setNftProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setNftProperty.test.ts
+++ b/tests/src/rmrk/setNftProperty.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft, sendNft, setNftProperty} from './util/tx';
tests/src/rmrk/setResourcePriorities.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setResourcePriorities.test.ts
+++ b/tests/src/rmrk/setResourcePriorities.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {mintNft, createCollection, setResourcePriorities} from './util/tx';
tests/src/substrate/get-balance.tsdiffbeforeafterboth--- a/tests/src/substrate/get-balance.ts
+++ b/tests/src/substrate/get-balance.ts
@@ -19,7 +19,7 @@
import promisifySubstrate from './promisify-substrate';
import {IKeyringPair} from '@polkadot/types/types';
import {submitTransactionAsync} from './substrate-api';
-import {getGenericResult} from '../util/helpers';
+import {getGenericResult} from '../deprecated-helpers/helpers';
import {expect} from 'chai';
export default async function getBalance(api: ApiPromise, accounts: string[]): Promise<Array<bigint>> {
tests/src/transfer.nload.tsdiffbeforeafterboth--- a/tests/src/transfer.nload.ts
+++ b/tests/src/transfer.nload.ts
@@ -18,10 +18,24 @@
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
import waitNewBlocks from './substrate/wait-new-blocks';
-import {findUnusedAddresses} from './util/helpers';
import * as cluster from 'cluster';
import os from 'os';
+async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
+ let bal = 0n;
+ let unused;
+ do {
+ const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
+ unused = privateKeyWrapper(`//${randomSeed}`);
+ bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
+ } while (bal !== 0n);
+ return unused;
+}
+
+function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
+ return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
+}
+
// Innacurate transfer fee
const FEE = 10n ** 8n;
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- a/tests/src/tx-version-presence.test.ts
+++ b/tests/src/tx-version-presence.test.ts
@@ -22,7 +22,7 @@
describe('TxVersion is present', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- metadata = await helper.api!.rpc.state.getMetadata();
+ metadata = await helper.callRpc('api.rpc.state.getMetadata', []);
});
});
tests/src/util/contracthelpers.tsdiffbeforeafterboth--- a/tests/src/util/contracthelpers.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import fs from 'fs';
-import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
-import {IKeyringPair} from '@polkadot/types/types';
-import {ApiPromise} from '@polkadot/api';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-import {findUnusedAddress, getGenericResult} from '../util/helpers';
-
-const value = 0;
-const gasLimit = '200000000000';
-const endowment = '100000000000000000';
-
-/* eslint no-async-promise-executor: "off" */
-function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {
- return new Promise<Contract>(async (resolve) => {
- const unsub = await (code as any)
- .tx[constructor]({value: endowment, gasLimit}, ...args)
- .signAndSend(alice, (result: any) => {
- if (result.status.isInBlock || result.status.isFinalized) {
- // here we have an additional field in the result, containing the blueprint
- resolve((result as any).contract);
- unsub();
- }
- });
- });
-}
-
-async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
- // Find unused address
- const deployer = await findUnusedAddress(api, privateKeyWrapper);
-
- // Transfer balance to it
- const alice = privateKeyWrapper('//Alice');
- const amount = BigInt(endowment) + 10n**15n;
- const tx = api.tx.balances.transfer(deployer.address, amount);
- await submitTransactionAsync(alice, tx);
-
- return deployer;
-}
-
-export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
- const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
-
- const deployer = await prepareDeployer(api, privateKeyWrapper);
-
- const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
-
- const code = new CodePromise(api, abi, wasm);
-
- const contract = (await deployContract(deployer, code, 'new', true)) as Contract;
-
- const initialGetResponse = await getFlipValue(contract, deployer);
- expect(initialGetResponse).to.be.true;
-
- return [contract, deployer];
-}
-
-export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
- const result = await contract.query.get(deployer.address, {value, gasLimit});
-
- if(!result.result.isOk) {
- throw 'Failed to get flipper value';
- }
- return (result.result.asOk.data[0] == 0x00) ? false : true;
-}
-
-export async function toggleFlipValueExpectSuccess(sender: IKeyringPair, contract: Contract) {
- const tx = contract.tx.flip({value, gasLimit});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
-}
-
-export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
- const tx = contract.tx.flip({value, gasLimit});
- await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-}
-
-export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
- const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
-
- const deployer = await prepareDeployer(api, privateKeyWrapper);
-
- const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
-
- const code = new CodePromise(api, abi, wasm);
-
- const contract = await deployContract(deployer, code);
-
- return [contract, deployer];
-}
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ /dev/null
@@ -1,1879 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import '../interfaces/augment-api-rpc';
-import '../interfaces/augment-api-query';
-import {ApiPromise, Keyring} from '@polkadot/api';
-import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';
-import type {GenericEventData} from '@polkadot/types';
-import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';
-import {evmToAddress} from '@polkadot/util-crypto';
-import {AnyNumber} from '@polkadot/types-codec/types';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import {hexToStr, strToUTF16, utf16ToStr} from './util';
-import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
-import {UpDataStructsTokenChild} from '../interfaces';
-import {Context} from 'mocha';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-export type CrossAccountId = {
- Substrate: string,
-} | {
- Ethereum: string,
-};
-
-
-export enum Pallets {
- Inflation = 'inflation',
- RmrkCore = 'rmrkcore',
- RmrkEquip = 'rmrkequip',
- ReFungible = 'refungible',
- Fungible = 'fungible',
- NFT = 'nonfungible',
- Scheduler = 'scheduler',
- AppPromotion = 'apppromotion',
-}
-
-export async function isUnique(): Promise<boolean> {
- return usingApi(async api => {
- const chain = await api.rpc.system.chain();
-
- return chain.eq('UNIQUE');
- });
-}
-
-export async function isQuartz(): Promise<boolean> {
- return usingApi(async api => {
- const chain = await api.rpc.system.chain();
-
- return chain.eq('QUARTZ');
- });
-}
-
-let modulesNames: any;
-export function getModuleNames(api: ApiPromise): string[] {
- if (typeof modulesNames === 'undefined')
- modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
- return modulesNames;
-}
-
-export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
- return await usingApi(async api => {
- const pallets = getModuleNames(api);
-
- return requiredPallets.filter(p => !pallets.includes(p));
- });
-}
-
-export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {
- return (await missingRequiredPallets(requiredPallets)).length == 0;
-}
-
-export async function requirePallets(mocha: Context, requiredPallets: string[]) {
- const missingPallets = await missingRequiredPallets(requiredPallets);
-
- if (missingPallets.length > 0) {
- const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
- const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
- const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
-
- console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
-
- mocha.skip();
- }
-}
-
-export function bigIntToSub(api: ApiPromise, number: bigint) {
- return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
-}
-
-export function bigIntToDecimals(number: bigint, decimals = 18): string {
- const numberStr = number.toString();
- const dotPos = numberStr.length - decimals;
-
- if (dotPos <= 0) {
- return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
- } else {
- const intPart = numberStr.substring(0, dotPos);
- const fractPart = numberStr.substring(dotPos);
- return intPart + '.' + fractPart;
- }
-}
-
-export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
- if (typeof input === 'string') {
- if (input.length >= 47) {
- return {Substrate: input};
- } else if (input.length === 42 && input.startsWith('0x')) {
- return {Ethereum: input.toLowerCase()};
- } else if (input.length === 40 && !input.startsWith('0x')) {
- return {Ethereum: '0x' + input.toLowerCase()};
- } else {
- throw new Error(`Unknown address format: "${input}"`);
- }
- }
- if ('address' in input) {
- return {Substrate: input.address};
- }
- if ('Ethereum' in input) {
- return {
- Ethereum: input.Ethereum.toLowerCase(),
- };
- } else if ('ethereum' in input) {
- return {
- Ethereum: (input as any).ethereum.toLowerCase(),
- };
- } else if ('Substrate' in input) {
- return input;
- } else if ('substrate' in input) {
- return {
- Substrate: (input as any).substrate,
- };
- }
-
- // AccountId
- return {Substrate: input.toString()};
-}
-export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {
- input = normalizeAccountId(input);
- if ('Substrate' in input) {
- return input.Substrate;
- } else {
- return evmToAddress(input.Ethereum);
- }
-}
-
-export const U128_MAX = (1n << 128n) - 1n;
-
-const MICROUNIQUE = 1_000_000_000_000n;
-const MILLIUNIQUE = 1_000n * MICROUNIQUE;
-const CENTIUNIQUE = 10n * MILLIUNIQUE;
-export const UNIQUE = 100n * CENTIUNIQUE;
-
-interface GenericResult<T> {
- success: boolean;
- data: T | null;
-}
-
-interface CreateCollectionResult {
- success: boolean;
- collectionId: number;
-}
-
-interface CreateItemResult {
- success: boolean;
- collectionId: number;
- itemId: number;
- recipient?: CrossAccountId;
- amount?: number;
-}
-
-interface DestroyItemResult {
- success: boolean;
- collectionId: number;
- itemId: number;
- owner: CrossAccountId;
- amount: number;
-}
-
-interface TransferResult {
- collectionId: number;
- itemId: number;
- sender?: CrossAccountId;
- recipient?: CrossAccountId;
- value: bigint;
-}
-
-interface IReFungibleOwner {
- fraction: BN;
- owner: number[];
-}
-
-interface IGetMessage {
- checkMsgUnqMethod: string;
- checkMsgTrsMethod: string;
- checkMsgSysMethod: string;
-}
-
-export interface IFungibleTokenDataType {
- value: number;
-}
-
-export interface IChainLimits {
- collectionNumbersLimit: number;
- accountTokenOwnershipLimit: number;
- collectionsAdminsLimit: number;
- customDataLimit: number;
- nftSponsorTransferTimeout: number;
- fungibleSponsorTransferTimeout: number;
- refungibleSponsorTransferTimeout: number;
- //offchainSchemaLimit: number;
- //constOnChainSchemaLimit: number;
-}
-
-export interface IReFungibleTokenDataType {
- owner: IReFungibleOwner[];
-}
-
-export function uniqueEventMessage(events: EventRecord[]): IGetMessage {
- let checkMsgUnqMethod = '';
- let checkMsgTrsMethod = '';
- let checkMsgSysMethod = '';
- events.forEach(({event: {method, section}}) => {
- if (section === 'common') {
- checkMsgUnqMethod = method;
- } else if (section === 'treasury') {
- checkMsgTrsMethod = method;
- } else if (section === 'system') {
- checkMsgSysMethod = method;
- } else { return null; }
- });
- const result: IGetMessage = {
- checkMsgUnqMethod,
- checkMsgTrsMethod,
- checkMsgSysMethod,
- };
- return result;
-}
-
-export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {
- const event = events.find(r => check(r.event));
- if (!event) return;
- return event.event as T;
-}
-
-export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;
-export function getGenericResult<T>(
- events: EventRecord[],
- expectSection: string,
- expectMethod: string,
- extractAction: (data: GenericEventData) => T
-): GenericResult<T>;
-
-export function getGenericResult<T>(
- events: EventRecord[],
- expectSection?: string,
- expectMethod?: string,
- extractAction?: (data: GenericEventData) => T,
-): GenericResult<T> {
- let success = false;
- let successData = null;
-
- events.forEach(({event: {data, method, section}}) => {
- // console.log(` ${phase}: ${section}.${method}:: ${data}`);
- if (method === 'ExtrinsicSuccess') {
- success = true;
- } else if ((expectSection == section) && (expectMethod == method)) {
- successData = extractAction!(data as any);
- }
- });
-
- const result: GenericResult<T> = {
- success,
- data: successData,
- };
- return result;
-}
-
-export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
- const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));
- const result: CreateCollectionResult = {
- success: genericResult.success,
- collectionId: genericResult.data ?? 0,
- };
- return result;
-}
-
-export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {
- const results: CreateItemResult[] = [];
-
- const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {
- const collectionId = parseInt(data[0].toString(), 10);
- const itemId = parseInt(data[1].toString(), 10);
- const recipient = normalizeAccountId(data[2].toJSON() as any);
- const amount = parseInt(data[3].toString(), 10);
-
- const itemRes: CreateItemResult = {
- success: true,
- collectionId,
- itemId,
- recipient,
- amount,
- };
-
- results.push(itemRes);
- return results;
- });
-
- if (!genericResult.success) return [];
- return results;
-}
-
-export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
- const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
-
- if (genericResult.data == null)
- return {
- success: genericResult.success,
- collectionId: 0,
- itemId: 0,
- amount: 0,
- };
- else
- return {
- success: genericResult.success,
- collectionId: genericResult.data[0] as number,
- itemId: genericResult.data[1] as number,
- recipient: normalizeAccountId(genericResult.data![2] as any),
- amount: genericResult.data[3] as number,
- };
-}
-
-export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
- const results: DestroyItemResult[] = [];
-
- const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {
- const collectionId = parseInt(data[0].toString(), 10);
- const itemId = parseInt(data[1].toString(), 10);
- const owner = normalizeAccountId(data[2].toJSON() as any);
- const amount = parseInt(data[3].toString(), 10);
-
- const itemRes: DestroyItemResult = {
- success: true,
- collectionId,
- itemId,
- owner,
- amount,
- };
-
- results.push(itemRes);
- return results;
- });
-
- if (!genericResult.success) return [];
- return results;
-}
-
-export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {
- for (const {event} of events) {
- if (api.events.common.Transfer.is(event)) {
- const [collection, token, sender, recipient, value] = event.data;
- return {
- collectionId: collection.toNumber(),
- itemId: token.toNumber(),
- sender: normalizeAccountId(sender.toJSON() as any),
- recipient: normalizeAccountId(recipient.toJSON() as any),
- value: value.toBigInt(),
- };
- }
- }
- throw new Error('no transfer event');
-}
-
-interface Nft {
- type: 'NFT';
-}
-
-interface Fungible {
- type: 'Fungible';
- decimalPoints: number;
-}
-
-interface ReFungible {
- type: 'ReFungible';
-}
-
-export type CollectionMode = Nft | Fungible | ReFungible;
-
-export type Property = {
- key: any,
- value: any,
-};
-
-type Permission = {
- mutable: boolean;
- collectionAdmin: boolean;
- tokenOwner: boolean;
-}
-
-type PropertyPermission = {
- key: any;
- permission: Permission;
-}
-
-export type CreateCollectionParams = {
- mode: CollectionMode,
- name: string,
- description: string,
- tokenPrefix: string,
- properties?: Array<Property>,
- propPerm?: Array<PropertyPermission>
-};
-
-const defaultCreateCollectionParams: CreateCollectionParams = {
- description: 'description',
- mode: {type: 'NFT'},
- name: 'name',
- tokenPrefix: 'prefix',
-};
-
-export async function
-createCollection(
- api: ApiPromise,
- sender: IKeyringPair,
- params: Partial<CreateCollectionParams> = {},
-): Promise<CreateCollectionResult> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({
- name: strToUTF16(name),
- description: strToUTF16(description),
- tokenPrefix: strToUTF16(tokenPrefix),
- mode: modeprm as any,
- });
- const events = await executeTransaction(api, sender, tx);
- return getCreateCollectionResult(events);
-}
-
-export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let collectionId = 0;
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- const result = await createCollection(api, alicePrivateKey, params);
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(result.collectionId).to.be.equal(collectionCountAfter);
- // tslint:disable-next-line:no-unused-expression
- expect(collection).to.be.not.null;
- expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
- expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
- expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
- expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
- expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
- collectionId = result.collectionId;
- });
-
- return collectionId;
-}
-
-export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let collectionId = 0;
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getCreateCollectionResult(events);
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(result.collectionId).to.be.equal(collectionCountAfter);
- // tslint:disable-next-line:no-unused-expression
- expect(collection).to.be.not.null;
- expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
- expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
- expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
- expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
- expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
-
- collectionId = result.collectionId;
- });
-
- return collectionId;
-}
-
-export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
- });
-}
-
-export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // What to expect
- expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
- });
-}
-
-export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
- let bal = 0n;
- let unused;
- do {
- const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
- unused = privateKeyWrapper(`//${randomSeed}`);
- bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
- } while (bal !== 0n);
- return unused;
-}
-
-export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {
- return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();
-}
-
-export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
- return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
-}
-
-export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
- const totalNumber = await getCreatedCollectionCount(api);
- const newCollection: number = totalNumber + 1;
- return newCollection;
-}
-
-function getDestroyResult(events: EventRecord[]): boolean {
- let success = false;
- events.forEach(({event: {method}}) => {
- if (method == 'ExtrinsicSuccess') {
- success = true;
- }
- });
- return success;
-}
-
-export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
- // Run the DestroyCollection transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.destroyCollection(collectionId);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
- // Run the DestroyCollection transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.destroyCollection(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getDestroyResult(events);
- expect(result).to.be.true;
-
- // What to expect
- expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
- });
-}
-
-export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {
- await usingApi(async(api) => {
- const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-};
-
-export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const senderPrivateKey = privateKeyWrapper(sender);
- const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
- const events = await submitTransactionAsync(senderPrivateKey, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.deep.equal({
- unconfirmed: sponsor,
- });
- });
-}
-
-export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(sender);
- const tx = api.tx.unique.removeCollectionSponsor(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});
- });
-}
-
-export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.removeCollectionSponsor(collectionId);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const sender = privateKeyWrapper(senderSeed);
- await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
- });
-}
-
-export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const tx = api.tx.unique.confirmSponsorship(collectionId);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.be.deep.equal({
- confirmed: sender.address,
- });
- });
-}
-
-
-export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const sender = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.confirmSponsorship(collectionId);
- await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- });
-}
-
-export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
- await usingApi(async (api) => {
-
- const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
- await usingApi(async (api) => {
-
- const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function getNextSponsored(
- api: ApiPromise,
- collectionId: number,
- account: string | CrossAccountId,
- tokenId: number,
-): Promise<number> {
- return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
-}
-
-export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
- let allowlisted = false;
- await usingApi(async (api) => {
- allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;
- });
- return allowlisted;
-}
-
-export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export interface CreateFungibleData {
- readonly Value: bigint;
-}
-
-export interface CreateReFungibleData { }
-export interface CreateNftData { }
-
-export type CreateItemData = {
- NFT: CreateNftData;
-} | {
- Fungible: CreateFungibleData;
-} | {
- ReFungible: CreateReFungibleData;
-};
-
-export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {
- const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
- const events = await submitTransactionAsync(sender, tx);
- return getGenericResult(events).success;
-}
-
-export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
- // if burning token by admin - use adminButnItemExpectSuccess
- expect(balanceBefore >= BigInt(value)).to.be.true;
-
- expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;
-
- const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
- expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);
- });
-}
-
-export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);
- const events = await submitTransactionAsync(sender, tx);
- return getGenericResult(events).success;
- });
-}
-
-export async function
-approve(
- api: ApiPromise,
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,
-) {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await submitTransactionAsync(owner, approveUniqueTx);
- return getGenericResult(events).success;
-}
-
-export async function
-approveExpectSuccess(
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const result = await approve(api, collectionId, tokenId, owner, approved, amount);
- expect(result).to.be.true;
-
- expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
- });
-}
-
-export async function adminApproveFromExpectSuccess(
- collectionId: number,
- tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await submitTransactionAsync(admin, approveUniqueTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
- });
-}
-
-export async function
-transferFrom(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair | CrossAccountId,
- accountTo: IKeyringPair | CrossAccountId,
- value: number | bigint,
-) {
- const from = normalizeAccountId(accountFrom);
- const to = normalizeAccountId(accountTo);
- const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);
- const events = await submitTransactionAsync(accountApproved, transferFromTx);
- return getGenericResult(events).success;
-}
-
-export async function
-transferFromExpectSuccess(
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair | CrossAccountId,
- accountTo: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
- type = 'NFT',
-) {
- await usingApi(async (api: ApiPromise) => {
- const from = normalizeAccountId(accountFrom);
- const to = normalizeAccountId(accountTo);
- let balanceBefore = 0n;
- if (type === 'Fungible' || type === 'ReFungible') {
- balanceBefore = await getBalance(api, collectionId, to, tokenId);
- }
- expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;
- if (type === 'NFT') {
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
- }
- if (type === 'Fungible') {
- const balanceAfter = await getBalance(api, collectionId, to, tokenId);
- if (JSON.stringify(to) !== JSON.stringify(from)) {
- expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
- } else {
- expect(balanceAfter).to.be.equal(balanceBefore);
- }
- }
- if (type === 'ReFungible') {
- expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));
- }
- });
-}
-
-export async function
-transferFromExpectFail(
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair,
- accountTo: IKeyringPair,
- value: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);
- const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-/* eslint no-async-promise-executor: "off" */
-export async function getBlockNumber(api: ApiPromise): Promise<number> {
- return new Promise<number>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
- unsubscribe();
- resolve(head.number.toNumber());
- });
- });
-}
-
-export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {
- await usingApi(async (api) => {
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, changeAdminTx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- });
-}
-
-export async function adminApproveFromExpectFail(
- collectionId: number,
- tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;
- const result = getGenericResult(events);
- expect(result.success).to.be.false;
- });
-}
-
-export async function
-getFreeBalance(account: IKeyringPair): Promise<bigint> {
- let balance = 0n;
- await usingApi(async (api) => {
- balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
- });
-
- return balance;
-}
-
-export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {
- return usingApi(async api => {
- // We are getting a *sibling* parachain sovereign account,
- // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
- const siblingPrefix = '0x7369626c';
-
- const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);
- const suffix = '000000000000000000000000000000000000000000000000';
-
- return siblingPrefix + encodedParaId + suffix;
- });
-}
-
-export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
- const tx = api.tx.balances.transfer(target, amount);
- const events = await submitTransactionAsync(source, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-}
-
-export async function
-scheduleExpectSuccess(
- operationTx: any,
- sender: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period = 1,
- repetitions = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const blockNumber: number | undefined = await getBlockNumber(api);
- const expectedBlockNumber = blockNumber + blockSchedule;
-
- expect(blockNumber).to.be.greaterThan(0);
- const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
- scheduledId,
- expectedBlockNumber,
- repetitions > 1 ? [period, repetitions] : null,
- 0,
- {Value: operationTx as any},
- );
-
- const events = await submitTransactionAsync(sender, scheduleTx);
- expect(getGenericResult(events).success).to.be.true;
- });
-}
-
-export async function
-scheduleExpectFailure(
- operationTx: any,
- sender: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period = 1,
- repetitions = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const blockNumber: number | undefined = await getBlockNumber(api);
- const expectedBlockNumber = blockNumber + blockSchedule;
-
- expect(blockNumber).to.be.greaterThan(0);
- const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
- scheduledId,
- expectedBlockNumber,
- repetitions <= 1 ? null : [period, repetitions],
- 0,
- {Value: operationTx as any},
- );
-
- //const events =
- await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
- //expect(getGenericResult(events).success).to.be.false;
- });
-}
-
-export async function
-scheduleTransferAndWaitExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
- blockSchedule: number,
- scheduledId: string,
-) {
- await usingApi(async (api: ApiPromise) => {
- await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
-
- const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
- // sleep for n + 1 blocks
- await waitNewBlocks(blockSchedule + 1);
-
- const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
- expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
- });
-}
-
-export async function
-scheduleTransferExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
- blockSchedule: number,
- scheduledId: string,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
-
- await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
- });
-}
-
-export async function
-scheduleTransferFundsPeriodicExpectSuccess(
- amount: bigint,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period: number,
- repetitions: number,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.balances.transfer(recipient.address, amount);
-
- const balanceBefore = await getFreeBalance(recipient);
-
- await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
-
- expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
- });
-}
-
-export async function
-transfer(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint,
-) : Promise<boolean> {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await executeTransaction(api, sender, transferTx);
- return getGenericResult(events).success;
-}
-
-export async function
-transferExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
- type = 'NFT',
-) {
- await usingApi(async (api: ApiPromise) => {
- const from = normalizeAccountId(sender);
- const to = normalizeAccountId(recipient);
-
- let balanceBefore = 0n;
- if (type === 'Fungible' || type === 'ReFungible') {
- balanceBefore = await getBalance(api, collectionId, to, tokenId);
- }
-
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await executeTransaction(api, sender, transferTx);
- const result = getTransferResult(api, events);
-
- expect(result.collectionId).to.be.equal(collectionId);
- expect(result.itemId).to.be.equal(tokenId);
- expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));
- expect(result.recipient).to.be.deep.equal(to);
- expect(result.value).to.be.equal(BigInt(value));
-
- if (type === 'NFT') {
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
- }
- if (type === 'Fungible' || type === 'ReFungible') {
- const balanceAfter = await getBalance(api, collectionId, to, tokenId);
- if (JSON.stringify(to) !== JSON.stringify(from)) {
- expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
- } else {
- expect(balanceAfter).to.be.equal(balanceBefore);
- }
- }
- });
-}
-
-export async function
-transferExpectFailure(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;
- const result = getGenericResult(events);
- // if (events && Array.isArray(events)) {
- // const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- //}
- });
-}
-
-export async function
-approveExpectFail(
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);
- const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function getBalance(
- api: ApiPromise,
- collectionId: number,
- owner: string | CrossAccountId | IKeyringPair,
- token: number,
-): Promise<bigint> {
- return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();
-}
-export async function getTokenOwner(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<CrossAccountId> {
- const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;
- if (owner == null) throw new Error('owner == null');
- return normalizeAccountId(owner);
-}
-export async function getTopmostTokenOwner(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<CrossAccountId> {
- const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;
- if (owner == null) throw new Error('owner == null');
- return normalizeAccountId(owner);
-}
-export async function getTokenChildren(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
-): Promise<UpDataStructsTokenChild[]> {
- return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
-}
-export async function isTokenExists(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<boolean> {
- return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();
-}
-export async function getLastTokenId(
- api: ApiPromise,
- collectionId: number,
-): Promise<number> {
- return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();
-}
-export async function getAdminList(
- api: ApiPromise,
- collectionId: number,
-): Promise<string[]> {
- return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;
-}
-export async function getTokenProperties(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- propertyKeys: string[],
-): Promise<UpDataStructsProperty[]> {
- return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;
-}
-
-export async function createFungibleItemExpectSuccess(
- sender: IKeyringPair,
- collectionId: number,
- data: CreateFungibleData,
- owner: CrossAccountId | string = sender.address,
-) {
- return await usingApi(async (api) => {
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.true;
- return result.itemId;
- });
-}
-
-export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- expect(getGenericResult(events).success).to.be.true;
- });
-}
-
-export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemsResult(events);
-
- for (const res of result) {
- expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
- }
- });
-}
-
-export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemsResult(events);
-
- for (const res of result) {
- expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
- }
- });
-}
-
-export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
- let newItemId = 0;
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const itemCountBefore = await getLastTokenId(api, collectionId);
- const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
- let tx;
- if (createMode === 'Fungible') {
- const createData = {fungible: {value: 10}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else if (createMode === 'ReFungible') {
- const createData = {refungible: {pieces: 100}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else {
- const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});
- tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);
- }
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemResult(events);
-
- const itemCountAfter = await getLastTokenId(api, collectionId);
- const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
- if (createMode === 'NFT') {
- expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;
- }
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- if (createMode === 'Fungible') {
- expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
- } else {
- expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
- }
- expect(collectionId).to.be.equal(result.collectionId);
- expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
- expect(to).to.be.deep.equal(result.recipient);
- newItemId = result.itemId;
- });
- return newItemId;
-}
-
-export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
-
- let tx;
- if (createMode === 'NFT') {
- const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;
- tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);
- } else {
- tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
- }
-
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
- let newItemId = 0;
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const itemCountBefore = await getLastTokenId(api, collectionId);
- const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
- let tx;
- if (createMode === 'Fungible') {
- const createData = {fungible: {value: 10}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else if (createMode === 'ReFungible') {
- const createData = {refungible: {pieces: 100}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else {
- const createData = {nft: {}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- }
-
- const events = await executeTransaction(api, sender, tx);
- const result = getCreateItemResult(events);
-
- const itemCountAfter = await getLastTokenId(api, collectionId);
- const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- if (createMode === 'Fungible') {
- expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
- } else {
- expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
- }
- expect(collectionId).to.be.equal(result.collectionId);
- expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
- expect(to).to.be.deep.equal(result.recipient);
- newItemId = result.itemId;
- });
- return newItemId;
-}
-
-export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {
- const createData = {refungible: {pieces: amount}};
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);
-
- const events = await submitTransactionAsync(sender, tx);
- return getCreateItemResult(events);
-}
-
-export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setPublicAccessModeExpectSuccess(
- sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'AllowList',
-) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);
- });
-}
-
-export async function setPublicAccessModeExpectFail(
- sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'AllowList',
-) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
-}
-
-export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
-}
-
-export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
-}
-
-export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);
- });
-}
-
-export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setMintPermissionExpectSuccess(sender, collectionId, true);
-}
-
-export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.setChainLimits(limits);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
- return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
-}
-
-export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
- await usingApi(async (api) => {
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
- });
-}
-
-export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
- await usingApi(async (api) => {
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
- });
-}
-
-export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
- : Promise<UpDataStructsRpcCollection | null> => {
- return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);
-};
-
-export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
- // set global object - collectionsCount
- return (await api.rpc.unique.collectionStats()).created.toNumber();
-};
-
-export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {
- return (await api.rpc.unique.collectionById(collectionId)).unwrap();
-}
-
-export const describe_xcm = (
- process.env.RUN_XCM_TESTS
- ? describe
- : describe.skip
-);
-
-export async function waitNewBlocks(blocksCount = 1): Promise<void> {
- await usingApi(async (api) => {
- const promise = new Promise<void>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {
- if (blocksCount > 0) {
- blocksCount--;
- } else {
- unsubscribe();
- resolve();
- }
- });
- });
- return promise;
- });
-}
-
-export async function waitEvent(
- api: ApiPromise,
- maxBlocksToWait: number,
- eventSection: string,
- eventMethod: string,
-): Promise<EventRecord | null> {
-
- const promise = new Promise<EventRecord | null>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {
- const blockNumber = header.number.toHuman();
- const blockHash = header.hash;
- const eventIdStr = `${eventSection}.${eventMethod}`;
- const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
-
- console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
-
- const apiAt = await api.at(blockHash);
- const eventRecords = await apiAt.query.system.events();
-
- const neededEvent = eventRecords.find(r => {
- return r.event.section == eventSection && r.event.method == eventMethod;
- });
-
- if (neededEvent) {
- unsubscribe();
- resolve(neededEvent);
- } else if (maxBlocksToWait > 0) {
- maxBlocksToWait--;
- } else {
- console.log(`Event \`${eventIdStr}\` is NOT found`);
-
- unsubscribe();
- resolve(null);
- }
- });
- });
- return promise;
-}
-
-export async function repartitionRFT(
- api: ApiPromise,
- collectionId: number,
- sender: IKeyringPair,
- tokenId: number,
- amount: bigint,
-): Promise<boolean> {
- const tx = api.tx.unique.repartition(collectionId, tokenId, amount);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- return result.success;
-}
-
-export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: 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 usingApi(async (api, privateKeyWrapper) => {
- await cb({api, privateKeyWrapper});
- });
- });
-}
-
-itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});
-itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
-
-let accountSeed = 10000;
-export function generateKeyringPair(keyring: Keyring) {
- const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;
- return keyring.addFromUri(privateKey);
-}
-
-export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {
- const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
- const subEvents = (await api.query.system.events.at(blockHash))
- .filter(x => x.event.section === section)
- .map((x) => x.toHuman());
- const events = methods.map((m) => {
- return {
- event: {
- method: m,
- section,
- },
- };
- });
- if (!dryRun) {
- expect(subEvents).to.be.like(events);
- }
- return subEvents;
-}
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -38,6 +38,7 @@
Fungible = 'fungible',
NFT = 'nonfungible',
Scheduler = 'scheduler',
+ AppPromotion = 'apppromotion',
}
export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: string[]) {
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -215,8 +215,8 @@
};
isDevNode = async () => {
- const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));
- const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));
+ const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);
+ const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);
const findCreationDate = async (block: any) => {
const humanBlock = block.toHuman();
let date;
@@ -259,7 +259,7 @@
async newBlocks(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(() => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {
if (blocksCount > 0) {
blocksCount--;
} else {
@@ -274,7 +274,7 @@
async forParachainBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {
if (data.number.toNumber() >= blockNumber) {
unsubscribe();
resolve();
@@ -286,7 +286,7 @@
async forRelayBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {
if (data.value.relayParentNumber.toNumber() >= blockNumber) {
// @ts-ignore
unsubscribe();
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321322 constructor(logger?: ILogger) {323 this.util = UniqueUtil;324 this.eventHelper = UniqueEventHelper;325 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();326 this.logger = logger;327 this.api = null;328 this.forcedNetwork = null;329 this.network = null;330 this.chainLog = [];331 }332333 clearChainLog(): void {334 this.chainLog = [];335 }336337 forceNetwork(value: TUniqueNetworks): void {338 this.forcedNetwork = value;339 }340341 async connect(wsEndpoint: string, listeners?: IApiListeners) {342 if (this.api !== null) throw Error('Already connected');343 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);344 this.api = api;345 this.network = network;346 }347348 async disconnect() {349 if (this.api === null) return;350 await this.api.disconnect();351 this.api = null;352 this.network = null;353 }354355 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {356 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;357 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;358 return 'opal';359 }360361 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {362 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});363 await api.isReady;364365 const network = await this.detectNetwork(api);366367 await api.disconnect();368369 return network;370 }371372 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{373 api: ApiPromise;374 network: TUniqueNetworks;375 }> {376 if(typeof network === 'undefined' || network === null) network = 'opal';377 const supportedRPC = {378 opal: {379 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,380 },381 quartz: {382 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,383 },384 unique: {385 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,386 },387 };388 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);389 const rpc = supportedRPC[network];390391 // TODO: investigate how to replace rpc in runtime392 // api._rpcCore.addUserInterfaces(rpc);393394 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});395396 await api.isReadyOrError;397398 if (typeof listeners === 'undefined') listeners = {};399 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {400 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;401 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);402 }403404 return {api, network};405 }406407 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {408 const {events, status} = data;409 if (status.isReady) {410 return this.transactionStatus.NOT_READY;411 }412 if (status.isBroadcast) {413 return this.transactionStatus.NOT_READY;414 }415 if (status.isInBlock || status.isFinalized) {416 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');417 if (errors.length > 0) {418 return this.transactionStatus.FAIL;419 }420 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {421 return this.transactionStatus.SUCCESS;422 }423 }424425 return this.transactionStatus.FAIL;426 }427428 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {429 const sign = (callback: any) => {430 if(options !== null) return transaction.signAndSend(sender, options, callback);431 return transaction.signAndSend(sender, callback);432 };433 // eslint-disable-next-line no-async-promise-executor434 return new Promise(async (resolve, reject) => {435 try {436 const unsub = await sign((result: any) => {437 const status = this.getTransactionStatus(result);438439 if (status === this.transactionStatus.SUCCESS) {440 this.logger.log(`${label} successful`);441 unsub();442 resolve({result, status});443 } else if (status === this.transactionStatus.FAIL) {444 let moduleError = null;445446 if (result.hasOwnProperty('dispatchError')) {447 const dispatchError = result['dispatchError'];448449 if (dispatchError) {450 if (dispatchError.isModule) {451 const modErr = dispatchError.asModule;452 const errorMeta = dispatchError.registry.findMetaError(modErr);453454 moduleError = `${errorMeta.section}.${errorMeta.name}`;455 } else {456 moduleError = dispatchError.toHuman();457 }458 } else {459 this.logger.log(result, this.logger.level.ERROR);460 }461 }462463 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);464 unsub();465 reject({status, moduleError, result});466 }467 });468 } catch (e) {469 this.logger.log(e, this.logger.level.ERROR);470 reject(e);471 }472 });473 }474475 constructApiCall(apiCall: string, params: any[]) {476 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);477 let call = this.api as any;478 for(const part of apiCall.slice(4).split('.')) {479 call = call[part];480 }481 return call(...params);482 }483484 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {485 if(this.api === null) throw Error('API not initialized');486 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);487488 const startTime = (new Date()).getTime();489 let result: ITransactionResult;490 let events: IEvent[] = [];491 try {492 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;493 events = this.eventHelper.extractEvents(result);494 }495 catch(e) {496 if(!(e as object).hasOwnProperty('status')) throw e;497 result = e as ITransactionResult;498 }499500 const endTime = (new Date()).getTime();501502 const log = {503 executedAt: endTime,504 executionTime: endTime - startTime,505 type: this.chainLogType.EXTRINSIC,506 status: result.status,507 call: extrinsic,508 signer: this.getSignerAddress(sender),509 params,510 } as IUniqueHelperLog;511512 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;513 if(events.length > 0) log.events = events;514515 this.chainLog.push(log);516517 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);518 return result;519 }520521 async callRpc(rpc: string, params?: any[]) {522 if(typeof params === 'undefined') params = [];523 if(this.api === null) throw Error('API not initialized');524 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);525526 const startTime = (new Date()).getTime();527 let result;528 let error = null;529 const log = {530 type: this.chainLogType.RPC,531 call: rpc,532 params,533 } as IUniqueHelperLog;534535 try {536 result = await this.constructApiCall(rpc, params);537 }538 catch(e) {539 error = e;540 }541542 const endTime = (new Date()).getTime();543544 log.executedAt = endTime;545 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';546 log.executionTime = endTime - startTime;547548 this.chainLog.push(log);549550 if(error !== null) throw error;551552 return result;553 }554555 getSignerAddress(signer: IKeyringPair | string): string {556 if(typeof signer === 'string') return signer;557 return signer.address;558 }559560 fetchAllPalletNames(): string[] {561 if(this.api === null) throw Error('API not initialized');562 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());563 }564565 fetchMissingPalletNames(requiredPallets: string[]): string[] {566 const palletNames = this.fetchAllPalletNames();567 return requiredPallets.filter(p => !palletNames.includes(p));568 }569}570571572class HelperGroup {573 helper: UniqueHelper;574575 constructor(uniqueHelper: UniqueHelper) {576 this.helper = uniqueHelper;577 }578}579580581class CollectionGroup extends HelperGroup {582 /**583 * Get number of blocks when sponsored transaction is available.584 *585 * @param collectionId ID of collection586 * @param tokenId ID of token587 * @param addressObj address for which the sponsorship is checked588 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});589 * @returns number of blocks or null if sponsorship hasn't been set590 */591 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {592 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();593 }594595 /**596 * Get the number of created collections.597 *598 * @returns number of created collections599 */600 async getTotalCount(): Promise<number> {601 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();602 }603604 /**605 * Get information about the collection with additional data,606 * including the number of tokens it contains, its administrators,607 * the normalized address of the collection's owner, and decoded name and description.608 *609 * @param collectionId ID of collection610 * @example await getData(2)611 * @returns collection information object612 */613 async getData(collectionId: number): Promise<{614 id: number;615 name: string;616 description: string;617 tokensCount: number;618 admins: CrossAccountId[];619 normalizedOwner: TSubstrateAccount;620 raw: any621 } | null> {622 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);623 const humanCollection = collection.toHuman(), collectionData = {624 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],625 raw: humanCollection,626 } as any, jsonCollection = collection.toJSON();627 if (humanCollection === null) return null;628 collectionData.raw.limits = jsonCollection.limits;629 collectionData.raw.permissions = jsonCollection.permissions;630 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);631 for (const key of ['name', 'description']) {632 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);633 }634635 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))636 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)637 : 0;638 collectionData.admins = await this.getAdmins(collectionId);639640 return collectionData;641 }642643 /**644 * Get the addresses of the collection's administrators, optionally normalized.645 *646 * @param collectionId ID of collection647 * @param normalize whether to normalize the addresses to the default ss58 format648 * @example await getAdmins(1)649 * @returns array of administrators650 */651 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {652 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();653654 return normalize655 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())656 : admins;657 }658659 /**660 * Get the addresses added to the collection allow-list, optionally normalized.661 * @param collectionId ID of collection662 * @param normalize whether to normalize the addresses to the default ss58 format663 * @example await getAllowList(1)664 * @returns array of allow-listed addresses665 */666 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {667 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();668 return normalize669 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())670 : allowListed;671 }672673 /**674 * Get the effective limits of the collection instead of null for default values675 *676 * @param collectionId ID of collection677 * @example await getEffectiveLimits(2)678 * @returns object of collection limits679 */680 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {681 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();682 }683684 /**685 * Burns the collection if the signer has sufficient permissions and collection is empty.686 *687 * @param signer keyring of signer688 * @param collectionId ID of collection689 * @example await helper.collection.burn(aliceKeyring, 3);690 * @returns ```true``` if extrinsic success, otherwise ```false```691 */692 async burn(signer: TSigner, collectionId: number): Promise<boolean> {693 const result = await this.helper.executeExtrinsic(694 signer,695 'api.tx.unique.destroyCollection', [collectionId],696 true,697 );698699 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');700 }701702 /**703 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.704 *705 * @param signer keyring of signer706 * @param collectionId ID of collection707 * @param sponsorAddress Sponsor substrate address708 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")709 * @returns ```true``` if extrinsic success, otherwise ```false```710 */711 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {712 const result = await this.helper.executeExtrinsic(713 signer,714 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],715 true,716 );717718 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');719 }720721 /**722 * Confirms consent to sponsor the collection on behalf of the signer.723 *724 * @param signer keyring of signer725 * @param collectionId ID of collection726 * @example confirmSponsorship(aliceKeyring, 10)727 * @returns ```true``` if extrinsic success, otherwise ```false```728 */729 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {730 const result = await this.helper.executeExtrinsic(731 signer,732 'api.tx.unique.confirmSponsorship', [collectionId],733 true,734 );735736 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');737 }738739 /**740 * Removes the sponsor of a collection, regardless if it consented or not.741 *742 * @param signer keyring of signer743 * @param collectionId ID of collection744 * @example removeSponsor(aliceKeyring, 10)745 * @returns ```true``` if extrinsic success, otherwise ```false```746 */747 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {748 const result = await this.helper.executeExtrinsic(749 signer,750 'api.tx.unique.removeCollectionSponsor', [collectionId],751 true,752 );753754 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');755 }756757 /**758 * Sets the limits of the collection. At least one limit must be specified for a correct call.759 *760 * @param signer keyring of signer761 * @param collectionId ID of collection762 * @param limits collection limits object763 * @example764 * await setLimits(765 * aliceKeyring,766 * 10,767 * {768 * sponsorTransferTimeout: 0,769 * ownerCanDestroy: false770 * }771 * )772 * @returns ```true``` if extrinsic success, otherwise ```false```773 */774 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {775 const result = await this.helper.executeExtrinsic(776 signer,777 'api.tx.unique.setCollectionLimits', [collectionId, limits],778 true,779 );780781 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');782 }783784 /**785 * Changes the owner of the collection to the new Substrate address.786 *787 * @param signer keyring of signer788 * @param collectionId ID of collection789 * @param ownerAddress substrate address of new owner790 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")791 * @returns ```true``` if extrinsic success, otherwise ```false```792 */793 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {794 const result = await this.helper.executeExtrinsic(795 signer,796 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],797 true,798 );799800 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');801 }802803 /**804 * Adds a collection administrator.805 *806 * @param signer keyring of signer807 * @param collectionId ID of collection808 * @param adminAddressObj Administrator address (substrate or ethereum)809 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})810 * @returns ```true``` if extrinsic success, otherwise ```false```811 */812 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {813 const result = await this.helper.executeExtrinsic(814 signer,815 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],816 true,817 );818819 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');820 }821822 /**823 * Removes a collection administrator.824 *825 * @param signer keyring of signer826 * @param collectionId ID of collection827 * @param adminAddressObj Administrator address (substrate or ethereum)828 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})829 * @returns ```true``` if extrinsic success, otherwise ```false```830 */831 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {832 const result = await this.helper.executeExtrinsic(833 signer,834 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],835 true,836 );837838 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');839 }840841 /**842 * Check if user is in allow list.843 * 844 * @param collectionId ID of collection845 * @param user Account to check846 * @example await getAdmins(1)847 * @returns is user in allow list848 */849 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {850 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();851 }852853 /**854 * Adds an address to allow list855 * @param signer keyring of signer856 * @param collectionId ID of collection857 * @param addressObj address to add to the allow list858 * @returns ```true``` if extrinsic success, otherwise ```false```859 */860 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.addToAllowList', [collectionId, addressObj],864 true,865 );866867 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');868 }869870 /**871 * Removes an address from allow list872 *873 * @param signer keyring of signer874 * @param collectionId ID of collection875 * @param addressObj address to remove from the allow list876 * @returns ```true``` if extrinsic success, otherwise ```false```877 */878 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {879 const result = await this.helper.executeExtrinsic(880 signer,881 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],882 true,883 );884885 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');886 }887888 /**889 * Sets onchain permissions for selected collection.890 *891 * @param signer keyring of signer892 * @param collectionId ID of collection893 * @param permissions collection permissions object894 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});895 * @returns ```true``` if extrinsic success, otherwise ```false```896 */897 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {898 const result = await this.helper.executeExtrinsic(899 signer,900 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],901 true,902 );903904 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');905 }906907 /**908 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.909 *910 * @param signer keyring of signer911 * @param collectionId ID of collection912 * @param permissions nesting permissions object913 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});914 * @returns ```true``` if extrinsic success, otherwise ```false```915 */916 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {917 return await this.setPermissions(signer, collectionId, {nesting: permissions});918 }919920 /**921 * Disables nesting for selected collection.922 *923 * @param signer keyring of signer924 * @param collectionId ID of collection925 * @example disableNesting(aliceKeyring, 10);926 * @returns ```true``` if extrinsic success, otherwise ```false```927 */928 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {929 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});930 }931932 /**933 * Sets onchain properties to the collection.934 *935 * @param signer keyring of signer936 * @param collectionId ID of collection937 * @param properties array of property objects938 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);939 * @returns ```true``` if extrinsic success, otherwise ```false```940 */941 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {942 const result = await this.helper.executeExtrinsic(943 signer,944 'api.tx.unique.setCollectionProperties', [collectionId, properties],945 true,946 );947948 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');949 }950951 /**952 * Get collection properties.953 * 954 * @param collectionId ID of collection955 * @param propertyKeys optionally filter the returned properties to only these keys956 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);957 * @returns array of key-value pairs958 */959 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {960 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();961 }962963 /**964 * Deletes onchain properties from the collection.965 *966 * @param signer keyring of signer967 * @param collectionId ID of collection968 * @param propertyKeys array of property keys to delete969 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);970 * @returns ```true``` if extrinsic success, otherwise ```false```971 */972 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {973 const result = await this.helper.executeExtrinsic(974 signer,975 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],976 true,977 );978979 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');980 }981982 /**983 * Changes the owner of the token.984 *985 * @param signer keyring of signer986 * @param collectionId ID of collection987 * @param tokenId ID of token988 * @param addressObj address of a new owner989 * @param amount amount of tokens to be transfered. For NFT must be set to 1n990 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})991 * @returns true if the token success, otherwise false992 */993 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {994 const result = await this.helper.executeExtrinsic(995 signer,996 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],997 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,998 );9991000 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1001 }10021003 /**1004 *1005 * Change ownership of a token(s) on behalf of the owner.1006 *1007 * @param signer keyring of signer1008 * @param collectionId ID of collection1009 * @param tokenId ID of token1010 * @param fromAddressObj address on behalf of which the token will be sent1011 * @param toAddressObj new token owner1012 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1013 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1014 * @returns true if the token success, otherwise false1015 */1016 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1017 const result = await this.helper.executeExtrinsic(1018 signer,1019 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1020 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1021 );1022 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1023 }10241025 /**1026 *1027 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1028 *1029 * @param signer keyring of signer1030 * @param collectionId ID of collection1031 * @param tokenId ID of token1032 * @param amount amount of tokens to be burned. For NFT must be set to 1n1033 * @example burnToken(aliceKeyring, 10, 5);1034 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1035 */1036 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1037 const burnResult = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1040 true, // `Unable to burn token for ${label}`,1041 );1042 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1043 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1044 return burnedTokens.success;1045 }10461047 /**1048 * Destroys a concrete instance of NFT on behalf of the owner1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param tokenId ID of token1053 * @param fromAddressObj address on behalf of which the token will be burnt1054 * @param amount amount of tokens to be burned. For NFT must be set to 1n1055 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1056 * @returns ```true``` if extrinsic success, otherwise ```false```1057 */1058 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1059 const burnResult = await this.helper.executeExtrinsic(1060 signer,1061 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1062 true, // `Unable to burn token from for ${label}`,1063 );1064 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1065 return burnedTokens.success && burnedTokens.tokens.length > 0;1066 }10671068 /**1069 * Set, change, or remove approved address to transfer the ownership of the NFT.1070 *1071 * @param signer keyring of signer1072 * @param collectionId ID of collection1073 * @param tokenId ID of token1074 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1075 * @param amount amount of token to be approved. For NFT must be set to 1n1076 * @returns ```true``` if extrinsic success, otherwise ```false```1077 */1078 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1079 const approveResult = await this.helper.executeExtrinsic(1080 signer,1081 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1082 true, // `Unable to approve token for ${label}`,1083 );10841085 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1086 }10871088 /**1089 * Get the amount of token pieces approved to transfer or burn. Normally 0.1090 *1091 * @param collectionId ID of collection1092 * @param tokenId ID of token1093 * @param toAccountObj address which is approved to use token pieces1094 * @param fromAccountObj address which may have allowed the use of its owned tokens1095 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1096 * @returns number of approved to transfer pieces1097 */1098 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1099 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1100 }11011102 /**1103 * Get the last created token ID in a collection1104 *1105 * @param collectionId ID of collection1106 * @example getLastTokenId(10);1107 * @returns id of the last created token1108 */1109 async getLastTokenId(collectionId: number): Promise<number> {1110 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1111 }11121113 /**1114 * Check if token exists1115 *1116 * @param collectionId ID of collection1117 * @param tokenId ID of token1118 * @example doesTokenExist(10, 20);1119 * @returns true if the token exists, otherwise false1120 */1121 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1122 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1123 }1124}11251126class NFTnRFT extends CollectionGroup {1127 /**1128 * Get tokens owned by account1129 *1130 * @param collectionId ID of collection1131 * @param addressObj tokens owner1132 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1133 * @returns array of token ids owned by account1134 */1135 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1136 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1137 }11381139 /**1140 * Get token data1141 *1142 * @param collectionId ID of collection1143 * @param tokenId ID of token1144 * @param propertyKeys optionally filter the token properties to only these keys1145 * @param blockHashAt optionally query the data at some block with this hash1146 * @example getToken(10, 5);1147 * @returns human readable token data1148 */1149 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1150 properties: IProperty[];1151 owner: CrossAccountId;1152 normalizedOwner: CrossAccountId;1153 }| null> {1154 let tokenData;1155 if(typeof blockHashAt === 'undefined') {1156 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1157 }1158 else {1159 if(propertyKeys.length == 0) {1160 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1161 if(!collection) return null;1162 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1163 }1164 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1165 }1166 tokenData = tokenData.toHuman();1167 if (tokenData === null || tokenData.owner === null) return null;1168 const owner = {} as any;1169 for (const key of Object.keys(tokenData.owner)) {1170 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1171 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1172 : tokenData.owner[key];1173 }1174 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1175 return tokenData;1176 }11771178 /**1179 * Set permissions to change token properties1180 *1181 * @param signer keyring of signer1182 * @param collectionId ID of collection1183 * @param permissions permissions to change a property by the collection admin or token owner1184 * @example setTokenPropertyPermissions(1185 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1186 * )1187 * @returns true if extrinsic success otherwise false1188 */1189 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1190 const result = await this.helper.executeExtrinsic(1191 signer,1192 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1193 true,1194 );11951196 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1197 }11981199 /**1200 * Get token property permissions.1201 * 1202 * @param collectionId ID of collection1203 * @param propertyKeys optionally filter the returned property permissions to only these keys1204 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1205 * @returns array of key-permission pairs1206 */1207 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1208 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1209 }12101211 /**1212 * Set token properties1213 *1214 * @param signer keyring of signer1215 * @param collectionId ID of collection1216 * @param tokenId ID of token1217 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1218 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1219 * @returns ```true``` if extrinsic success, otherwise ```false```1220 */1221 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1222 const result = await this.helper.executeExtrinsic(1223 signer,1224 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1225 true,1226 );12271228 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1229 }12301231 /**1232 * Get properties, metadata assigned to a token.1233 * 1234 * @param collectionId ID of collection1235 * @param tokenId ID of token1236 * @param propertyKeys optionally filter the returned properties to only these keys1237 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1238 * @returns array of key-value pairs1239 */1240 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1241 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1242 }12431244 /**1245 * Delete the provided properties of a token1246 * @param signer keyring of signer1247 * @param collectionId ID of collection1248 * @param tokenId ID of token1249 * @param propertyKeys property keys to be deleted1250 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1251 * @returns ```true``` if extrinsic success, otherwise ```false```1252 */1253 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1254 const result = await this.helper.executeExtrinsic(1255 signer,1256 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1257 true,1258 );12591260 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1261 }12621263 /**1264 * Mint new collection1265 *1266 * @param signer keyring of signer1267 * @param collectionOptions basic collection options and properties1268 * @param mode NFT or RFT type of a collection1269 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1270 * @returns object of the created collection1271 */1272 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1273 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1274 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1275 for (const key of ['name', 'description', 'tokenPrefix']) {1276 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);1277 }1278 const creationResult = await this.helper.executeExtrinsic(1279 signer,1280 'api.tx.unique.createCollectionEx', [collectionOptions],1281 true, // errorLabel,1282 );1283 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1284 }12851286 getCollectionObject(_collectionId: number): any {1287 return null;1288 }12891290 getTokenObject(_collectionId: number, _tokenId: number): any {1291 return null;1292 }1293}129412951296class NFTGroup extends NFTnRFT {1297 /**1298 * Get collection object1299 * @param collectionId ID of collection1300 * @example getCollectionObject(2);1301 * @returns instance of UniqueNFTCollection1302 */1303 getCollectionObject(collectionId: number): UniqueNFTCollection {1304 return new UniqueNFTCollection(collectionId, this.helper);1305 }13061307 /**1308 * Get token object1309 * @param collectionId ID of collection1310 * @param tokenId ID of token1311 * @example getTokenObject(10, 5);1312 * @returns instance of UniqueNFTToken1313 */1314 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1315 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1316 }13171318 /**1319 * Get token's owner1320 * @param collectionId ID of collection1321 * @param tokenId ID of token1322 * @param blockHashAt optionally query the data at the block with this hash1323 * @example getTokenOwner(10, 5);1324 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1325 */1326 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1327 let owner;1328 if (typeof blockHashAt === 'undefined') {1329 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1330 } else {1331 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1332 }1333 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1334 }13351336 /**1337 * Is token approved to transfer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param toAccountObj address to be approved1341 * @returns ```true``` if extrinsic success, otherwise ```false```1342 */1343 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1344 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1345 }13461347 /**1348 * Changes the owner of the token.1349 *1350 * @param signer keyring of signer1351 * @param collectionId ID of collection1352 * @param tokenId ID of token1353 * @param addressObj address of a new owner1354 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1355 * @returns ```true``` if extrinsic success, otherwise ```false```1356 */1357 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1358 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1359 }13601361 /**1362 *1363 * Change ownership of a NFT on behalf of the owner.1364 *1365 * @param signer keyring of signer1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param fromAddressObj address on behalf of which the token will be sent1369 * @param toAddressObj new token owner1370 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1371 * @returns ```true``` if extrinsic success, otherwise ```false```1372 */1373 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1374 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1375 }13761377 /**1378 * Recursively find the address that owns the token1379 * @param collectionId ID of collection1380 * @param tokenId ID of token1381 * @param blockHashAt1382 * @example getTokenTopmostOwner(10, 5);1383 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1384 */1385 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1386 let owner;1387 if (typeof blockHashAt === 'undefined') {1388 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1389 } else {1390 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1391 }13921393 if (owner === null) return null;13941395 return owner.toHuman();1396 }13971398 /**1399 * Get tokens nested in the provided token1400 * @param collectionId ID of collection1401 * @param tokenId ID of token1402 * @param blockHashAt optionally query the data at the block with this hash1403 * @example getTokenChildren(10, 5);1404 * @returns tokens whose depth of nesting is <= 51405 */1406 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1407 let children;1408 if(typeof blockHashAt === 'undefined') {1409 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1410 } else {1411 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1412 }14131414 return children.toJSON().map((x: any) => {1415 return {collectionId: x.collection, tokenId: x.token};1416 });1417 }14181419 /**1420 * Nest one token into another1421 * @param signer keyring of signer1422 * @param tokenObj token to be nested1423 * @param rootTokenObj token to be parent1424 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1425 * @returns ```true``` if extrinsic success, otherwise ```false```1426 */1427 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1428 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1429 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1430 if(!result) {1431 throw Error('Unable to nest token!');1432 }1433 return result;1434 }14351436 /**1437 * Remove token from nested state1438 * @param signer keyring of signer1439 * @param tokenObj token to unnest1440 * @param rootTokenObj parent of a token1441 * @param toAddressObj address of a new token owner1442 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1443 * @returns ```true``` if extrinsic success, otherwise ```false```1444 */1445 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1446 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1447 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1448 if(!result) {1449 throw Error('Unable to unnest token!');1450 }1451 return result;1452 }14531454 /**1455 * Mint new collection1456 * @param signer keyring of signer1457 * @param collectionOptions Collection options1458 * @example1459 * mintCollection(aliceKeyring, {1460 * name: 'New',1461 * description: 'New collection',1462 * tokenPrefix: 'NEW',1463 * })1464 * @returns object of the created collection1465 */1466 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1467 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1468 }14691470 /**1471 * Mint new token1472 * @param signer keyring of signer1473 * @param data token data1474 * @returns created token object1475 */1476 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1477 const creationResult = await this.helper.executeExtrinsic(1478 signer,1479 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1480 nft: {1481 properties: data.properties,1482 },1483 }],1484 true,1485 );1486 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1487 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1488 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1489 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1490 }14911492 /**1493 * Mint multiple NFT tokens1494 * @param signer keyring of signer1495 * @param collectionId ID of collection1496 * @param tokens array of tokens with owner and properties1497 * @example1498 * mintMultipleTokens(aliceKeyring, 10, [{1499 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1500 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1501 * },{1502 * owner: {Ethereum: "0x9F0583DbB855d..."},1503 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1504 * }]);1505 * @returns ```true``` if extrinsic success, otherwise ```false```1506 */1507 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1508 const creationResult = await this.helper.executeExtrinsic(1509 signer,1510 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1511 true,1512 );1513 const collection = this.getCollectionObject(collectionId);1514 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1515 }15161517 /**1518 * Mint multiple NFT tokens with one owner1519 * @param signer keyring of signer1520 * @param collectionId ID of collection1521 * @param owner tokens owner1522 * @param tokens array of tokens with owner and properties1523 * @example1524 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1525 * properties: [{1526 * key: "gender",1527 * value: "female",1528 * },{1529 * key: "age",1530 * value: "33",1531 * }],1532 * }]);1533 * @returns array of newly created tokens1534 */1535 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1536 const rawTokens = [];1537 for (const token of tokens) {1538 const raw = {NFT: {properties: token.properties}};1539 rawTokens.push(raw);1540 }1541 const creationResult = await this.helper.executeExtrinsic(1542 signer,1543 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1544 true,1545 );1546 const collection = this.getCollectionObject(collectionId);1547 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1548 }15491550 /**1551 * Set, change, or remove approved address to transfer the ownership of the NFT.1552 *1553 * @param signer keyring of signer1554 * @param collectionId ID of collection1555 * @param tokenId ID of token1556 * @param toAddressObj address to approve1557 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1558 * @returns ```true``` if extrinsic success, otherwise ```false```1559 */1560 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1561 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1562 }1563}156415651566class RFTGroup extends NFTnRFT {1567 /**1568 * Get collection object1569 * @param collectionId ID of collection1570 * @example getCollectionObject(2);1571 * @returns instance of UniqueRFTCollection1572 */1573 getCollectionObject(collectionId: number): UniqueRFTCollection {1574 return new UniqueRFTCollection(collectionId, this.helper);1575 }15761577 /**1578 * Get token object1579 * @param collectionId ID of collection1580 * @param tokenId ID of token1581 * @example getTokenObject(10, 5);1582 * @returns instance of UniqueNFTToken1583 */1584 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1585 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1586 }15871588 /**1589 * Get top 10 token owners with the largest number of pieces1590 * @param collectionId ID of collection1591 * @param tokenId ID of token1592 * @example getTokenTop10Owners(10, 5);1593 * @returns array of top 10 owners1594 */1595 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1596 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1597 }15981599 /**1600 * Get number of pieces owned by address1601 * @param collectionId ID of collection1602 * @param tokenId ID of token1603 * @param addressObj address token owner1604 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1605 * @returns number of pieces ownerd by address1606 */1607 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1608 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1609 }16101611 /**1612 * Transfer pieces of token to another address1613 * @param signer keyring of signer1614 * @param collectionId ID of collection1615 * @param tokenId ID of token1616 * @param addressObj address of a new owner1617 * @param amount number of pieces to be transfered1618 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1619 * @returns ```true``` if extrinsic success, otherwise ```false```1620 */1621 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1622 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1623 }16241625 /**1626 * Change ownership of some pieces of RFT on behalf of the owner.1627 * @param signer keyring of signer1628 * @param collectionId ID of collection1629 * @param tokenId ID of token1630 * @param fromAddressObj address on behalf of which the token will be sent1631 * @param toAddressObj new token owner1632 * @param amount number of pieces to be transfered1633 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1634 * @returns ```true``` if extrinsic success, otherwise ```false```1635 */1636 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1637 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1638 }16391640 /**1641 * Mint new collection1642 * @param signer keyring of signer1643 * @param collectionOptions Collection options1644 * @example1645 * mintCollection(aliceKeyring, {1646 * name: 'New',1647 * description: 'New collection',1648 * tokenPrefix: 'NEW',1649 * })1650 * @returns object of the created collection1651 */1652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1653 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1654 }16551656 /**1657 * Mint new token1658 * @param signer keyring of signer1659 * @param data token data1660 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1661 * @returns created token object1662 */1663 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1667 refungible: {1668 pieces: data.pieces,1669 properties: data.properties,1670 },1671 }],1672 true,1673 );1674 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1675 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1676 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1677 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1678 }16791680 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1681 throw Error('Not implemented');1682 const creationResult = await this.helper.executeExtrinsic(1683 signer,1684 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1685 true, // `Unable to mint RFT tokens for ${label}`,1686 );1687 const collection = this.getCollectionObject(collectionId);1688 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1689 }16901691 /**1692 * Mint multiple RFT 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 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1698 * @returns array of newly created RFT tokens1699 */1700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1701 const rawTokens = [];1702 for (const token of tokens) {1703 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1704 rawTokens.push(raw);1705 }1706 const creationResult = await this.helper.executeExtrinsic(1707 signer,1708 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1709 true,1710 );1711 const collection = this.getCollectionObject(collectionId);1712 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1713 }17141715 /**1716 * Destroys a concrete instance of RFT.1717 * @param signer keyring of signer1718 * @param collectionId ID of collection1719 * @param tokenId ID of token1720 * @param amount number of pieces to be burnt1721 * @example burnToken(aliceKeyring, 10, 5);1722 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1723 */1724 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1725 return await super.burnToken(signer, collectionId, tokenId, amount);1726 }17271728 /**1729 * Destroys a concrete instance of RFT on behalf of the owner.1730 * @param signer keyring of signer1731 * @param collectionId ID of collection1732 * @param tokenId ID of token1733 * @param fromAddressObj address on behalf of which the token will be burnt1734 * @param amount number of pieces to be burnt1735 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1736 * @returns ```true``` if extrinsic success, otherwise ```false```1737 */1738 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1739 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1740 }17411742 /**1743 * Set, change, or remove approved address to transfer the ownership of the RFT.1744 *1745 * @param signer keyring of signer1746 * @param collectionId ID of collection1747 * @param tokenId ID of token1748 * @param toAddressObj address to approve1749 * @param amount number of pieces to be approved1750 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1751 * @returns true if the token success, otherwise false1752 */1753 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1754 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1755 }17561757 /**1758 * Get total number of pieces1759 * @param collectionId ID of collection1760 * @param tokenId ID of token1761 * @example getTokenTotalPieces(10, 5);1762 * @returns number of pieces1763 */1764 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1765 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1766 }17671768 /**1769 * Change number of token pieces. Signer must be the owner of all token pieces.1770 * @param signer keyring of signer1771 * @param collectionId ID of collection1772 * @param tokenId ID of token1773 * @param amount new number of pieces1774 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1775 * @returns true if the repartion was success, otherwise false1776 */1777 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1778 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1779 const repartitionResult = await this.helper.executeExtrinsic(1780 signer,1781 'api.tx.unique.repartition', [collectionId, tokenId, amount],1782 true,1783 );1784 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1785 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1786 }1787}178817891790class FTGroup extends CollectionGroup {1791 /**1792 * Get collection object1793 * @param collectionId ID of collection1794 * @example getCollectionObject(2);1795 * @returns instance of UniqueFTCollection1796 */1797 getCollectionObject(collectionId: number): UniqueFTCollection {1798 return new UniqueFTCollection(collectionId, this.helper);1799 }18001801 /**1802 * Mint new fungible collection1803 * @param signer keyring of signer1804 * @param collectionOptions Collection options1805 * @param decimalPoints number of token decimals1806 * @example1807 * mintCollection(aliceKeyring, {1808 * name: 'New',1809 * description: 'New collection',1810 * tokenPrefix: 'NEW',1811 * }, 18)1812 * @returns newly created fungible collection1813 */1814 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1815 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1816 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1817 collectionOptions.mode = {fungible: decimalPoints};1818 for (const key of ['name', 'description', 'tokenPrefix']) {1819 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);1820 }1821 const creationResult = await this.helper.executeExtrinsic(1822 signer,1823 'api.tx.unique.createCollectionEx', [collectionOptions],1824 true,1825 );1826 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1827 }18281829 /**1830 * Mint tokens1831 * @param signer keyring of signer1832 * @param collectionId ID of collection1833 * @param owner address owner of new tokens1834 * @param amount amount of tokens to be meanted1835 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1836 * @returns ```true``` if extrinsic success, otherwise ```false```1837 */1838 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1839 const creationResult = await this.helper.executeExtrinsic(1840 signer,1841 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1842 fungible: {1843 value: amount,1844 },1845 }],1846 true, // `Unable to mint fungible tokens for ${label}`,1847 );1848 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1849 }18501851 /**1852 * Mint multiple Fungible tokens with one owner1853 * @param signer keyring of signer1854 * @param collectionId ID of collection1855 * @param owner tokens owner1856 * @param tokens array of tokens with properties and pieces1857 * @returns ```true``` if extrinsic success, otherwise ```false```1858 */1859 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1860 const rawTokens = [];1861 for (const token of tokens) {1862 const raw = {Fungible: {Value: token.value}};1863 rawTokens.push(raw);1864 }1865 const creationResult = await this.helper.executeExtrinsic(1866 signer,1867 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1868 true,1869 );1870 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1871 }18721873 /**1874 * Get the top 10 owners with the largest balance for the Fungible collection1875 * @param collectionId ID of collection1876 * @example getTop10Owners(10);1877 * @returns array of ```ICrossAccountId```1878 */1879 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1880 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1881 }18821883 /**1884 * Get account balance1885 * @param collectionId ID of collection1886 * @param addressObj address of owner1887 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1888 * @returns amount of fungible tokens owned by address1889 */1890 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1891 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1892 }18931894 /**1895 * Transfer tokens to address1896 * @param signer keyring of signer1897 * @param collectionId ID of collection1898 * @param toAddressObj address recipient1899 * @param amount amount of tokens to be sent1900 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1901 * @returns ```true``` if extrinsic success, otherwise ```false```1902 */1903 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1904 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1905 }19061907 /**1908 * Transfer some tokens on behalf of the owner.1909 * @param signer keyring of signer1910 * @param collectionId ID of collection1911 * @param fromAddressObj address on behalf of which tokens will be sent1912 * @param toAddressObj address where token to be sent1913 * @param amount number of tokens to be sent1914 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1915 * @returns ```true``` if extrinsic success, otherwise ```false```1916 */1917 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1918 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1919 }19201921 /**1922 * Destroy some amount of tokens1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param amount amount of tokens to be destroyed1926 * @example burnTokens(aliceKeyring, 10, 1000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1930 return await super.burnToken(signer, collectionId, 0, amount);1931 }19321933 /**1934 * Burn some tokens on behalf of the owner.1935 * @param signer keyring of signer1936 * @param collectionId ID of collection1937 * @param fromAddressObj address on behalf of which tokens will be burnt1938 * @param amount amount of tokens to be burnt1939 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1940 * @returns ```true``` if extrinsic success, otherwise ```false```1941 */1942 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1943 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1944 }19451946 /**1947 * Get total collection supply1948 * @param collectionId1949 * @returns1950 */1951 async getTotalPieces(collectionId: number): Promise<bigint> {1952 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1953 }19541955 /**1956 * Set, change, or remove approved address to transfer tokens.1957 *1958 * @param signer keyring of signer1959 * @param collectionId ID of collection1960 * @param toAddressObj address to be approved1961 * @param amount amount of tokens to be approved1962 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1963 * @returns ```true``` if extrinsic success, otherwise ```false```1964 */1965 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1966 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1967 }19681969 /**1970 * Get amount of fungible tokens approved to transfer1971 * @param collectionId ID of collection1972 * @param fromAddressObj owner of tokens1973 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1974 * @returns number of tokens approved for the transfer1975 */1976 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1977 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1978 }1979}198019811982class ChainGroup extends HelperGroup {1983 /**1984 * Get system properties of a chain1985 * @example getChainProperties();1986 * @returns ss58Format, token decimals, and token symbol1987 */1988 getChainProperties(): IChainProperties {1989 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1990 return {1991 ss58Format: properties.ss58Format.toJSON(),1992 tokenDecimals: properties.tokenDecimals.toJSON(),1993 tokenSymbol: properties.tokenSymbol.toJSON(),1994 };1995 }19961997 /**1998 * Get chain header1999 * @example getLatestBlockNumber();2000 * @returns the number of the last block2001 */2002 async getLatestBlockNumber(): Promise<number> {2003 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2004 }20052006 /**2007 * Get block hash by block number2008 * @param blockNumber number of block2009 * @example getBlockHashByNumber(12345);2010 * @returns hash of a block2011 */2012 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2013 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2014 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2015 return blockHash;2016 }20172018 // TODO add docs2019 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2020 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2021 if (!blockHash) return null;2022 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2023 }20242025 /**2026 * Get account nonce2027 * @param address substrate address2028 * @example getNonce("5GrwvaEF5zXb26Fz...");2029 * @returns number, account's nonce2030 */2031 async getNonce(address: TSubstrateAccount): Promise<number> {2032 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2033 }2034}203520362037class BalanceGroup extends HelperGroup {2038 getCollectionCreationPrice(): bigint {2039 return 2n * this.helper.balance.getOneTokenNominal();2040 }2041 /**2042 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2043 * @example getOneTokenNominal()2044 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2045 */2046 getOneTokenNominal(): bigint {2047 const chainProperties = this.helper.chain.getChainProperties();2048 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2049 }20502051 /**2052 * Get substrate address balance2053 * @param address substrate address2054 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2055 * @returns amount of tokens on address2056 */2057 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2058 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2059 }20602061 /**2062 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2063 * @param address substrate address2064 * @returns2065 */2066 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2067 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2068 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2069 }20702071 /**2072 * Get ethereum address balance2073 * @param address ethereum address2074 * @example getEthereum("0x9F0583DbB855d...")2075 * @returns amount of tokens on address2076 */2077 async getEthereum(address: TEthereumAccount): Promise<bigint> {2078 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2079 }20802081 /**2082 * Transfer tokens to substrate address2083 * @param signer keyring of signer2084 * @param address substrate address of a recipient2085 * @param amount amount of tokens to be transfered2086 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2087 * @returns ```true``` if extrinsic success, otherwise ```false```2088 */2089 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2090 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}`*/);20912092 let transfer = {from: null, to: null, amount: 0n} as any;2093 result.result.events.forEach(({event: {data, method, section}}) => {2094 if ((section === 'balances') && (method === 'Transfer')) {2095 transfer = {2096 from: this.helper.address.normalizeSubstrate(data[0]),2097 to: this.helper.address.normalizeSubstrate(data[1]),2098 amount: BigInt(data[2]),2099 };2100 }2101 });2102 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2103 && this.helper.address.normalizeSubstrate(address) === transfer.to 2104 && BigInt(amount) === transfer.amount;2105 return isSuccess;2106 }2107}210821092110class AddressGroup extends HelperGroup {2111 /**2112 * Normalizes the address to the specified ss58 format, by default ```42```.2113 * @param address substrate address2114 * @param ss58Format format for address conversion, by default ```42```2115 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2116 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2117 */2118 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2119 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2120 }21212122 /**2123 * Get address in the connected chain format2124 * @param address substrate address2125 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2126 * @returns address in chain format2127 */2128 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2129 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2130 }21312132 /**2133 * Get substrate mirror of an ethereum address2134 * @param ethAddress ethereum address2135 * @param toChainFormat false for normalized account2136 * @example ethToSubstrate('0x9F0583DbB855d...')2137 * @returns substrate mirror of a provided ethereum address2138 */2139 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2140 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2141 }21422143 /**2144 * Get ethereum mirror of a substrate address2145 * @param subAddress substrate account2146 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2147 * @returns ethereum mirror of a provided substrate address2148 */2149 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2150 return CrossAccountId.translateSubToEth(subAddress);2151 }2152}21532154class StakingGroup extends HelperGroup {2155 /**2156 * Stake tokens for App Promotion2157 * @param signer keyring of signer2158 * @param amountToStake amount of tokens to stake2159 * @param label extra label for log2160 * @returns2161 */2162 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2163 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2164 const _stakeResult = await this.helper.executeExtrinsic(2165 signer, 'api.tx.appPromotion.stake',2166 [amountToStake], true,2167 );2168 // TODO extract info from stakeResult2169 return true;2170 }21712172 /**2173 * Unstake tokens for App Promotion2174 * @param signer keyring of signer2175 * @param amountToUnstake amount of tokens to unstake2176 * @param label extra label for log2177 * @returns block number where balances will be unlocked2178 */2179 async unstake(signer: TSigner, label?: string): Promise<number> {2180 if(typeof label === 'undefined') label = `${signer.address}`;2181 const _unstakeResult = await this.helper.executeExtrinsic(2182 signer, 'api.tx.appPromotion.unstake',2183 [], true,2184 );2185 // TODO extract block number fron events2186 return 1;2187 }21882189 /**2190 * Get total staked amount for address2191 * @param address substrate or ethereum address2192 * @returns total staked amount2193 */2194 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2195 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2196 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2197 }21982199 /**2200 * Get total staked per block2201 * @param address substrate or ethereum address2202 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2203 */2204 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2205 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2206 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2207 return { 2208 block: block.toBigInt(),2209 amount: amount.toBigInt(),2210 };2211 });2212 }22132214 /**2215 * Get total pending unstake amount for address2216 * @param address substrate or ethereum address2217 * @returns total pending unstake amount2218 */2219 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2220 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2221 }22222223 /**2224 * Get pending unstake amount per block for address2225 * @param address substrate or ethereum address2226 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2227 */2228 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2229 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2230 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2231 return {2232 block: block.toBigInt(),2233 amount: amount.toBigInt(),2234 };2235 });2236 return result;2237 }2238}22392240export class UniqueHelper extends ChainHelperBase {2241 chain: ChainGroup;2242 balance: BalanceGroup;2243 address: AddressGroup;2244 collection: CollectionGroup;2245 nft: NFTGroup;2246 rft: RFTGroup;2247 ft: FTGroup;2248 staking: StakingGroup;22492250 constructor(logger?: ILogger) {2251 super(logger);2252 this.chain = new ChainGroup(this);2253 this.balance = new BalanceGroup(this);2254 this.address = new AddressGroup(this);2255 this.collection = new CollectionGroup(this);2256 this.nft = new NFTGroup(this);2257 this.rft = new RFTGroup(this);2258 this.ft = new FTGroup(this);2259 this.staking = new StakingGroup(this);2260 }2261}226222632264export class UniqueBaseCollection {2265 helper: UniqueHelper;2266 collectionId: number;22672268 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2269 this.collectionId = collectionId;2270 this.helper = uniqueHelper;2271 }22722273 async getData() {2274 return await this.helper.collection.getData(this.collectionId);2275 }22762277 async getLastTokenId() {2278 return await this.helper.collection.getLastTokenId(this.collectionId);2279 }22802281 async doesTokenExist(tokenId: number) {2282 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2283 }22842285 async getAdmins() {2286 return await this.helper.collection.getAdmins(this.collectionId);2287 }22882289 async getAllowList() {2290 return await this.helper.collection.getAllowList(this.collectionId);2291 }22922293 async getEffectiveLimits() {2294 return await this.helper.collection.getEffectiveLimits(this.collectionId);2295 }22962297 async getProperties(propertyKeys?: string[] | null) {2298 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2299 }23002301 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2302 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2303 }23042305 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2306 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2307 }23082309 async confirmSponsorship(signer: TSigner) {2310 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2311 }23122313 async removeSponsor(signer: TSigner) {2314 return await this.helper.collection.removeSponsor(signer, this.collectionId);2315 }23162317 async setLimits(signer: TSigner, limits: ICollectionLimits) {2318 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2319 }23202321 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2322 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2323 }23242325 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2326 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2327 }23282329 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2330 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2331 }23322333 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2334 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2335 }23362337 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2338 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2339 }23402341 async setProperties(signer: TSigner, properties: IProperty[]) {2342 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2343 }23442345 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2346 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2347 }23482349 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2350 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2351 }23522353 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2354 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2355 }23562357 async disableNesting(signer: TSigner) {2358 return await this.helper.collection.disableNesting(signer, this.collectionId);2359 }23602361 async burn(signer: TSigner) {2362 return await this.helper.collection.burn(signer, this.collectionId);2363 }2364}236523662367export class UniqueNFTCollection extends UniqueBaseCollection {2368 getTokenObject(tokenId: number) {2369 return new UniqueNFToken(tokenId, this);2370 }23712372 async getTokensByAddress(addressObj: ICrossAccountId) {2373 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2374 }23752376 async getToken(tokenId: number, blockHashAt?: string) {2377 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2378 }23792380 async getTokenOwner(tokenId: number, blockHashAt?: string) {2381 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2382 }23832384 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2385 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2386 }23872388 async getTokenChildren(tokenId: number, blockHashAt?: string) {2389 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2390 }23912392 async getPropertyPermissions(propertyKeys: string[] | null = null) {2393 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2394 }23952396 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2397 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2398 }23992400 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2401 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2402 }24032404 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2405 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2406 }24072408 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2409 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2410 }24112412 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2413 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2414 }24152416 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2417 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2418 }24192420 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2421 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2422 }24232424 async burnToken(signer: TSigner, tokenId: number) {2425 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2426 }24272428 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2429 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2430 }24312432 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2433 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2434 }24352436 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2437 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2438 }24392440 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2441 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2442 }24432444 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2445 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2446 }24472448 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2449 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2450 }2451}245224532454export class UniqueRFTCollection extends UniqueBaseCollection {2455 getTokenObject(tokenId: number) {2456 return new UniqueRFToken(tokenId, this);2457 }24582459 async getToken(tokenId: number, blockHashAt?: string) {2460 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2461 }24622463 async getTokensByAddress(addressObj: ICrossAccountId) {2464 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2465 }24662467 async getTop10TokenOwners(tokenId: number) {2468 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2469 }24702471 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2472 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2473 }24742475 async getTokenTotalPieces(tokenId: number) {2476 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2477 }24782479 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2480 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2481 }24822483 async getPropertyPermissions(propertyKeys: string[] | null = null) {2484 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2485 }24862487 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2488 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2489 }24902491 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2492 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2493 }24942495 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2496 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2497 }24982499 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2500 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2501 }25022503 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2504 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2505 }25062507 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2508 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2509 }25102511 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2512 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2513 }25142515 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2516 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2517 }25182519 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2520 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2521 }25222523 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2524 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2525 }25262527 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2528 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2529 }25302531 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2532 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2533 }2534}253525362537export class UniqueFTCollection extends UniqueBaseCollection {2538 async getBalance(addressObj: ICrossAccountId) {2539 return await this.helper.ft.getBalance(this.collectionId, addressObj);2540 }25412542 async getTotalPieces() {2543 return await this.helper.ft.getTotalPieces(this.collectionId);2544 }25452546 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2547 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2548 }25492550 async getTop10Owners() {2551 return await this.helper.ft.getTop10Owners(this.collectionId);2552 }25532554 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2555 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2556 }25572558 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2559 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2560 }25612562 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2563 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2564 }25652566 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2567 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2568 }25692570 async burnTokens(signer: TSigner, amount=1n) {2571 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2572 }25732574 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2575 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2576 }25772578 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2579 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2580 }2581}258225832584export class UniqueBaseToken {2585 collection: UniqueNFTCollection | UniqueRFTCollection;2586 collectionId: number;2587 tokenId: number;25882589 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2590 this.collection = collection;2591 this.collectionId = collection.collectionId;2592 this.tokenId = tokenId;2593 }25942595 async getNextSponsored(addressObj: ICrossAccountId) {2596 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2597 }25982599 async getProperties(propertyKeys?: string[] | null) {2600 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2601 }26022603 async setProperties(signer: TSigner, properties: IProperty[]) {2604 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2605 }26062607 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2608 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2609 }26102611 async doesExist() {2612 return await this.collection.doesTokenExist(this.tokenId);2613 }26142615 nestingAccount() {2616 return this.collection.helper.util.getTokenAccount(this);2617 }2618}261926202621export class UniqueNFToken extends UniqueBaseToken {2622 collection: UniqueNFTCollection;26232624 constructor(tokenId: number, collection: UniqueNFTCollection) {2625 super(tokenId, collection);2626 this.collection = collection;2627 }26282629 async getData(blockHashAt?: string) {2630 return await this.collection.getToken(this.tokenId, blockHashAt);2631 }26322633 async getOwner(blockHashAt?: string) {2634 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2635 }26362637 async getTopmostOwner(blockHashAt?: string) {2638 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2639 }26402641 async getChildren(blockHashAt?: string) {2642 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2643 }26442645 async nest(signer: TSigner, toTokenObj: IToken) {2646 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2647 }26482649 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2650 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2651 }26522653 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2654 return await this.collection.transferToken(signer, this.tokenId, addressObj);2655 }26562657 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2658 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2659 }26602661 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2662 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2663 }26642665 async isApproved(toAddressObj: ICrossAccountId) {2666 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2667 }26682669 async burn(signer: TSigner) {2670 return await this.collection.burnToken(signer, this.tokenId);2671 }26722673 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2674 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2675 }2676}26772678export class UniqueRFToken extends UniqueBaseToken {2679 collection: UniqueRFTCollection;26802681 constructor(tokenId: number, collection: UniqueRFTCollection) {2682 super(tokenId, collection);2683 this.collection = collection;2684 }26852686 async getData(blockHashAt?: string) {2687 return await this.collection.getToken(this.tokenId, blockHashAt);2688 }26892690 async getTop10Owners() {2691 return await this.collection.getTop10TokenOwners(this.tokenId);2692 }26932694 async getBalance(addressObj: ICrossAccountId) {2695 return await this.collection.getTokenBalance(this.tokenId, addressObj);2696 }26972698 async getTotalPieces() {2699 return await this.collection.getTokenTotalPieces(this.tokenId);2700 }27012702 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2703 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2704 }27052706 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2707 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2708 }27092710 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2711 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2712 }27132714 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2715 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2716 }27172718 async repartition(signer: TSigner, amount: bigint) {2719 return await this.collection.repartitionToken(signer, this.tokenId, amount);2720 }27212722 async burn(signer: TSigner, amount=1n) {2723 return await this.collection.burnToken(signer, this.tokenId, amount);2724 }27252726 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2727 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2728 }2729}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321322 constructor(logger?: ILogger) {323 this.util = UniqueUtil;324 this.eventHelper = UniqueEventHelper;325 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();326 this.logger = logger;327 this.api = null;328 this.forcedNetwork = null;329 this.network = null;330 this.chainLog = [];331 }332333 getApi(): ApiPromise {334 if(this.api === null) throw Error('API not initialized');335 return this.api;336 }337338 clearChainLog(): void {339 this.chainLog = [];340 }341342 forceNetwork(value: TUniqueNetworks): void {343 this.forcedNetwork = value;344 }345346 async connect(wsEndpoint: string, listeners?: IApiListeners) {347 if (this.api !== null) throw Error('Already connected');348 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);349 this.api = api;350 this.network = network;351 }352353 async disconnect() {354 if (this.api === null) return;355 await this.api.disconnect();356 this.api = null;357 this.network = null;358 }359360 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {361 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;362 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;363 return 'opal';364 }365366 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {367 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});368 await api.isReady;369370 const network = await this.detectNetwork(api);371372 await api.disconnect();373374 return network;375 }376377 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{378 api: ApiPromise;379 network: TUniqueNetworks;380 }> {381 if(typeof network === 'undefined' || network === null) network = 'opal';382 const supportedRPC = {383 opal: {384 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,385 },386 quartz: {387 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,388 },389 unique: {390 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,391 },392 };393 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);394 const rpc = supportedRPC[network];395396 // TODO: investigate how to replace rpc in runtime397 // api._rpcCore.addUserInterfaces(rpc);398399 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});400401 await api.isReadyOrError;402403 if (typeof listeners === 'undefined') listeners = {};404 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {405 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;406 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);407 }408409 return {api, network};410 }411412 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {413 const {events, status} = data;414 if (status.isReady) {415 return this.transactionStatus.NOT_READY;416 }417 if (status.isBroadcast) {418 return this.transactionStatus.NOT_READY;419 }420 if (status.isInBlock || status.isFinalized) {421 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');422 if (errors.length > 0) {423 return this.transactionStatus.FAIL;424 }425 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {426 return this.transactionStatus.SUCCESS;427 }428 }429430 return this.transactionStatus.FAIL;431 }432433 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {434 const sign = (callback: any) => {435 if(options !== null) return transaction.signAndSend(sender, options, callback);436 return transaction.signAndSend(sender, callback);437 };438 // eslint-disable-next-line no-async-promise-executor439 return new Promise(async (resolve, reject) => {440 try {441 const unsub = await sign((result: any) => {442 const status = this.getTransactionStatus(result);443444 if (status === this.transactionStatus.SUCCESS) {445 this.logger.log(`${label} successful`);446 unsub();447 resolve({result, status});448 } else if (status === this.transactionStatus.FAIL) {449 let moduleError = null;450451 if (result.hasOwnProperty('dispatchError')) {452 const dispatchError = result['dispatchError'];453454 if (dispatchError) {455 if (dispatchError.isModule) {456 const modErr = dispatchError.asModule;457 const errorMeta = dispatchError.registry.findMetaError(modErr);458459 moduleError = `${errorMeta.section}.${errorMeta.name}`;460 } else {461 moduleError = dispatchError.toHuman();462 }463 } else {464 this.logger.log(result, this.logger.level.ERROR);465 }466 }467468 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);469 unsub();470 reject({status, moduleError, result});471 }472 });473 } catch (e) {474 this.logger.log(e, this.logger.level.ERROR);475 reject(e);476 }477 });478 }479480 constructApiCall(apiCall: string, params: any[]) {481 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);482 let call = this.api as any;483 for(const part of apiCall.slice(4).split('.')) {484 call = call[part];485 }486 return call(...params);487 }488489 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {490 if(this.api === null) throw Error('API not initialized');491 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);492493 const startTime = (new Date()).getTime();494 let result: ITransactionResult;495 let events: IEvent[] = [];496 try {497 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;498 events = this.eventHelper.extractEvents(result);499 }500 catch(e) {501 if(!(e as object).hasOwnProperty('status')) throw e;502 result = e as ITransactionResult;503 }504505 const endTime = (new Date()).getTime();506507 const log = {508 executedAt: endTime,509 executionTime: endTime - startTime,510 type: this.chainLogType.EXTRINSIC,511 status: result.status,512 call: extrinsic,513 signer: this.getSignerAddress(sender),514 params,515 } as IUniqueHelperLog;516517 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;518 if(events.length > 0) log.events = events;519520 this.chainLog.push(log);521522 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);523 return result;524 }525526 async callRpc(rpc: string, params?: any[]) {527 if(typeof params === 'undefined') params = [];528 if(this.api === null) throw Error('API not initialized');529 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);530531 const startTime = (new Date()).getTime();532 let result;533 let error = null;534 const log = {535 type: this.chainLogType.RPC,536 call: rpc,537 params,538 } as IUniqueHelperLog;539540 try {541 result = await this.constructApiCall(rpc, params);542 }543 catch(e) {544 error = e;545 }546547 const endTime = (new Date()).getTime();548549 log.executedAt = endTime;550 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';551 log.executionTime = endTime - startTime;552553 this.chainLog.push(log);554555 if(error !== null) throw error;556557 return result;558 }559560 getSignerAddress(signer: IKeyringPair | string): string {561 if(typeof signer === 'string') return signer;562 return signer.address;563 }564565 fetchAllPalletNames(): string[] {566 if(this.api === null) throw Error('API not initialized');567 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());568 }569570 fetchMissingPalletNames(requiredPallets: string[]): string[] {571 const palletNames = this.fetchAllPalletNames();572 return requiredPallets.filter(p => !palletNames.includes(p));573 }574}575576577class HelperGroup {578 helper: UniqueHelper;579580 constructor(uniqueHelper: UniqueHelper) {581 this.helper = uniqueHelper;582 }583}584585586class CollectionGroup extends HelperGroup {587 /**588 * Get number of blocks when sponsored transaction is available.589 *590 * @param collectionId ID of collection591 * @param tokenId ID of token592 * @param addressObj address for which the sponsorship is checked593 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});594 * @returns number of blocks or null if sponsorship hasn't been set595 */596 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {597 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();598 }599600 /**601 * Get the number of created collections.602 *603 * @returns number of created collections604 */605 async getTotalCount(): Promise<number> {606 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();607 }608609 /**610 * Get information about the collection with additional data,611 * including the number of tokens it contains, its administrators,612 * the normalized address of the collection's owner, and decoded name and description.613 *614 * @param collectionId ID of collection615 * @example await getData(2)616 * @returns collection information object617 */618 async getData(collectionId: number): Promise<{619 id: number;620 name: string;621 description: string;622 tokensCount: number;623 admins: CrossAccountId[];624 normalizedOwner: TSubstrateAccount;625 raw: any626 } | null> {627 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);628 const humanCollection = collection.toHuman(), collectionData = {629 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],630 raw: humanCollection,631 } as any, jsonCollection = collection.toJSON();632 if (humanCollection === null) return null;633 collectionData.raw.limits = jsonCollection.limits;634 collectionData.raw.permissions = jsonCollection.permissions;635 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);636 for (const key of ['name', 'description']) {637 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);638 }639640 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))641 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)642 : 0;643 collectionData.admins = await this.getAdmins(collectionId);644645 return collectionData;646 }647648 /**649 * Get the addresses of the collection's administrators, optionally normalized.650 *651 * @param collectionId ID of collection652 * @param normalize whether to normalize the addresses to the default ss58 format653 * @example await getAdmins(1)654 * @returns array of administrators655 */656 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {657 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();658659 return normalize660 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())661 : admins;662 }663664 /**665 * Get the addresses added to the collection allow-list, optionally normalized.666 * @param collectionId ID of collection667 * @param normalize whether to normalize the addresses to the default ss58 format668 * @example await getAllowList(1)669 * @returns array of allow-listed addresses670 */671 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {672 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();673 return normalize674 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())675 : allowListed;676 }677678 /**679 * Get the effective limits of the collection instead of null for default values680 *681 * @param collectionId ID of collection682 * @example await getEffectiveLimits(2)683 * @returns object of collection limits684 */685 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {686 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();687 }688689 /**690 * Burns the collection if the signer has sufficient permissions and collection is empty.691 *692 * @param signer keyring of signer693 * @param collectionId ID of collection694 * @example await helper.collection.burn(aliceKeyring, 3);695 * @returns ```true``` if extrinsic success, otherwise ```false```696 */697 async burn(signer: TSigner, collectionId: number): Promise<boolean> {698 const result = await this.helper.executeExtrinsic(699 signer,700 'api.tx.unique.destroyCollection', [collectionId],701 true,702 );703704 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');705 }706707 /**708 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.709 *710 * @param signer keyring of signer711 * @param collectionId ID of collection712 * @param sponsorAddress Sponsor substrate address713 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")714 * @returns ```true``` if extrinsic success, otherwise ```false```715 */716 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],720 true,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');724 }725726 /**727 * Confirms consent to sponsor the collection on behalf of the signer.728 *729 * @param signer keyring of signer730 * @param collectionId ID of collection731 * @example confirmSponsorship(aliceKeyring, 10)732 * @returns ```true``` if extrinsic success, otherwise ```false```733 */734 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {735 const result = await this.helper.executeExtrinsic(736 signer,737 'api.tx.unique.confirmSponsorship', [collectionId],738 true,739 );740741 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');742 }743744 /**745 * Removes the sponsor of a collection, regardless if it consented or not.746 *747 * @param signer keyring of signer748 * @param collectionId ID of collection749 * @example removeSponsor(aliceKeyring, 10)750 * @returns ```true``` if extrinsic success, otherwise ```false```751 */752 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {753 const result = await this.helper.executeExtrinsic(754 signer,755 'api.tx.unique.removeCollectionSponsor', [collectionId],756 true,757 );758759 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');760 }761762 /**763 * Sets the limits of the collection. At least one limit must be specified for a correct call.764 *765 * @param signer keyring of signer766 * @param collectionId ID of collection767 * @param limits collection limits object768 * @example769 * await setLimits(770 * aliceKeyring,771 * 10,772 * {773 * sponsorTransferTimeout: 0,774 * ownerCanDestroy: false775 * }776 * )777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.setCollectionLimits', [collectionId, limits],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');787 }788789 /**790 * Changes the owner of the collection to the new Substrate address.791 *792 * @param signer keyring of signer793 * @param collectionId ID of collection794 * @param ownerAddress substrate address of new owner795 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")796 * @returns ```true``` if extrinsic success, otherwise ```false```797 */798 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {799 const result = await this.helper.executeExtrinsic(800 signer,801 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],802 true,803 );804805 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');806 }807808 /**809 * Adds a collection administrator.810 *811 * @param signer keyring of signer812 * @param collectionId ID of collection813 * @param adminAddressObj Administrator address (substrate or ethereum)814 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})815 * @returns ```true``` if extrinsic success, otherwise ```false```816 */817 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {818 const result = await this.helper.executeExtrinsic(819 signer,820 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],821 true,822 );823824 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');825 }826827 /**828 * Removes a collection administrator.829 *830 * @param signer keyring of signer831 * @param collectionId ID of collection832 * @param adminAddressObj Administrator address (substrate or ethereum)833 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})834 * @returns ```true``` if extrinsic success, otherwise ```false```835 */836 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {837 const result = await this.helper.executeExtrinsic(838 signer,839 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],840 true,841 );842843 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');844 }845846 /**847 * Check if user is in allow list.848 * 849 * @param collectionId ID of collection850 * @param user Account to check851 * @example await getAdmins(1)852 * @returns is user in allow list853 */854 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {855 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();856 }857858 /**859 * Adds an address to allow list860 * @param signer keyring of signer861 * @param collectionId ID of collection862 * @param addressObj address to add to the allow list863 * @returns ```true``` if extrinsic success, otherwise ```false```864 */865 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {866 const result = await this.helper.executeExtrinsic(867 signer,868 'api.tx.unique.addToAllowList', [collectionId, addressObj],869 true,870 );871872 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');873 }874875 /**876 * Removes an address from allow list877 *878 * @param signer keyring of signer879 * @param collectionId ID of collection880 * @param addressObj address to remove from the allow list881 * @returns ```true``` if extrinsic success, otherwise ```false```882 */883 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {884 const result = await this.helper.executeExtrinsic(885 signer,886 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],887 true,888 );889890 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');891 }892893 /**894 * Sets onchain permissions for selected collection.895 *896 * @param signer keyring of signer897 * @param collectionId ID of collection898 * @param permissions collection permissions object899 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});900 * @returns ```true``` if extrinsic success, otherwise ```false```901 */902 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {903 const result = await this.helper.executeExtrinsic(904 signer,905 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],906 true,907 );908909 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');910 }911912 /**913 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.914 *915 * @param signer keyring of signer916 * @param collectionId ID of collection917 * @param permissions nesting permissions object918 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});919 * @returns ```true``` if extrinsic success, otherwise ```false```920 */921 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {922 return await this.setPermissions(signer, collectionId, {nesting: permissions});923 }924925 /**926 * Disables nesting for selected collection.927 *928 * @param signer keyring of signer929 * @param collectionId ID of collection930 * @example disableNesting(aliceKeyring, 10);931 * @returns ```true``` if extrinsic success, otherwise ```false```932 */933 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {934 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});935 }936937 /**938 * Sets onchain properties to the collection.939 *940 * @param signer keyring of signer941 * @param collectionId ID of collection942 * @param properties array of property objects943 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);944 * @returns ```true``` if extrinsic success, otherwise ```false```945 */946 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {947 const result = await this.helper.executeExtrinsic(948 signer,949 'api.tx.unique.setCollectionProperties', [collectionId, properties],950 true,951 );952953 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');954 }955956 /**957 * Get collection properties.958 * 959 * @param collectionId ID of collection960 * @param propertyKeys optionally filter the returned properties to only these keys961 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);962 * @returns array of key-value pairs963 */964 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {965 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();966 }967968 /**969 * Deletes onchain properties from the collection.970 *971 * @param signer keyring of signer972 * @param collectionId ID of collection973 * @param propertyKeys array of property keys to delete974 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);975 * @returns ```true``` if extrinsic success, otherwise ```false```976 */977 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {978 const result = await this.helper.executeExtrinsic(979 signer,980 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],981 true,982 );983984 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');985 }986987 /**988 * Changes the owner of the token.989 *990 * @param signer keyring of signer991 * @param collectionId ID of collection992 * @param tokenId ID of token993 * @param addressObj address of a new owner994 * @param amount amount of tokens to be transfered. For NFT must be set to 1n995 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})996 * @returns true if the token success, otherwise false997 */998 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {999 const result = await this.helper.executeExtrinsic(1000 signer,1001 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1002 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1003 );10041005 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1006 }10071008 /**1009 *1010 * Change ownership of a token(s) on behalf of the owner.1011 *1012 * @param signer keyring of signer1013 * @param collectionId ID of collection1014 * @param tokenId ID of token1015 * @param fromAddressObj address on behalf of which the token will be sent1016 * @param toAddressObj new token owner1017 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1018 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1019 * @returns true if the token success, otherwise false1020 */1021 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1025 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1026 );1027 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1028 }10291030 /**1031 *1032 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1033 *1034 * @param signer keyring of signer1035 * @param collectionId ID of collection1036 * @param tokenId ID of token1037 * @param amount amount of tokens to be burned. For NFT must be set to 1n1038 * @example burnToken(aliceKeyring, 10, 5);1039 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1040 */1041 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1042 const burnResult = await this.helper.executeExtrinsic(1043 signer,1044 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1045 true, // `Unable to burn token for ${label}`,1046 );1047 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1048 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1049 return burnedTokens.success;1050 }10511052 /**1053 * Destroys a concrete instance of NFT on behalf of the owner1054 *1055 * @param signer keyring of signer1056 * @param collectionId ID of collection1057 * @param tokenId ID of token1058 * @param fromAddressObj address on behalf of which the token will be burnt1059 * @param amount amount of tokens to be burned. For NFT must be set to 1n1060 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1061 * @returns ```true``` if extrinsic success, otherwise ```false```1062 */1063 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064 const burnResult = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1067 true, // `Unable to burn token from for ${label}`,1068 );1069 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1070 return burnedTokens.success && burnedTokens.tokens.length > 0;1071 }10721073 /**1074 * Set, change, or remove approved address to transfer the ownership of the NFT.1075 *1076 * @param signer keyring of signer1077 * @param collectionId ID of collection1078 * @param tokenId ID of token1079 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1080 * @param amount amount of token to be approved. For NFT must be set to 1n1081 * @returns ```true``` if extrinsic success, otherwise ```false```1082 */1083 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1084 const approveResult = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1087 true, // `Unable to approve token for ${label}`,1088 );10891090 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1091 }10921093 /**1094 * Get the amount of token pieces approved to transfer or burn. Normally 0.1095 *1096 * @param collectionId ID of collection1097 * @param tokenId ID of token1098 * @param toAccountObj address which is approved to use token pieces1099 * @param fromAccountObj address which may have allowed the use of its owned tokens1100 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1101 * @returns number of approved to transfer pieces1102 */1103 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1104 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1105 }11061107 /**1108 * Get the last created token ID in a collection1109 *1110 * @param collectionId ID of collection1111 * @example getLastTokenId(10);1112 * @returns id of the last created token1113 */1114 async getLastTokenId(collectionId: number): Promise<number> {1115 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1116 }11171118 /**1119 * Check if token exists1120 *1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @example doesTokenExist(10, 20);1124 * @returns true if the token exists, otherwise false1125 */1126 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1127 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1128 }1129}11301131class NFTnRFT extends CollectionGroup {1132 /**1133 * Get tokens owned by account1134 *1135 * @param collectionId ID of collection1136 * @param addressObj tokens owner1137 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1138 * @returns array of token ids owned by account1139 */1140 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1141 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1142 }11431144 /**1145 * Get token data1146 *1147 * @param collectionId ID of collection1148 * @param tokenId ID of token1149 * @param propertyKeys optionally filter the token properties to only these keys1150 * @param blockHashAt optionally query the data at some block with this hash1151 * @example getToken(10, 5);1152 * @returns human readable token data1153 */1154 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1155 properties: IProperty[];1156 owner: CrossAccountId;1157 normalizedOwner: CrossAccountId;1158 }| null> {1159 let tokenData;1160 if(typeof blockHashAt === 'undefined') {1161 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1162 }1163 else {1164 if(propertyKeys.length == 0) {1165 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1166 if(!collection) return null;1167 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1168 }1169 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1170 }1171 tokenData = tokenData.toHuman();1172 if (tokenData === null || tokenData.owner === null) return null;1173 const owner = {} as any;1174 for (const key of Object.keys(tokenData.owner)) {1175 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1176 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1177 : tokenData.owner[key];1178 }1179 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1180 return tokenData;1181 }11821183 /**1184 * Set permissions to change token properties1185 *1186 * @param signer keyring of signer1187 * @param collectionId ID of collection1188 * @param permissions permissions to change a property by the collection admin or token owner1189 * @example setTokenPropertyPermissions(1190 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1191 * )1192 * @returns true if extrinsic success otherwise false1193 */1194 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1195 const result = await this.helper.executeExtrinsic(1196 signer,1197 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1198 true,1199 );12001201 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1202 }12031204 /**1205 * Get token property permissions.1206 * 1207 * @param collectionId ID of collection1208 * @param propertyKeys optionally filter the returned property permissions to only these keys1209 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1210 * @returns array of key-permission pairs1211 */1212 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1213 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1214 }12151216 /**1217 * Set token properties1218 *1219 * @param signer keyring of signer1220 * @param collectionId ID of collection1221 * @param tokenId ID of token1222 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1223 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1224 * @returns ```true``` if extrinsic success, otherwise ```false```1225 */1226 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1227 const result = await this.helper.executeExtrinsic(1228 signer,1229 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1230 true,1231 );12321233 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1234 }12351236 /**1237 * Get properties, metadata assigned to a token.1238 * 1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @param propertyKeys optionally filter the returned properties to only these keys1242 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1243 * @returns array of key-value pairs1244 */1245 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1246 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1247 }12481249 /**1250 * Delete the provided properties of a token1251 * @param signer keyring of signer1252 * @param collectionId ID of collection1253 * @param tokenId ID of token1254 * @param propertyKeys property keys to be deleted1255 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1256 * @returns ```true``` if extrinsic success, otherwise ```false```1257 */1258 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1259 const result = await this.helper.executeExtrinsic(1260 signer,1261 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1262 true,1263 );12641265 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1266 }12671268 /**1269 * Mint new collection1270 *1271 * @param signer keyring of signer1272 * @param collectionOptions basic collection options and properties1273 * @param mode NFT or RFT type of a collection1274 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1275 * @returns object of the created collection1276 */1277 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1278 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1279 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1280 for (const key of ['name', 'description', 'tokenPrefix']) {1281 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);1282 }1283 const creationResult = await this.helper.executeExtrinsic(1284 signer,1285 'api.tx.unique.createCollectionEx', [collectionOptions],1286 true, // errorLabel,1287 );1288 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1289 }12901291 getCollectionObject(_collectionId: number): any {1292 return null;1293 }12941295 getTokenObject(_collectionId: number, _tokenId: number): any {1296 return null;1297 }1298}129913001301class NFTGroup extends NFTnRFT {1302 /**1303 * Get collection object1304 * @param collectionId ID of collection1305 * @example getCollectionObject(2);1306 * @returns instance of UniqueNFTCollection1307 */1308 getCollectionObject(collectionId: number): UniqueNFTCollection {1309 return new UniqueNFTCollection(collectionId, this.helper);1310 }13111312 /**1313 * Get token object1314 * @param collectionId ID of collection1315 * @param tokenId ID of token1316 * @example getTokenObject(10, 5);1317 * @returns instance of UniqueNFTToken1318 */1319 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1320 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1321 }13221323 /**1324 * Get token's owner1325 * @param collectionId ID of collection1326 * @param tokenId ID of token1327 * @param blockHashAt optionally query the data at the block with this hash1328 * @example getTokenOwner(10, 5);1329 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1330 */1331 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1332 let owner;1333 if (typeof blockHashAt === 'undefined') {1334 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1335 } else {1336 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1337 }1338 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1339 }13401341 /**1342 * Is token approved to transfer1343 * @param collectionId ID of collection1344 * @param tokenId ID of token1345 * @param toAccountObj address to be approved1346 * @returns ```true``` if extrinsic success, otherwise ```false```1347 */1348 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1349 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1350 }13511352 /**1353 * Changes the owner of the token.1354 *1355 * @param signer keyring of signer1356 * @param collectionId ID of collection1357 * @param tokenId ID of token1358 * @param addressObj address of a new owner1359 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1360 * @returns ```true``` if extrinsic success, otherwise ```false```1361 */1362 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1363 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1364 }13651366 /**1367 *1368 * Change ownership of a NFT on behalf of the owner.1369 *1370 * @param signer keyring of signer1371 * @param collectionId ID of collection1372 * @param tokenId ID of token1373 * @param fromAddressObj address on behalf of which the token will be sent1374 * @param toAddressObj new token owner1375 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1376 * @returns ```true``` if extrinsic success, otherwise ```false```1377 */1378 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1379 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1380 }13811382 /**1383 * Recursively find the address that owns the token1384 * @param collectionId ID of collection1385 * @param tokenId ID of token1386 * @param blockHashAt1387 * @example getTokenTopmostOwner(10, 5);1388 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1389 */1390 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1391 let owner;1392 if (typeof blockHashAt === 'undefined') {1393 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1394 } else {1395 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1396 }13971398 if (owner === null) return null;13991400 return owner.toHuman();1401 }14021403 /**1404 * Get tokens nested in the provided token1405 * @param collectionId ID of collection1406 * @param tokenId ID of token1407 * @param blockHashAt optionally query the data at the block with this hash1408 * @example getTokenChildren(10, 5);1409 * @returns tokens whose depth of nesting is <= 51410 */1411 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1412 let children;1413 if(typeof blockHashAt === 'undefined') {1414 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1415 } else {1416 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1417 }14181419 return children.toJSON().map((x: any) => {1420 return {collectionId: x.collection, tokenId: x.token};1421 });1422 }14231424 /**1425 * Nest one token into another1426 * @param signer keyring of signer1427 * @param tokenObj token to be nested1428 * @param rootTokenObj token to be parent1429 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1430 * @returns ```true``` if extrinsic success, otherwise ```false```1431 */1432 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1433 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1434 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1435 if(!result) {1436 throw Error('Unable to nest token!');1437 }1438 return result;1439 }14401441 /**1442 * Remove token from nested state1443 * @param signer keyring of signer1444 * @param tokenObj token to unnest1445 * @param rootTokenObj parent of a token1446 * @param toAddressObj address of a new token owner1447 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1448 * @returns ```true``` if extrinsic success, otherwise ```false```1449 */1450 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1451 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1452 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1453 if(!result) {1454 throw Error('Unable to unnest token!');1455 }1456 return result;1457 }14581459 /**1460 * Mint new collection1461 * @param signer keyring of signer1462 * @param collectionOptions Collection options1463 * @example1464 * mintCollection(aliceKeyring, {1465 * name: 'New',1466 * description: 'New collection',1467 * tokenPrefix: 'NEW',1468 * })1469 * @returns object of the created collection1470 */1471 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1472 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1473 }14741475 /**1476 * Mint new token1477 * @param signer keyring of signer1478 * @param data token data1479 * @returns created token object1480 */1481 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1482 const creationResult = await this.helper.executeExtrinsic(1483 signer,1484 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1485 nft: {1486 properties: data.properties,1487 },1488 }],1489 true,1490 );1491 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1492 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1493 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1494 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1495 }14961497 /**1498 * Mint multiple NFT tokens1499 * @param signer keyring of signer1500 * @param collectionId ID of collection1501 * @param tokens array of tokens with owner and properties1502 * @example1503 * mintMultipleTokens(aliceKeyring, 10, [{1504 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1505 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1506 * },{1507 * owner: {Ethereum: "0x9F0583DbB855d..."},1508 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1509 * }]);1510 * @returns ```true``` if extrinsic success, otherwise ```false```1511 */1512 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1513 const creationResult = await this.helper.executeExtrinsic(1514 signer,1515 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1516 true,1517 );1518 const collection = this.getCollectionObject(collectionId);1519 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1520 }15211522 /**1523 * Mint multiple NFT tokens with one owner1524 * @param signer keyring of signer1525 * @param collectionId ID of collection1526 * @param owner tokens owner1527 * @param tokens array of tokens with owner and properties1528 * @example1529 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1530 * properties: [{1531 * key: "gender",1532 * value: "female",1533 * },{1534 * key: "age",1535 * value: "33",1536 * }],1537 * }]);1538 * @returns array of newly created tokens1539 */1540 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1541 const rawTokens = [];1542 for (const token of tokens) {1543 const raw = {NFT: {properties: token.properties}};1544 rawTokens.push(raw);1545 }1546 const creationResult = await this.helper.executeExtrinsic(1547 signer,1548 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1549 true,1550 );1551 const collection = this.getCollectionObject(collectionId);1552 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1553 }15541555 /**1556 * Set, change, or remove approved address to transfer the ownership of the NFT.1557 *1558 * @param signer keyring of signer1559 * @param collectionId ID of collection1560 * @param tokenId ID of token1561 * @param toAddressObj address to approve1562 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1563 * @returns ```true``` if extrinsic success, otherwise ```false```1564 */1565 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1566 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1567 }1568}156915701571class RFTGroup extends NFTnRFT {1572 /**1573 * Get collection object1574 * @param collectionId ID of collection1575 * @example getCollectionObject(2);1576 * @returns instance of UniqueRFTCollection1577 */1578 getCollectionObject(collectionId: number): UniqueRFTCollection {1579 return new UniqueRFTCollection(collectionId, this.helper);1580 }15811582 /**1583 * Get token object1584 * @param collectionId ID of collection1585 * @param tokenId ID of token1586 * @example getTokenObject(10, 5);1587 * @returns instance of UniqueNFTToken1588 */1589 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1590 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1591 }15921593 /**1594 * Get top 10 token owners with the largest number of pieces1595 * @param collectionId ID of collection1596 * @param tokenId ID of token1597 * @example getTokenTop10Owners(10, 5);1598 * @returns array of top 10 owners1599 */1600 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1601 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1602 }16031604 /**1605 * Get number of pieces owned by address1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param addressObj address token owner1609 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1610 * @returns number of pieces ownerd by address1611 */1612 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1613 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1614 }16151616 /**1617 * Transfer pieces of token to another address1618 * @param signer keyring of signer1619 * @param collectionId ID of collection1620 * @param tokenId ID of token1621 * @param addressObj address of a new owner1622 * @param amount number of pieces to be transfered1623 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1624 * @returns ```true``` if extrinsic success, otherwise ```false```1625 */1626 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1627 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1628 }16291630 /**1631 * Change ownership of some pieces of RFT on behalf of the owner.1632 * @param signer keyring of signer1633 * @param collectionId ID of collection1634 * @param tokenId ID of token1635 * @param fromAddressObj address on behalf of which the token will be sent1636 * @param toAddressObj new token owner1637 * @param amount number of pieces to be transfered1638 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1639 * @returns ```true``` if extrinsic success, otherwise ```false```1640 */1641 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1642 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1643 }16441645 /**1646 * Mint new collection1647 * @param signer keyring of signer1648 * @param collectionOptions Collection options1649 * @example1650 * mintCollection(aliceKeyring, {1651 * name: 'New',1652 * description: 'New collection',1653 * tokenPrefix: 'NEW',1654 * })1655 * @returns object of the created collection1656 */1657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1658 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1659 }16601661 /**1662 * Mint new token1663 * @param signer keyring of signer1664 * @param data token data1665 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1666 * @returns created token object1667 */1668 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1669 const creationResult = await this.helper.executeExtrinsic(1670 signer,1671 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1672 refungible: {1673 pieces: data.pieces,1674 properties: data.properties,1675 },1676 }],1677 true,1678 );1679 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1680 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1681 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1682 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1683 }16841685 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1686 throw Error('Not implemented');1687 const creationResult = await this.helper.executeExtrinsic(1688 signer,1689 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1690 true, // `Unable to mint RFT tokens for ${label}`,1691 );1692 const collection = this.getCollectionObject(collectionId);1693 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1694 }16951696 /**1697 * Mint multiple RFT tokens with one owner1698 * @param signer keyring of signer1699 * @param collectionId ID of collection1700 * @param owner tokens owner1701 * @param tokens array of tokens with properties and pieces1702 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1703 * @returns array of newly created RFT tokens1704 */1705 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1706 const rawTokens = [];1707 for (const token of tokens) {1708 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1709 rawTokens.push(raw);1710 }1711 const creationResult = await this.helper.executeExtrinsic(1712 signer,1713 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1714 true,1715 );1716 const collection = this.getCollectionObject(collectionId);1717 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1718 }17191720 /**1721 * Destroys a concrete instance of RFT.1722 * @param signer keyring of signer1723 * @param collectionId ID of collection1724 * @param tokenId ID of token1725 * @param amount number of pieces to be burnt1726 * @example burnToken(aliceKeyring, 10, 5);1727 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1728 */1729 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1730 return await super.burnToken(signer, collectionId, tokenId, amount);1731 }17321733 /**1734 * Destroys a concrete instance of RFT on behalf of the owner.1735 * @param signer keyring of signer1736 * @param collectionId ID of collection1737 * @param tokenId ID of token1738 * @param fromAddressObj address on behalf of which the token will be burnt1739 * @param amount number of pieces to be burnt1740 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1741 * @returns ```true``` if extrinsic success, otherwise ```false```1742 */1743 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1744 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1745 }17461747 /**1748 * Set, change, or remove approved address to transfer the ownership of the RFT.1749 *1750 * @param signer keyring of signer1751 * @param collectionId ID of collection1752 * @param tokenId ID of token1753 * @param toAddressObj address to approve1754 * @param amount number of pieces to be approved1755 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1756 * @returns true if the token success, otherwise false1757 */1758 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1759 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1760 }17611762 /**1763 * Get total number of pieces1764 * @param collectionId ID of collection1765 * @param tokenId ID of token1766 * @example getTokenTotalPieces(10, 5);1767 * @returns number of pieces1768 */1769 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1770 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1771 }17721773 /**1774 * Change number of token pieces. Signer must be the owner of all token pieces.1775 * @param signer keyring of signer1776 * @param collectionId ID of collection1777 * @param tokenId ID of token1778 * @param amount new number of pieces1779 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1780 * @returns true if the repartion was success, otherwise false1781 */1782 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1783 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1784 const repartitionResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.repartition', [collectionId, tokenId, amount],1787 true,1788 );1789 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1790 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1791 }1792}179317941795class FTGroup extends CollectionGroup {1796 /**1797 * Get collection object1798 * @param collectionId ID of collection1799 * @example getCollectionObject(2);1800 * @returns instance of UniqueFTCollection1801 */1802 getCollectionObject(collectionId: number): UniqueFTCollection {1803 return new UniqueFTCollection(collectionId, this.helper);1804 }18051806 /**1807 * Mint new fungible collection1808 * @param signer keyring of signer1809 * @param collectionOptions Collection options1810 * @param decimalPoints number of token decimals1811 * @example1812 * mintCollection(aliceKeyring, {1813 * name: 'New',1814 * description: 'New collection',1815 * tokenPrefix: 'NEW',1816 * }, 18)1817 * @returns newly created fungible collection1818 */1819 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1820 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1821 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1822 collectionOptions.mode = {fungible: decimalPoints};1823 for (const key of ['name', 'description', 'tokenPrefix']) {1824 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);1825 }1826 const creationResult = await this.helper.executeExtrinsic(1827 signer,1828 'api.tx.unique.createCollectionEx', [collectionOptions],1829 true,1830 );1831 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1832 }18331834 /**1835 * Mint tokens1836 * @param signer keyring of signer1837 * @param collectionId ID of collection1838 * @param owner address owner of new tokens1839 * @param amount amount of tokens to be meanted1840 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1841 * @returns ```true``` if extrinsic success, otherwise ```false```1842 */1843 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1844 const creationResult = await this.helper.executeExtrinsic(1845 signer,1846 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1847 fungible: {1848 value: amount,1849 },1850 }],1851 true, // `Unable to mint fungible tokens for ${label}`,1852 );1853 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1854 }18551856 /**1857 * Mint multiple Fungible tokens with one owner1858 * @param signer keyring of signer1859 * @param collectionId ID of collection1860 * @param owner tokens owner1861 * @param tokens array of tokens with properties and pieces1862 * @returns ```true``` if extrinsic success, otherwise ```false```1863 */1864 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1865 const rawTokens = [];1866 for (const token of tokens) {1867 const raw = {Fungible: {Value: token.value}};1868 rawTokens.push(raw);1869 }1870 const creationResult = await this.helper.executeExtrinsic(1871 signer,1872 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1873 true,1874 );1875 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1876 }18771878 /**1879 * Get the top 10 owners with the largest balance for the Fungible collection1880 * @param collectionId ID of collection1881 * @example getTop10Owners(10);1882 * @returns array of ```ICrossAccountId```1883 */1884 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1885 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1886 }18871888 /**1889 * Get account balance1890 * @param collectionId ID of collection1891 * @param addressObj address of owner1892 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1893 * @returns amount of fungible tokens owned by address1894 */1895 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1896 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1897 }18981899 /**1900 * Transfer tokens to address1901 * @param signer keyring of signer1902 * @param collectionId ID of collection1903 * @param toAddressObj address recipient1904 * @param amount amount of tokens to be sent1905 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1906 * @returns ```true``` if extrinsic success, otherwise ```false```1907 */1908 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1909 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1910 }19111912 /**1913 * Transfer some tokens on behalf of the owner.1914 * @param signer keyring of signer1915 * @param collectionId ID of collection1916 * @param fromAddressObj address on behalf of which tokens will be sent1917 * @param toAddressObj address where token to be sent1918 * @param amount number of tokens to be sent1919 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1920 * @returns ```true``` if extrinsic success, otherwise ```false```1921 */1922 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1923 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1924 }19251926 /**1927 * Destroy some amount of tokens1928 * @param signer keyring of signer1929 * @param collectionId ID of collection1930 * @param amount amount of tokens to be destroyed1931 * @example burnTokens(aliceKeyring, 10, 1000n);1932 * @returns ```true``` if extrinsic success, otherwise ```false```1933 */1934 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1935 return await super.burnToken(signer, collectionId, 0, amount);1936 }19371938 /**1939 * Burn some tokens on behalf of the owner.1940 * @param signer keyring of signer1941 * @param collectionId ID of collection1942 * @param fromAddressObj address on behalf of which tokens will be burnt1943 * @param amount amount of tokens to be burnt1944 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1945 * @returns ```true``` if extrinsic success, otherwise ```false```1946 */1947 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1948 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1949 }19501951 /**1952 * Get total collection supply1953 * @param collectionId1954 * @returns1955 */1956 async getTotalPieces(collectionId: number): Promise<bigint> {1957 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1958 }19591960 /**1961 * Set, change, or remove approved address to transfer tokens.1962 *1963 * @param signer keyring of signer1964 * @param collectionId ID of collection1965 * @param toAddressObj address to be approved1966 * @param amount amount of tokens to be approved1967 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1968 * @returns ```true``` if extrinsic success, otherwise ```false```1969 */1970 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1971 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1972 }19731974 /**1975 * Get amount of fungible tokens approved to transfer1976 * @param collectionId ID of collection1977 * @param fromAddressObj owner of tokens1978 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1979 * @returns number of tokens approved for the transfer1980 */1981 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1982 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1983 }1984}198519861987class ChainGroup extends HelperGroup {1988 /**1989 * Get system properties of a chain1990 * @example getChainProperties();1991 * @returns ss58Format, token decimals, and token symbol1992 */1993 getChainProperties(): IChainProperties {1994 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();1995 return {1996 ss58Format: properties.ss58Format.toJSON(),1997 tokenDecimals: properties.tokenDecimals.toJSON(),1998 tokenSymbol: properties.tokenSymbol.toJSON(),1999 };2000 }20012002 /**2003 * Get chain header2004 * @example getLatestBlockNumber();2005 * @returns the number of the last block2006 */2007 async getLatestBlockNumber(): Promise<number> {2008 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2009 }20102011 /**2012 * Get block hash by block number2013 * @param blockNumber number of block2014 * @example getBlockHashByNumber(12345);2015 * @returns hash of a block2016 */2017 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2018 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2019 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2020 return blockHash;2021 }20222023 // TODO add docs2024 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2025 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2026 if (!blockHash) return null;2027 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2028 }20292030 /**2031 * Get account nonce2032 * @param address substrate address2033 * @example getNonce("5GrwvaEF5zXb26Fz...");2034 * @returns number, account's nonce2035 */2036 async getNonce(address: TSubstrateAccount): Promise<number> {2037 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2038 }2039}204020412042class BalanceGroup extends HelperGroup {2043 getCollectionCreationPrice(): bigint {2044 return 2n * this.helper.balance.getOneTokenNominal();2045 }2046 /**2047 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2048 * @example getOneTokenNominal()2049 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2050 */2051 getOneTokenNominal(): bigint {2052 const chainProperties = this.helper.chain.getChainProperties();2053 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2054 }20552056 /**2057 * Get substrate address balance2058 * @param address substrate address2059 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2060 * @returns amount of tokens on address2061 */2062 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2063 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2064 }20652066 /**2067 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2068 * @param address substrate address2069 * @returns2070 */2071 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2072 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2073 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2074 }20752076 /**2077 * Get ethereum address balance2078 * @param address ethereum address2079 * @example getEthereum("0x9F0583DbB855d...")2080 * @returns amount of tokens on address2081 */2082 async getEthereum(address: TEthereumAccount): Promise<bigint> {2083 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2084 }20852086 /**2087 * Transfer tokens to substrate address2088 * @param signer keyring of signer2089 * @param address substrate address of a recipient2090 * @param amount amount of tokens to be transfered2091 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2092 * @returns ```true``` if extrinsic success, otherwise ```false```2093 */2094 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2095 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}`*/);20962097 let transfer = {from: null, to: null, amount: 0n} as any;2098 result.result.events.forEach(({event: {data, method, section}}) => {2099 if ((section === 'balances') && (method === 'Transfer')) {2100 transfer = {2101 from: this.helper.address.normalizeSubstrate(data[0]),2102 to: this.helper.address.normalizeSubstrate(data[1]),2103 amount: BigInt(data[2]),2104 };2105 }2106 });2107 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2108 && this.helper.address.normalizeSubstrate(address) === transfer.to 2109 && BigInt(amount) === transfer.amount;2110 return isSuccess;2111 }2112}211321142115class AddressGroup extends HelperGroup {2116 /**2117 * Normalizes the address to the specified ss58 format, by default ```42```.2118 * @param address substrate address2119 * @param ss58Format format for address conversion, by default ```42```2120 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2121 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2122 */2123 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2124 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2125 }21262127 /**2128 * Get address in the connected chain format2129 * @param address substrate address2130 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2131 * @returns address in chain format2132 */2133 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2134 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2135 }21362137 /**2138 * Get substrate mirror of an ethereum address2139 * @param ethAddress ethereum address2140 * @param toChainFormat false for normalized account2141 * @example ethToSubstrate('0x9F0583DbB855d...')2142 * @returns substrate mirror of a provided ethereum address2143 */2144 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2145 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2146 }21472148 /**2149 * Get ethereum mirror of a substrate address2150 * @param subAddress substrate account2151 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2152 * @returns ethereum mirror of a provided substrate address2153 */2154 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2155 return CrossAccountId.translateSubToEth(subAddress);2156 }2157}21582159class StakingGroup extends HelperGroup {2160 /**2161 * Stake tokens for App Promotion2162 * @param signer keyring of signer2163 * @param amountToStake amount of tokens to stake2164 * @param label extra label for log2165 * @returns2166 */2167 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2168 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2169 const _stakeResult = await this.helper.executeExtrinsic(2170 signer, 'api.tx.appPromotion.stake',2171 [amountToStake], true,2172 );2173 // TODO extract info from stakeResult2174 return true;2175 }21762177 /**2178 * Unstake tokens for App Promotion2179 * @param signer keyring of signer2180 * @param amountToUnstake amount of tokens to unstake2181 * @param label extra label for log2182 * @returns block number where balances will be unlocked2183 */2184 async unstake(signer: TSigner, label?: string): Promise<number> {2185 if(typeof label === 'undefined') label = `${signer.address}`;2186 const _unstakeResult = await this.helper.executeExtrinsic(2187 signer, 'api.tx.appPromotion.unstake',2188 [], true,2189 );2190 // TODO extract block number fron events2191 return 1;2192 }21932194 /**2195 * Get total staked amount for address2196 * @param address substrate or ethereum address2197 * @returns total staked amount2198 */2199 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2200 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2201 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2202 }22032204 /**2205 * Get total staked per block2206 * @param address substrate or ethereum address2207 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2208 */2209 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2210 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2211 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2212 return { 2213 block: block.toBigInt(),2214 amount: amount.toBigInt(),2215 };2216 });2217 }22182219 /**2220 * Get total pending unstake amount for address2221 * @param address substrate or ethereum address2222 * @returns total pending unstake amount2223 */2224 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2225 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2226 }22272228 /**2229 * Get pending unstake amount per block for address2230 * @param address substrate or ethereum address2231 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2232 */2233 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2234 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2235 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2236 return {2237 block: block.toBigInt(),2238 amount: amount.toBigInt(),2239 };2240 });2241 return result;2242 }2243}22442245export class UniqueHelper extends ChainHelperBase {2246 chain: ChainGroup;2247 balance: BalanceGroup;2248 address: AddressGroup;2249 collection: CollectionGroup;2250 nft: NFTGroup;2251 rft: RFTGroup;2252 ft: FTGroup;2253 staking: StakingGroup;22542255 constructor(logger?: ILogger) {2256 super(logger);2257 this.chain = new ChainGroup(this);2258 this.balance = new BalanceGroup(this);2259 this.address = new AddressGroup(this);2260 this.collection = new CollectionGroup(this);2261 this.nft = new NFTGroup(this);2262 this.rft = new RFTGroup(this);2263 this.ft = new FTGroup(this);2264 this.staking = new StakingGroup(this);2265 }2266}226722682269export class UniqueBaseCollection {2270 helper: UniqueHelper;2271 collectionId: number;22722273 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2274 this.collectionId = collectionId;2275 this.helper = uniqueHelper;2276 }22772278 async getData() {2279 return await this.helper.collection.getData(this.collectionId);2280 }22812282 async getLastTokenId() {2283 return await this.helper.collection.getLastTokenId(this.collectionId);2284 }22852286 async doesTokenExist(tokenId: number) {2287 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2288 }22892290 async getAdmins() {2291 return await this.helper.collection.getAdmins(this.collectionId);2292 }22932294 async getAllowList() {2295 return await this.helper.collection.getAllowList(this.collectionId);2296 }22972298 async getEffectiveLimits() {2299 return await this.helper.collection.getEffectiveLimits(this.collectionId);2300 }23012302 async getProperties(propertyKeys?: string[] | null) {2303 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2304 }23052306 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2307 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2308 }23092310 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2311 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2312 }23132314 async confirmSponsorship(signer: TSigner) {2315 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2316 }23172318 async removeSponsor(signer: TSigner) {2319 return await this.helper.collection.removeSponsor(signer, this.collectionId);2320 }23212322 async setLimits(signer: TSigner, limits: ICollectionLimits) {2323 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2324 }23252326 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2327 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2328 }23292330 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2331 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2332 }23332334 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2335 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2336 }23372338 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2339 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2340 }23412342 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2343 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2344 }23452346 async setProperties(signer: TSigner, properties: IProperty[]) {2347 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2348 }23492350 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2351 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2352 }23532354 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2355 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2356 }23572358 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2359 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2360 }23612362 async disableNesting(signer: TSigner) {2363 return await this.helper.collection.disableNesting(signer, this.collectionId);2364 }23652366 async burn(signer: TSigner) {2367 return await this.helper.collection.burn(signer, this.collectionId);2368 }2369}237023712372export class UniqueNFTCollection extends UniqueBaseCollection {2373 getTokenObject(tokenId: number) {2374 return new UniqueNFToken(tokenId, this);2375 }23762377 async getTokensByAddress(addressObj: ICrossAccountId) {2378 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2379 }23802381 async getToken(tokenId: number, blockHashAt?: string) {2382 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2383 }23842385 async getTokenOwner(tokenId: number, blockHashAt?: string) {2386 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2387 }23882389 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2390 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2391 }23922393 async getTokenChildren(tokenId: number, blockHashAt?: string) {2394 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2395 }23962397 async getPropertyPermissions(propertyKeys: string[] | null = null) {2398 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2399 }24002401 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2402 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2403 }24042405 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2406 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2407 }24082409 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2410 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2411 }24122413 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2414 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2415 }24162417 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2418 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2419 }24202421 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2422 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2423 }24242425 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2426 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2427 }24282429 async burnToken(signer: TSigner, tokenId: number) {2430 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2431 }24322433 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2434 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2435 }24362437 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2438 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2439 }24402441 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2442 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2443 }24442445 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2446 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2447 }24482449 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2450 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2451 }24522453 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2454 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2455 }2456}245724582459export class UniqueRFTCollection extends UniqueBaseCollection {2460 getTokenObject(tokenId: number) {2461 return new UniqueRFToken(tokenId, this);2462 }24632464 async getToken(tokenId: number, blockHashAt?: string) {2465 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2466 }24672468 async getTokensByAddress(addressObj: ICrossAccountId) {2469 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2470 }24712472 async getTop10TokenOwners(tokenId: number) {2473 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2474 }24752476 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2477 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2478 }24792480 async getTokenTotalPieces(tokenId: number) {2481 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2482 }24832484 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2485 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2486 }24872488 async getPropertyPermissions(propertyKeys: string[] | null = null) {2489 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2490 }24912492 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2493 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2494 }24952496 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2497 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2498 }24992500 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2501 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2502 }25032504 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2505 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2506 }25072508 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2509 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2510 }25112512 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2513 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2514 }25152516 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2517 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2518 }25192520 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2521 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2522 }25232524 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2525 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2526 }25272528 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2529 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2530 }25312532 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2533 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2534 }25352536 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2537 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2538 }2539}254025412542export class UniqueFTCollection extends UniqueBaseCollection {2543 async getBalance(addressObj: ICrossAccountId) {2544 return await this.helper.ft.getBalance(this.collectionId, addressObj);2545 }25462547 async getTotalPieces() {2548 return await this.helper.ft.getTotalPieces(this.collectionId);2549 }25502551 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2552 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2553 }25542555 async getTop10Owners() {2556 return await this.helper.ft.getTop10Owners(this.collectionId);2557 }25582559 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2560 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2561 }25622563 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2564 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2565 }25662567 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2568 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2569 }25702571 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2572 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2573 }25742575 async burnTokens(signer: TSigner, amount=1n) {2576 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2577 }25782579 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2580 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2581 }25822583 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2584 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2585 }2586}258725882589export class UniqueBaseToken {2590 collection: UniqueNFTCollection | UniqueRFTCollection;2591 collectionId: number;2592 tokenId: number;25932594 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2595 this.collection = collection;2596 this.collectionId = collection.collectionId;2597 this.tokenId = tokenId;2598 }25992600 async getNextSponsored(addressObj: ICrossAccountId) {2601 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2602 }26032604 async getProperties(propertyKeys?: string[] | null) {2605 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2606 }26072608 async setProperties(signer: TSigner, properties: IProperty[]) {2609 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2610 }26112612 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2613 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2614 }26152616 async doesExist() {2617 return await this.collection.doesTokenExist(this.tokenId);2618 }26192620 nestingAccount() {2621 return this.collection.helper.util.getTokenAccount(this);2622 }2623}262426252626export class UniqueNFToken extends UniqueBaseToken {2627 collection: UniqueNFTCollection;26282629 constructor(tokenId: number, collection: UniqueNFTCollection) {2630 super(tokenId, collection);2631 this.collection = collection;2632 }26332634 async getData(blockHashAt?: string) {2635 return await this.collection.getToken(this.tokenId, blockHashAt);2636 }26372638 async getOwner(blockHashAt?: string) {2639 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2640 }26412642 async getTopmostOwner(blockHashAt?: string) {2643 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2644 }26452646 async getChildren(blockHashAt?: string) {2647 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2648 }26492650 async nest(signer: TSigner, toTokenObj: IToken) {2651 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2652 }26532654 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2655 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2656 }26572658 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2659 return await this.collection.transferToken(signer, this.tokenId, addressObj);2660 }26612662 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2663 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2664 }26652666 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2667 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2668 }26692670 async isApproved(toAddressObj: ICrossAccountId) {2671 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2672 }26732674 async burn(signer: TSigner) {2675 return await this.collection.burnToken(signer, this.tokenId);2676 }26772678 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2679 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2680 }2681}26822683export class UniqueRFToken extends UniqueBaseToken {2684 collection: UniqueRFTCollection;26852686 constructor(tokenId: number, collection: UniqueRFTCollection) {2687 super(tokenId, collection);2688 this.collection = collection;2689 }26902691 async getData(blockHashAt?: string) {2692 return await this.collection.getToken(this.tokenId, blockHashAt);2693 }26942695 async getTop10Owners() {2696 return await this.collection.getTop10TokenOwners(this.tokenId);2697 }26982699 async getBalance(addressObj: ICrossAccountId) {2700 return await this.collection.getTokenBalance(this.tokenId, addressObj);2701 }27022703 async getTotalPieces() {2704 return await this.collection.getTokenTotalPieces(this.tokenId);2705 }27062707 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2708 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2709 }27102711 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2712 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2713 }27142715 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2716 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2717 }27182719 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2720 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2721 }27222723 async repartition(signer: TSigner, amount: bigint) {2724 return await this.collection.repartitionToken(signer, this.tokenId, amount);2725 }27262727 async burn(signer: TSigner, amount=1n) {2728 return await this.collection.burnToken(signer, this.tokenId, amount);2729 }27302731 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2732 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2733 }2734}tests/src/util/util.tsdiffbeforeafterboth--- a/tests/src/util/util.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-export function strToUTF16(str: string): any {
- const buf: number[] = [];
- for (let i=0, strLen=str.length; i < strLen; i++) {
- buf.push(str.charCodeAt(i));
- }
- return buf;
-}
-
-export function utf16ToStr(buf: number[]): string {
- let str = '';
- for (let i=0, strLen=buf.length; i < strLen; i++) {
- if (buf[i] != 0) str += String.fromCharCode(buf[i]);
- else break;
- }
- return str;
-}
-
-export function hexToStr(buf: string): string {
- let str = '';
- let hexStart = buf.indexOf('0x');
- if (hexStart < 0) hexStart = 0;
- else hexStart = 2;
- for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
- const ch = buf[i] + buf[i+1];
- const num = parseInt(ch, 16);
- if (num != 0) str += String.fromCharCode(num);
- else break;
- }
- return str;
-}
tests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -21,9 +21,8 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {executeTransaction} from './../substrate/substrate-api';
-import {bigIntToDecimals, describe_xcm, getGenericResult, paraSiblingSovereignAccount} from './../util/helpers';
+import {bigIntToDecimals, describe_xcm, getGenericResult, paraSiblingSovereignAccount, normalizeAccountId} from './../deprecated-helpers/helpers';
import waitNewBlocks from './../substrate/wait-new-blocks';
-import {normalizeAccountId} from './../util/helpers';
import getBalance from './../substrate/get-balance';
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../deprecated-helpers/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../deprecated-helpers/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';