difftreelog
ES lint issues fixed
in: master
58 files changed
tests/src/addToContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import {10import {11 deployFlipper11 deployFlipper,12} from "./util/contracthelpers";12} from './util/contracthelpers';13import {13import {14 getGenericResult, normalizeAccountId14 getGenericResult,15} from "./util/helpers"15} from './util/helpers';161617chai.use(chaiAsPromised);17chai.use(chaiAsPromised);18const expect = chai.expect;18const expect = chai.expect;191920describe('Integration Test addToContractWhiteList', () => {20describe('Integration Test addToContractWhiteList', () => {212122 it(`Add an address to a contract white list`, async () => {22 it('Add an address to a contract white list', async () => {23 await usingApi(async api => {23 await usingApi(async api => {24 const bob = privateKey("//Bob");24 const bob = privateKey('//Bob');25 const [contract, deployer] = await deployFlipper(api);25 const [contract, deployer] = await deployFlipper(api);262627 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();27 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();35 });35 });36 });36 });373738 it(`Adding same address to white list repeatedly should not produce errors`, async () => {38 it('Adding same address to white list repeatedly should not produce errors', async () => {39 await usingApi(async api => {39 await usingApi(async api => {40 const bob = privateKey("//Bob");40 const bob = privateKey('//Bob');41 const [contract, deployer] = await deployFlipper(api);41 const [contract, deployer] = await deployFlipper(api);424243 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();43 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();585859describe('Negative Integration Test addToContractWhiteList', () => {59describe('Negative Integration Test addToContractWhiteList', () => {606061 it(`Add an address to a white list of a non-contract`, async () => {61 it('Add an address to a white list of a non-contract', async () => {62 await usingApi(async api => {62 await usingApi(async api => {63 const alice = privateKey("//Bob");63 const alice = privateKey('//Bob');64 const bob = privateKey("//Bob");64 const bob = privateKey('//Bob');65 const charlieGuineaPig = privateKey("//Charlie");65 const charlieGuineaPig = privateKey('//Charlie');666667 const whiteListedBefore = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();67 const whiteListedBefore = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();68 const addTx = api.tx.nft.addToContractWhiteList(charlieGuineaPig.address, bob.address);68 const addTx = api.tx.nft.addToContractWhiteList(charlieGuineaPig.address, bob.address);74 });74 });75 });75 });767677 it(`Add to a contract white list using a non-owner address`, async () => {77 it('Add to a contract white list using a non-owner address', async () => {78 await usingApi(async api => {78 await usingApi(async api => {79 const bob = privateKey("//Bob");79 const bob = privateKey('//Bob');80 const [contract, deployer] = await deployFlipper(api);80 const [contract] = await deployFlipper(api);818182 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();82 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();83 const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);83 const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);tests/src/addToWhiteList.test.tsdiffbeforeafterboth27describe('Integration Test ext. addToWhiteList()', () => {
27describe('Integration Test ext. addToWhiteList()', () => {28
2829 before(async () => {
29 before(async () => {30 await usingApi(async (api) => {
30 await usingApi(async () => {31 Alice = privateKey('//Alice');
31 Alice = privateKey('//Alice');32 Bob = privateKey('//Bob');
32 Bob = privateKey('//Bob');33 });
33 });tests/src/approve.test.tsdiffbeforeafterboth82 let Charlie: IKeyringPair;82 let Charlie: IKeyringPair;838384 before(async () => {84 before(async () => {85 await usingApi(async (api) => {85 await usingApi(async () => {86 Alice = privateKey('//Alice');86 Alice = privateKey('//Alice');87 Bob = privateKey('//Bob');87 Bob = privateKey('//Bob');88 Charlie = privateKey('//Charlie');88 Charlie = privateKey('//Charlie');tests/src/block-production.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import usingApi from "./substrate/substrate-api";6import usingApi from './substrate/substrate-api';7import { expect } from "chai";7import { expect } from 'chai';8import { ApiPromise } from "@polkadot/api";8import { ApiPromise } from '@polkadot/api';9910const BlockTimeMs = 12000;10const BlockTimeMs = 12000;11const ToleranceMs = 1000;11const ToleranceMs = 1000;121213/* eslint no-async-promise-executor: "off" */13async function getBlocks(api: ApiPromise): Promise<number[]> {14function getBlocks(api: ApiPromise): Promise<number[]> {14 return new Promise<number[]>(async (resolve, reject) => {15 return new Promise<number[]>(async (resolve, reject) => {15 const blockNumbers: number[] = [];16 const blockNumbers: number[] = [];16 setTimeout(() => reject('Block production test failed due to timeout.'), BlockTimeMs + ToleranceMs);17 setTimeout(() => reject('Block production test failed due to timeout.'), BlockTimeMs + ToleranceMs);27describe('Block Production smoke test', () => {28describe('Block Production smoke test', () => {28 it('Node produces new blocks', async () => {29 it('Node produces new blocks', async () => {29 await usingApi(async (api) => {30 await usingApi(async (api) => {30 let blocks: number[] | undefined = await getBlocks(api);31 const blocks: number[] | undefined = await getBlocks(api);31 expect(blocks[0]).to.be.lessThan(blocks[1]);32 expect(blocks[0]).to.be.lessThan(blocks[1]);32 });33 });33 });34 });tests/src/burnItem.test.tsdiffbeforeafterboth4//4//556import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';6import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";7import { Keyring } from '@polkadot/api';8import { IKeyringPair } from "@polkadot/types/types";8import { IKeyringPair } from '@polkadot/types/types';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 createItemExpectSuccess,11 createItemExpectSuccess,12 getGenericResult,12 getGenericResult,13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,14 normalizeAccountId14 normalizeAccountId,15} from './util/helpers';15} from './util/helpers';16import { nullPublicKey } from "./accounts";171618import chai from 'chai';17import chai from 'chai';19import chaiAsPromised from 'chai-as-promised';18import chaiAsPromised from 'chai-as-promised';252426describe('integration test: ext. burnItem():', () => {25describe('integration test: ext. burnItem():', () => {27 before(async () => {26 before(async () => {28 await usingApi(async (api) => {27 await usingApi(async () => {29 const keyring = new Keyring({ type: 'sr25519' });28 const keyring = new Keyring({ type: 'sr25519' });30 alice = keyring.addFromUri(`//Alice`);29 alice = keyring.addFromUri('//Alice');31 bob = keyring.addFromUri(`//Bob`);30 bob = keyring.addFromUri('//Bob');32 });31 });33 });32 });3433139138140describe('Negative integration test: ext. burnItem():', () => {139describe('Negative integration test: ext. burnItem():', () => {141 before(async () => {140 before(async () => {142 await usingApi(async (api) => {141 await usingApi(async () => {143 const keyring = new Keyring({ type: 'sr25519' });142 const keyring = new Keyring({ type: 'sr25519' });144 alice = keyring.addFromUri(`//Alice`);143 alice = keyring.addFromUri('//Alice');145 bob = keyring.addFromUri(`//Bob`);144 bob = keyring.addFromUri('//Bob');146 });145 });147 });146 });148147tests/src/change-collection-owner.test.tsdiffbeforeafterboth6import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import privateKey from './substrate/privateKey';8import privateKey from './substrate/privateKey';9import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";9import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';10import { createCollectionExpectSuccess, createCollectionExpectFailure, normalizeAccountId } from "./util/helpers";10import { createCollectionExpectSuccess, normalizeAccountId } from './util/helpers';111112chai.use(chaiAsPromised);12chai.use(chaiAsPromised);13const expect = chai.expect;13const expect = chai.expect;32});32});333334describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {34describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {35 it(`Not owner can't change owner.`, async () => {35 it('Not owner can\'t change owner.', async () => {36 await usingApi(async api => {36 await usingApi(async api => {37 const collectionId = await createCollectionExpectSuccess();37 const collectionId = await createCollectionExpectSuccess();38 const alice = privateKey('//Alice');38 const alice = privateKey('//Alice');48 await createCollectionExpectSuccess();48 await createCollectionExpectSuccess();49 });49 });50 });50 });51 it(`Can't change owner of not existing collection.`, async () => {51 it('Can\'t change owner of not existing collection.', async () => {52 await usingApi(async api => {52 await usingApi(async api => {53 const collectionId = (1<<32) - 1;53 const collectionId = (1<<32) - 1;54 const alice = privateKey('//Alice');54 const alice = privateKey('//Alice');tests/src/check-event/createItemEvent.test.tsdiffbeforeafterboth10import chaiAsPromised from 'chai-as-promised';10import chaiAsPromised from 'chai-as-promised';11import privateKey from '../substrate/privateKey';11import privateKey from '../substrate/privateKey';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';13import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';13import { createCollectionExpectSuccess, nftEventMessage } from '../util/helpers';141415chai.use(chaiAsPromised);15chai.use(chaiAsPromised);16const expect = chai.expect;16const expect = chai.expect;tests/src/check-event/createMultipleItemsEvent.test.tsdiffbeforeafterboth10import chaiAsPromised from 'chai-as-promised';10import chaiAsPromised from 'chai-as-promised';11import privateKey from '../substrate/privateKey';11import privateKey from '../substrate/privateKey';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';13import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';13import { createCollectionExpectSuccess, nftEventMessage } from '../util/helpers';141415chai.use(chaiAsPromised);15chai.use(chaiAsPromised);16const expect = chai.expect;16const expect = chai.expect;tests/src/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);tests/src/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);16const expect = chai.expect;
12const expect = chai.expect;17let Alice: IKeyringPair;
13let Alice: IKeyringPair;18let Bob: IKeyringPair;
14let Bob: IKeyringPair;19let Ferdie: IKeyringPair;
1520
21before(async () => {
16before(async () => {22 await usingApi(async () => {
17 await usingApi(async () => {23 Alice = privateKey('//Alice');
18 Alice = privateKey('//Alice');24 Bob = privateKey('//Bob');
19 Bob = privateKey('//Bob');25 Ferdie = privateKey('//Ferdie');
26 });
20 });27});
21});28
22tests/src/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);44 burnItem.signAndSend(Alice),
39 burnItem.signAndSend(Alice),45 ]);
40 ]);46 await timeoutPromise(10000);
41 await timeoutPromise(10000);47 let itemBurn: boolean = false;
42 let itemBurn = false;48 itemBurn = (await (api.query.nft.nftItemList(collectionId, itemId))).toJSON() as boolean;
43 itemBurn = (await (api.query.nft.nftItemList(collectionId, itemId))).toJSON() as boolean;49 // tslint:disable-next-line: no-unused-expression
44 // tslint:disable-next-line: no-unused-expression50 expect(itemBurn).to.be.null;
45 expect(itemBurn).to.be.null;tests/src/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';1import { IKeyringPair } from '@polkadot/types/types';2import BN from 'bn.js';3import chai from 'chai';2import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';3import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';4import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';7import {6import {8 createCollectionExpectSuccess,7 createCollectionExpectSuccess,9} from '../util/helpers';8} from '../util/helpers';10911chai.use(chaiAsPromised);10chai.use(chaiAsPromised);12const expect = chai.expect;11const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;12let Alice: IKeyringPair;19let Bob: IKeyringPair;13let Bob: IKeyringPair;20let Ferdie: IKeyringPair;14let Ferdie: IKeyringPair;21let Charlie: IKeyringPair;22let Eve: IKeyringPair;23let Dave: IKeyringPair;241525before(async () => {16before(async () => {26 await usingApi(async () => {17 await usingApi(async () => {27 Alice = privateKey('//Alice');18 Alice = privateKey('//Alice');28 Bob = privateKey('//Bob');19 Bob = privateKey('//Bob');29 Ferdie = privateKey('//Ferdie');20 Ferdie = privateKey('//Ferdie');30 Charlie = privateKey('//Charlie');31 Eve = privateKey('//Eve');32 Dave = privateKey('//Dave');33 });21 });34});22});352351 destroyCollection.signAndSend(Alice),38 destroyCollection.signAndSend(Alice),52 ]);39 ]);53 await timeoutPromise(10000);40 await timeoutPromise(10000);54 let whiteList: boolean = false;41 let whiteList = false;55 whiteList = (await api.query.nft.whiteList(collectionId, Ferdie.address)).toJSON() as boolean;42 whiteList = (await api.query.nft.whiteList(collectionId, Ferdie.address)).toJSON() as boolean;56 // tslint:disable-next-line: no-unused-expression43 // tslint:disable-next-line: no-unused-expression57 expect(whiteList).to.be.false;44 expect(whiteList).to.be.false;tests/src/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth101011chai.use(chaiAsPromised);11chai.use(chaiAsPromised);12const expect = chai.expect;12const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;13let Alice: IKeyringPair;19let Bob: IKeyringPair;14let Bob: IKeyringPair;20let Ferdie: IKeyringPair;15let Ferdie: IKeyringPair;51 await submitTransactionAsync(Alice, changeAdminTx3);46 await submitTransactionAsync(Alice, changeAdminTx3);524753 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));48 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));54 //55 const addAdmOne = api.tx.nft.addCollectionAdmin(collectionId, Ferdie.address);49 const addAdmOne = api.tx.nft.addCollectionAdmin(collectionId, Ferdie.address);56 const addAdmTwo = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);50 const addAdmTwo = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);57 await Promise.all51 await Promise.all([tests/src/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth3import chai from 'chai';3import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';4import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';5import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';6import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';7import {7import {8 createCollectionExpectSuccess,8 createCollectionExpectSuccess,9} from '../util/helpers';9} from '../util/helpers';101011chai.use(chaiAsPromised);11chai.use(chaiAsPromised);12const expect = chai.expect;12const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;13let Alice: IKeyringPair;19let Bob: IKeyringPair;14let Bob: IKeyringPair;20let Ferdie: IKeyringPair;21let Charlie: IKeyringPair;22let Eve: IKeyringPair;23let Dave: IKeyringPair;241525before(async () => {16before(async () => {26 await usingApi(async () => {17 await usingApi(async () => {27 Alice = privateKey('//Alice');18 Alice = privateKey('//Alice');28 Bob = privateKey('//Bob');19 Bob = privateKey('//Bob');29 Ferdie = privateKey('//Ferdie');30 Charlie = privateKey('//Charlie');31 Eve = privateKey('//Eve');32 Dave = privateKey('//Dave');33 });20 });34});21});352242 await submitTransactionAsync(Alice, changeAdminTx);29 await submitTransactionAsync(Alice, changeAdminTx);43 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));30 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));44 await timeoutPromise(10000);31 await timeoutPromise(10000);45 //46 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];32 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];47 const addItemAdm = api.tx.nft.createMultipleItems(collectionId, Bob.address, args);33 const addItemAdm = api.tx.nft.createMultipleItems(collectionId, Bob.address, args);48 const removeAdm = api.tx.nft.removeCollectionAdmin(collectionId, Bob.address);34 const removeAdm = api.tx.nft.removeCollectionAdmin(collectionId, Bob.address);tests/src/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';1import { IKeyringPair } from '@polkadot/types/types';2import BN from 'bn.js';3import chai from 'chai';2import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';3import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';4import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';5import usingApi from '../substrate/substrate-api';7import {6import {8 createCollectionExpectSuccess, createItemExpectSuccess, setCollectionSponsorExpectSuccess,7 createCollectionExpectSuccess, setCollectionSponsorExpectSuccess,9} from '../util/helpers';8} from '../util/helpers';10911chai.use(chaiAsPromised);10chai.use(chaiAsPromised);12const expect = chai.expect;11const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;12let Alice: IKeyringPair;19let Bob: IKeyringPair;13let Bob: IKeyringPair;20let Ferdie: IKeyringPair;14let Ferdie: IKeyringPair;35 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);29 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);36 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));30 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));37 await timeoutPromise(10000);31 await timeoutPromise(10000);38 //39 const confirmSponsorship = api.tx.nft.confirmSponsorship(collectionId);32 const confirmSponsorship = api.tx.nft.confirmSponsorship(collectionId);40 const changeCollectionOwner = api.tx.nft.changeCollectionOwner(collectionId, Ferdie.address);33 const changeCollectionOwner = api.tx.nft.changeCollectionOwner(collectionId, Ferdie.address);41 await Promise.all34 await Promise.all([tests/src/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth5import getBalance from '../substrate/get-balance';
5import getBalance from '../substrate/get-balance';6import privateKey from '../substrate/privateKey';
6import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
8import {10 confirmSponsorshipExpectSuccess,
9 confirmSponsorshipExpectSuccess,11 createCollectionExpectSuccess,
10 createCollectionExpectSuccess,17const expect = chai.expect;
16const expect = chai.expect;18let Alice: IKeyringPair;
17let Alice: IKeyringPair;19let Bob: IKeyringPair;
18let Bob: IKeyringPair;20let Ferdie: IKeyringPair;
1921
22before(async () => {
20before(async () => {23 await usingApi(async () => {
21 await usingApi(async () => {24 Alice = privateKey('//Alice');
22 Alice = privateKey('//Alice');25 Bob = privateKey('//Bob');
23 Bob = privateKey('//Bob');26 Ferdie = privateKey('//Ferdie');
27 });
24 });28});
25});29
2638 const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
35 const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');39 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
36 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);40 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
37 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');41 //
3842 const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
39 const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);43 const sendItem = api.tx.nft.transfer(Alice.address, collectionId, itemId, 1);
40 const sendItem = api.tx.nft.transfer(Alice.address, collectionId, itemId, 1);44 const revokeSponsor = api.tx.nft.removeCollectionSponsor(collectionId);
41 const revokeSponsor = api.tx.nft.removeCollectionSponsor(collectionId);tests/src/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth131314chai.use(chaiAsPromised);14chai.use(chaiAsPromised);15const expect = chai.expect;15const expect = chai.expect;16interface ITokenDataType {17 Owner: number[];18 ConstData: number[];19 VariableData: number[];20}21let Alice: IKeyringPair;16let Alice: IKeyringPair;22let Bob: IKeyringPair;17let Bob: IKeyringPair;23let Ferdie: IKeyringPair;18let Ferdie: IKeyringPair;63 expect(subTxTesult.success).to.be.true;58 expect(subTxTesult.success).to.be.true;64 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));59 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));65 await timeoutPromise(10000);60 await timeoutPromise(10000);66 //6167 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];62 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];68 const mintItemOne = api.tx.nft63 const mintItemOne = api.tx.nft69 .createMultipleItems(collectionId, Ferdie.address, args);64 .createMultipleItems(collectionId, Ferdie.address, args);tests/src/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi from '../substrate/substrate-api';6import waitNewBlocks from '../substrate/wait-new-blocks';
7import {
6import {8 addToWhiteListExpectSuccess,
7 addToWhiteListExpectSuccess,9 createCollectionExpectSuccess,
8 createCollectionExpectSuccess,13chai.use(chaiAsPromised);
12chai.use(chaiAsPromised);14const expect = chai.expect;
13const expect = chai.expect;15let Alice: IKeyringPair;
14let Alice: IKeyringPair;16let Bob: IKeyringPair;
17let Ferdie: IKeyringPair;
15let Ferdie: IKeyringPair;18
1619before(async () => {
17before(async () => {20 await usingApi(async () => {
18 await usingApi(async () => {21 Alice = privateKey('//Alice');
19 Alice = privateKey('//Alice');22 Bob = privateKey('//Bob');
23 Ferdie = privateKey('//Ferdie');
20 Ferdie = privateKey('//Ferdie');24 });
21 });25});
22});32 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));
29 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));33 await setMintPermissionExpectSuccess(Alice, collectionId, true);
30 await setMintPermissionExpectSuccess(Alice, collectionId, true);34 await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);
31 await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);35 //
3236 const mintItem = api.tx.nft.createItem(collectionId, Ferdie.address, 'NFT');
33 const mintItem = api.tx.nft.createItem(collectionId, Ferdie.address, 'NFT');37 const offMinting = api.tx.nft.setMintPermission(collectionId, false);
34 const offMinting = api.tx.nft.setMintPermission(collectionId, false);38 await Promise.all
35 await Promise.all([39 ([
40 mintItem.signAndSend(Ferdie),
36 mintItem.signAndSend(Ferdie),41 offMinting.signAndSend(Alice),
37 offMinting.signAndSend(Alice),42 ]);
38 ]);43 let itemList: boolean = false;
39 let itemList = false;44 itemList = (await (api.query.nft.nftItemList(collectionId, mintItem))).toJSON() as boolean;
40 itemList = (await (api.query.nft.nftItemList(collectionId, mintItem))).toJSON() as boolean;45 // tslint:disable-next-line: no-unused-expression
41 // tslint:disable-next-line: no-unused-expression46 expect(itemList).to.be.null;
42 expect(itemList).to.be.null;tests/src/config.tsdiffbeforeafterboth778const config = {8const config = {9 substrateUrl: process.env.substrateUrl || 'ws://127.0.0.1:9844'9 substrateUrl: process.env.substrateUrl || 'ws://127.0.0.1:9844',10}10};111112export default config;12export default config;tests/src/config_docker.tsdiffbeforeafterboth778const config = {8const config = {9 substrateUrl: process.env.substrateUrl || 'ws://172.17.0.1:9944'9 substrateUrl: process.env.substrateUrl || 'ws://172.17.0.1:9944',10}10};111112export default config;12export default config;tests/src/confirmSponsorship.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 setCollectionSponsorExpectSuccess, 11 setCollectionSponsorExpectSuccess, 12 destroyCollectionExpectSuccess, 12 destroyCollectionExpectSuccess, 13 setCollectionSponsorExpectFailure,14 confirmSponsorshipExpectSuccess,13 confirmSponsorshipExpectSuccess,15 confirmSponsorshipExpectFailure,14 confirmSponsorshipExpectFailure,16 createItemExpectSuccess,15 createItemExpectSuccess,20 enablePublicMintingExpectSuccess,19 enablePublicMintingExpectSuccess,21 addToWhiteListExpectSuccess,20 addToWhiteListExpectSuccess,22 normalizeAccountId,21 normalizeAccountId,23} from "./util/helpers";22} from './util/helpers';24import { Keyring } from "@polkadot/api";23import { Keyring } from '@polkadot/api';25import { IKeyringPair } from "@polkadot/types/types";24import { IKeyringPair } from '@polkadot/types/types';26import type { AccountId } from '@polkadot/types/interfaces';27import { BigNumber } from 'bignumber.js';25import { BigNumber } from 'bignumber.js';282629chai.use(chaiAsPromised);27chai.use(chaiAsPromised);36describe('integration test: ext. confirmSponsorship():', () => {34describe('integration test: ext. confirmSponsorship():', () => {373538 before(async () => {36 before(async () => {39 await usingApi(async (api) => {37 await usingApi(async () => {40 const keyring = new Keyring({ type: 'sr25519' });38 const keyring = new Keyring({ type: 'sr25519' });41 alice = keyring.addFromUri(`//Alice`);39 alice = keyring.addFromUri('//Alice');42 bob = keyring.addFromUri(`//Bob`);40 bob = keyring.addFromUri('//Bob');43 charlie = keyring.addFromUri(`//Charlie`);41 charlie = keyring.addFromUri('//Charlie');44 });42 });45 });43 });4644163 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);161 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);164162165 // Mint token using unused address as signer163 // Mint token using unused address as signer166 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);164 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);167165168 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());166 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());169167195 const badTransaction = async function () { 193 const badTransaction = async function () { 196 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);194 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);197 };195 };198 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");196 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');199 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());197 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());200198201 // Try again after Zero gets some balance - now it should succeed199 // Try again after Zero gets some balance - now it should succeed229227230 const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());228 const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());231232 const badTransaction = async function () { 233 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);229 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);234 };235236 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());230 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());237231271 const badTransaction = async function () { 265 const badTransaction = async function () { 272 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);266 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);273 };267 };274 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");268 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');275 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());269 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());276270277 // Try again after Zero gets some balance - now it should succeed271 // Try again after Zero gets some balance - now it should succeed317 const badTransaction = async function () { 311 const badTransaction = async function () { 318 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);312 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);319 };313 };320 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");314 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');321 console.error = consoleError;315 console.error = consoleError;322 console.log = consoleLog;316 console.log = consoleLog;323 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());317 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());335329336describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {330describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {337 before(async () => {331 before(async () => {338 await usingApi(async (api) => {332 await usingApi(async () => {339 const keyring = new Keyring({ type: 'sr25519' });333 const keyring = new Keyring({ type: 'sr25519' });340 alice = keyring.addFromUri(`//Alice`);334 alice = keyring.addFromUri('//Alice');341 bob = keyring.addFromUri(`//Bob`);335 bob = keyring.addFromUri('//Bob');342 charlie = keyring.addFromUri(`//Charlie`);336 charlie = keyring.addFromUri('//Charlie');343 });337 });344 });338 });345339346 it('(!negative test!) Confirm sponsorship for a collection that never existed', async () => {340 it('(!negative test!) Confirm sponsorship for a collection that never existed', async () => {347 // Find the collection that never existed341 // Find the collection that never existed348 const collectionId = 0;342 let collectionId = 0;349 await usingApi(async (api) => {343 await usingApi(async (api) => {350 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;344 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;351 });345 });352346353 await confirmSponsorshipExpectFailure(collectionId, '//Bob');347 await confirmSponsorshipExpectFailure(collectionId, '//Bob');tests/src/connection.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import usingApi from "./substrate/substrate-api";6import usingApi from './substrate/substrate-api';7import { WsProvider } from '@polkadot/api';7import { WsProvider } from '@polkadot/api';8import * as chai from 'chai';8import * as chai from 'chai';9import chaiAsPromised from 'chai-as-promised';9import chaiAsPromised from 'chai-as-promised';29 const neverConnectProvider = new WsProvider('ws://255.255.255.255:9944');29 const neverConnectProvider = new WsProvider('ws://255.255.255.255:9944');30 await expect((async () => {30 await expect((async () => {31 await usingApi(async api => {31 await usingApi(async api => {32 const health = await api.rpc.system.health();32 await api.rpc.system.health();33 }, { provider: neverConnectProvider });33 }, { provider: neverConnectProvider });34 })()).to.be.eventually.rejected;34 })()).to.be.eventually.rejected;3535tests/src/contracts.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync } from './substrate/substrate-api';9import fs from "fs";9import fs from 'fs';10import { Abi, ContractPromise as Contract } from "@polkadot/api-contract";10import { Abi, ContractPromise as Contract } from '@polkadot/api-contract';11import privateKey from "./substrate/privateKey";11import privateKey from './substrate/privateKey';12import {12import {13 deployFlipper,13 deployFlipper,14 getFlipValue,14 getFlipValue,15 deployTransferContract,15 deployTransferContract,16} from "./util/contracthelpers";16} from './util/contracthelpers';171718import {18import {19 addToWhiteListExpectSuccess,19 addToWhiteListExpectSuccess,25 getGenericResult,25 getGenericResult,26 normalizeAccountId,26 normalizeAccountId,27 isWhitelisted,27 isWhitelisted,28 transferFromExpectSuccess28 transferFromExpectSuccess,29} from "./util/helpers";29} from './util/helpers';3030313132chai.use(chaiAsPromised);32chai.use(chaiAsPromised);37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';383839describe('Contracts', () => {39describe('Contracts', () => {40 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {40 it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {41 await usingApi(async api => {41 await usingApi(async api => {42 const [contract, deployer] = await deployFlipper(api);42 const [contract, deployer] = await deployFlipper(api);43 const initialGetResponse = await getFlipValue(contract, deployer);43 const initialGetResponse = await getFlipValue(contract, deployer);444445 const bob = privateKey("//Bob");45 const bob = privateKey('//Bob');46 const flip = contract.tx.flip(value, gasLimit);46 const flip = contract.tx.flip(value, gasLimit);47 await submitTransactionAsync(bob, flip);47 await submitTransactionAsync(bob, flip);484865describe.only('Chain extensions', () => {65describe.only('Chain extensions', () => {66 it('Transfer CE', async () => {66 it('Transfer CE', async () => {67 await usingApi(async api => {67 await usingApi(async api => {68 const alice = privateKey("//Alice");68 const alice = privateKey('//Alice');69 const bob = privateKey("//Bob");69 const bob = privateKey('//Bob');707071 // Prep work71 // Prep work72 const collectionId = await createCollectionExpectSuccess();72 const collectionId = await createCollectionExpectSuccess();73 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');73 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');74 const [contract, deployer] = await deployTransferContract(api);74 const [contract] = await deployTransferContract(api);75 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);75 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);76 await submitTransactionAsync(alice, changeAdminTx);76 await submitTransactionAsync(alice, changeAdminTx);777796 const bob = privateKey('//Bob');96 const bob = privateKey('//Bob');979798 const collectionId = await createCollectionExpectSuccess();98 const collectionId = await createCollectionExpectSuccess();99 const [contract, deployer] = await deployTransferContract(api);99 const [contract] = await deployTransferContract(api);100 await enablePublicMintingExpectSuccess(alice, collectionId);100 await enablePublicMintingExpectSuccess(alice, collectionId);101 await enableWhiteListExpectSuccess(alice, collectionId);101 await enableWhiteListExpectSuccess(alice, collectionId);102 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);102 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);124 const bob = privateKey('//Bob');124 const bob = privateKey('//Bob');125125126 const collectionId = await createCollectionExpectSuccess();126 const collectionId = await createCollectionExpectSuccess();127 const [contract, deployer] = await deployTransferContract(api);127 const [contract] = await deployTransferContract(api);128 await enablePublicMintingExpectSuccess(alice, collectionId);128 await enablePublicMintingExpectSuccess(alice, collectionId);129 await enableWhiteListExpectSuccess(alice, collectionId);129 await enableWhiteListExpectSuccess(alice, collectionId);130 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);130 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);169 const charlie = privateKey('//Charlie');169 const charlie = privateKey('//Charlie');170170171 const collectionId = await createCollectionExpectSuccess();171 const collectionId = await createCollectionExpectSuccess();172 const [contract, deployer] = await deployTransferContract(api);172 const [contract] = await deployTransferContract(api);173 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());173 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());174174175 const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);175 const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);188 const charlie = privateKey('//Charlie');188 const charlie = privateKey('//Charlie');189189190 const collectionId = await createCollectionExpectSuccess();190 const collectionId = await createCollectionExpectSuccess();191 const [contract, deployer] = await deployTransferContract(api);191 const [contract] = await deployTransferContract(api);192 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);192 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);193 await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);193 await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);194194197 const result = getGenericResult(events);197 const result = getGenericResult(events);198 expect(result.success).to.be.true;198 expect(result.success).to.be.true;199199200 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()200 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();201 expect(token.Owner.toString()).to.be.equal(charlie.address);201 expect(token.Owner.toString()).to.be.equal(charlie.address);202 });202 });203 });203 });207 const alice = privateKey('//Alice');207 const alice = privateKey('//Alice');208208209 const collectionId = await createCollectionExpectSuccess();209 const collectionId = await createCollectionExpectSuccess();210 const [contract, deployer] = await deployTransferContract(api);210 const [contract] = await deployTransferContract(api);211 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());211 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());212212213 const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');213 const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');214 const events = await submitTransactionAsync(alice, transferTx);214 const events = await submitTransactionAsync(alice, transferTx);215 const result = getGenericResult(events);215 const result = getGenericResult(events);216 expect(result.success).to.be.true;216 expect(result.success).to.be.true;217217218 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()218 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();219 expect(token.VariableData.toString()).to.be.equal('0x121314');219 expect(token.VariableData.toString()).to.be.equal('0x121314');220 });220 });221 });221 });226 const bob = privateKey('//Bob');226 const bob = privateKey('//Bob');227227228 const collectionId = await createCollectionExpectSuccess();228 const collectionId = await createCollectionExpectSuccess();229 const [contract, deployer] = await deployTransferContract(api);229 const [contract] = await deployTransferContract(api);230 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);230 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);231 await submitTransactionAsync(alice, changeAdminTx); 231 await submitTransactionAsync(alice, changeAdminTx); 232232tests/src/createItem.test.tsdiffbeforeafterboth4//
4//5
56import { default as usingApi } from './substrate/substrate-api';
6import { default as usingApi } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";
7import { Keyring } from '@polkadot/api';8import { IKeyringPair } from "@polkadot/types/types";
8import { IKeyringPair } from '@polkadot/types/types';9import {
9import { 10 createCollectionExpectSuccess,
10 createCollectionExpectSuccess, 11 createItemExpectSuccess
11 createItemExpectSuccess,12} from './util/helpers';
12} from './util/helpers';13
1314let alice: IKeyringPair;
14let alice: IKeyringPair;15
1516describe('integration test: ext. createItem():', () => {
16describe('integration test: ext. createItem():', () => {17 before(async () => {
17 before(async () => {18 await usingApi(async (api) => {
18 await usingApi(async () => {19 const keyring = new Keyring({ type: 'sr25519' });
19 const keyring = new Keyring({ type: 'sr25519' });20 alice = keyring.addFromUri(`//Alice`);
20 alice = keyring.addFromUri('//Alice');21 });
21 });22 });
22 });23
23tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { alicesPublicKey, bobsPublicKey } from "./accounts";9import { alicesPublicKey, bobsPublicKey } from './accounts';10import privateKey from "./substrate/privateKey";10import privateKey from './substrate/privateKey';11import { BigNumber } from 'bignumber.js';11import { BigNumber } from 'bignumber.js';12import { IKeyringPair } from '@polkadot/types/types';12import { IKeyringPair } from '@polkadot/types/types';13import { 13import { 14 createCollectionExpectSuccess, 14 createCollectionExpectSuccess, 15 createItemExpectSuccess,15 createItemExpectSuccess,16 getGenericResult,16 getGenericResult,17 transferExpectSuccess17 transferExpectSuccess,18} from './util/helpers';18} from './util/helpers';191920import { default as waitNewBlocks } from './substrate/wait-new-blocks';20import { default as waitNewBlocks } from './substrate/wait-new-blocks';23chai.use(chaiAsPromised);23chai.use(chaiAsPromised);24const expect = chai.expect;24const expect = chai.expect;252526const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";26const Treasury = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';27const saneMinimumFee = 0.05;27const saneMinimumFee = 0.05;28const saneMaximumFee = 0.5;28const saneMaximumFee = 0.5;29const createCollectionDeposit = 100;29const createCollectionDeposit = 100;333334// Skip the inflation block pauses if the block is close to inflation block 34// Skip the inflation block pauses if the block is close to inflation block 35// until the inflation happens35// until the inflation happens36/*eslint no-async-promise-executor: "off"*/36function skipInflationBlock(api: ApiPromise): Promise<void> {37function skipInflationBlock(api: ApiPromise): Promise<void> {37 const promise = new Promise<void>(async (resolve, reject) => {38 const promise = new Promise<void>(async (resolve) => {38 const blockInterval = parseInt((await api.consts.inflation.inflationBlockInterval).toString());39 const blockInterval = parseInt((await api.consts.inflation.inflationBlockInterval).toString());39 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const currentBlock = parseInt(head.number.toString());41 const currentBlock = parseInt(head.number.toString());525353describe('integration test: Fees must be credited to Treasury:', () => {54describe('integration test: Fees must be credited to Treasury:', () => {54 before(async () => {55 before(async () => {55 await usingApi(async (api) => {56 await usingApi(async () => {56 alice = privateKey('//Alice');57 alice = privateKey('//Alice');57 bob = privateKey('//Bob');58 bob = privateKey('//Bob');58 });59 });tests/src/destroyCollection.test.tsdiffbeforeafterboth7import chai from 'chai';7import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';8import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';9import privateKey from './substrate/privateKey';10import { default as usingApi } from "./substrate/substrate-api";10import { default as usingApi } from './substrate/substrate-api';11import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from "./util/helpers";11import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);141431 let alice: IKeyringPair;31 let alice: IKeyringPair;323233 before(async () => {33 before(async () => {34 await usingApi(async (api) => {34 await usingApi(async () => {35 alice = privateKey('//Alice');35 alice = privateKey('//Alice');36 });36 });37 });37 });tests/src/enableContractSponsoring.test.tsdiffbeforeafterboth818182 it('fails when called by non-owning user', async () => {82 it('fails when called by non-owning user', async () => {83 await usingApi(async (api) => {83 await usingApi(async (api) => {84 const [flipper, _] = await deployFlipper(api);84 const [flipper] = await deployFlipper(api);858586 await enableContractSponsoringExpectFailure(alice, flipper.address, true);86 await enableContractSponsoringExpectFailure(alice, flipper.address, true);87 });87 });tests/src/eth/fungible.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import privateKey from "../substrate/privateKey";6import privateKey from '../substrate/privateKey';2import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from "../util/helpers";7import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';3import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from "./util/helpers"8import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';4import fungibleAbi from './fungibleAbi.json';9import fungibleAbi from './fungibleAbi.json';5import { expect } from "chai";10import { expect } from 'chai';6117describe('Information getting', () => {12describe('Information getting', () => {8 itWeb3('totalSupply', async ({ web3 }) => {13 itWeb3('totalSupply', async ({ web3 }) => {170 value: '50',175 value: '50',171 }176 },172 },177 },173 ])178 ]);174 }179 }175180176 {181 {tests/src/eth/metadata.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { expect } from "chai";6import { expect } from 'chai';2import privateKey from "../substrate/privateKey";7import privateKey from '../substrate/privateKey';3import { createCollectionExpectSuccess } from "../util/helpers";8import { createCollectionExpectSuccess } from '../util/helpers';4import { collectionIdToAddress, createEthAccount, itWeb3, transferBalanceToEth } from "./util/helpers";9import { collectionIdToAddress, createEthAccount, itWeb3, transferBalanceToEth } from './util/helpers';5import fungibleMetadataAbi from './fungibleMetadataAbi.json';10import fungibleMetadataAbi from './fungibleMetadataAbi.json';6117describe('Common metadata', () => {12describe('Common metadata', () => {49 const decimals = await contract.methods.decimals().call({ from: caller });54 const decimals = await contract.methods.decimals().call({ from: caller });505551 expect(+decimals).to.equal(6);56 expect(+decimals).to.equal(6);52 })57 });53})58});tests/src/eth/nonFungible.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import privateKey from "../substrate/privateKey";6import privateKey from '../substrate/privateKey';2import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from "../util/helpers";7import { approveExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';3import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from "./util/helpers"8import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';4import nonFungibleAbi from './nonFungibleAbi.json';9import nonFungibleAbi from './nonFungibleAbi.json';5import { expect } from "chai";10import { expect } from 'chai';6117describe('Information getting', () => {12describe('Information getting', () => {8 itWeb3('totalSupply', async ({ web3 }) => {13 itWeb3('totalSupply', async ({ web3 }) => {170 tokenId: tokenId.toString(),175 tokenId: tokenId.toString(),171 }176 },172 },177 },173 ])178 ]);174 }179 }175180176 {181 {tests/src/eth/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';2import { addressToEvm, evmToAddress } from "@polkadot/util-crypto";7import { addressToEvm, evmToAddress } from '@polkadot/util-crypto';3import Web3 from "web3";8import Web3 from 'web3';4import usingApi, { submitTransactionAsync } from "../../substrate/substrate-api";9import usingApi, { submitTransactionAsync } from '../../substrate/substrate-api';5import { IKeyringPair } from '@polkadot/types/types';10import { IKeyringPair } from '@polkadot/types/types';6import { expect } from "chai";11import { expect } from 'chai';7import { getGenericResult } from "../../util/helpers";12import { getGenericResult } from '../../util/helpers';8139let web3Connected = false;14let web3Connected = false;10export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {15export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {11 if (web3Connected) throw new Error('do not nest usingWeb3 calls');16 if (web3Connected) throw new Error('do not nest usingWeb3 calls');12 web3Connected = true;17 web3Connected = true;131814 const provider = new Web3.providers.WebsocketProvider("http://localhost:9944");19 const provider = new Web3.providers.WebsocketProvider('http://localhost:9944');15 const web3 = new Web3(provider);20 const web3 = new Web3(provider);162117 try {22 try {63itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });68itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });646965export async function generateSubstrateEthPair(web3: Web3) {70export async function generateSubstrateEthPair(web3: Web3) {66 let account = web3.eth.accounts.create();71 const account = web3.eth.accounts.create();67 const evm = evmToAddress(account.address);72 evmToAddress(account.address);68}73}697470type NormalizedEvent = {75type NormalizedEvent = {758076export function normalizeEvents(events: any): NormalizedEvent[] {81export function normalizeEvents(events: any): NormalizedEvent[] {77 const output = [];82 const output = [];78 for (let key of Object.keys(events)) {83 for (const key of Object.keys(events)) {79 if (key.match(/^[0-9]+$/)) {84 if (key.match(/^[0-9]+$/)) {80 output.push(events[key]);85 output.push(events[key]);81 } else if (Array.isArray(events[key])) {86 } else if (Array.isArray(events[key])) {87 output.sort((a, b) => a.logIndex - b.logIndex);92 output.sort((a, b) => a.logIndex - b.logIndex);88 return output.map(({ address, event, returnValues }) => {93 return output.map(({ address, event, returnValues }) => {89 const args: { [key: string]: string } = {};94 const args: { [key: string]: string } = {};90 for (let key of Object.keys(returnValues)) {95 for (const key of Object.keys(returnValues)) {91 if (!key.match(/^[0-9]+$/)) {96 if (!key.match(/^[0-9]+$/)) {92 args[key] = returnValues[key];97 args[key] = returnValues[key];93 }98 }tests/src/inflation.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi } from "./substrate/substrate-api";8import { default as usingApi } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";10import { BigNumber } from 'bignumber.js';9import { BigNumber } from 'bignumber.js';11import { IKeyringPair } from '@polkadot/types/types';121013chai.use(chaiAsPromised);11chai.use(chaiAsPromised);14const expect = chai.expect;12const expect = chai.expect;1516let alice: IKeyringPair;17let bob: IKeyringPair;181319describe('integration test: Inflation', () => {14describe('integration test: Inflation', () => {20 before(async () => {21 await usingApi(async (api) => {22 alice = privateKey('//Alice');23 bob = privateKey('//Bob');24 });25 });2627 it('First year inflation is 10%', async () => {15 it('First year inflation is 10%', async () => {28 await usingApi(async (api) => {16 await usingApi(async (api) => {tests/src/overflow.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { IKeyringPair } from "@polkadot/types/types";6import { IKeyringPair } from '@polkadot/types/types';7import chai from 'chai';7import chai from 'chai';8import chaiAsPromised from "chai-as-promised";8import chaiAsPromised from 'chai-as-promised';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import usingApi from "./substrate/substrate-api";10import usingApi from './substrate/substrate-api';11import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFail, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from "./util/helpers";11import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFail, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;14const expect = chai.expect;tests/src/pallet-presence.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';7import { expect } from "chai";7import { expect } from 'chai';8import usingApi from "./substrate/substrate-api";8import usingApi from './substrate/substrate-api';9910function getModuleNames(api: ApiPromise): string[] {10function getModuleNames(api: ApiPromise): string[] {11 return api.runtimeMetadata.asLatest.modules.map(m => m.name.toString().toLowerCase());11 return api.runtimeMetadata.asLatest.modules.map(m => m.name.toString().toLowerCase());tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 setCollectionSponsorExpectSuccess, 11 setCollectionSponsorExpectSuccess, 12 destroyCollectionExpectSuccess, 12 destroyCollectionExpectSuccess, 13 setCollectionSponsorExpectFailure,14 confirmSponsorshipExpectSuccess,13 confirmSponsorshipExpectSuccess,15 confirmSponsorshipExpectFailure,14 confirmSponsorshipExpectFailure,16 createItemExpectSuccess,15 createItemExpectSuccess,17 findUnusedAddress,16 findUnusedAddress,18 getGenericResult,19 enableWhiteListExpectSuccess,20 enablePublicMintingExpectSuccess,21 addToWhiteListExpectSuccess,22 removeCollectionSponsorExpectSuccess,17 removeCollectionSponsorExpectSuccess,23 removeCollectionSponsorExpectFailure,18 removeCollectionSponsorExpectFailure,24 normalizeAccountId,19 normalizeAccountId,25} from "./util/helpers";20} from './util/helpers';26import { Keyring } from "@polkadot/api";21import { Keyring } from '@polkadot/api';27import { IKeyringPair } from "@polkadot/types/types";22import { IKeyringPair } from '@polkadot/types/types';28import type { AccountId } from '@polkadot/types/interfaces';29import { BigNumber } from 'bignumber.js';23import { BigNumber } from 'bignumber.js';302431chai.use(chaiAsPromised);25chai.use(chaiAsPromised);32const expect = chai.expect;26const expect = chai.expect;332734let alice: IKeyringPair;28let alice: IKeyringPair;35let bob: IKeyringPair;29let bob: IKeyringPair;36let charlie: IKeyringPair;373038describe('integration test: ext. removeCollectionSponsor():', () => {31describe('integration test: ext. removeCollectionSponsor():', () => {393240 before(async () => {33 before(async () => {41 await usingApi(async (api) => {34 await usingApi(async () => {42 const keyring = new Keyring({ type: 'sr25519' });35 const keyring = new Keyring({ type: 'sr25519' });43 alice = keyring.addFromUri(`//Alice`);36 alice = keyring.addFromUri('//Alice');44 bob = keyring.addFromUri(`//Bob`);37 bob = keyring.addFromUri('//Bob');45 charlie = keyring.addFromUri(`//Charlie`);46 });38 });47 });39 });484065 const badTransaction = async function () { 57 const badTransaction = async function () { 66 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);58 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);67 };59 };68 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");60 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');69 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());61 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());706271 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;63 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;958796describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {88describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {97 before(async () => {89 before(async () => {98 await usingApi(async (api) => {90 await usingApi(async () => {99 const keyring = new Keyring({ type: 'sr25519' });91 const keyring = new Keyring({ type: 'sr25519' });100 alice = keyring.addFromUri(`//Alice`);92 alice = keyring.addFromUri('//Alice');101 bob = keyring.addFromUri(`//Bob`);93 bob = keyring.addFromUri('//Bob');102 charlie = keyring.addFromUri(`//Charlie`);103 });94 });104 });95 });10596106 it('(!negative test!) Remove sponsor for a collection that never existed', async () => {97 it('(!negative test!) Remove sponsor for a collection that never existed', async () => {107 // Find the collection that never existed98 // Find the collection that never existed108 const collectionId = 0;99 let collectionId = 0;109 await usingApi(async (api) => {100 await usingApi(async (api) => {110 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;101 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;111 });102 });112103113 await removeCollectionSponsorExpectFailure(collectionId);104 await removeCollectionSponsorExpectFailure(collectionId);tests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import privateKey from "./substrate/privateKey";6import privateKey from './substrate/privateKey';7import usingApi from "./substrate/substrate-api";7import usingApi from './substrate/substrate-api';8import { deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess } from "./util/contracthelpers";8import { deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess } from './util/contracthelpers';9import { addToContractWhiteListExpectSuccess, isWhitelistedInContract, removeFromContractWhiteListExpectFailure, removeFromContractWhiteListExpectSuccess, toggleContractWhitelistExpectSuccess } from "./util/helpers";9import { addToContractWhiteListExpectSuccess, isWhitelistedInContract, removeFromContractWhiteListExpectFailure, removeFromContractWhiteListExpectSuccess, toggleContractWhitelistExpectSuccess } from './util/helpers';10import { IKeyringPair } from '@polkadot/types/types';10import { IKeyringPair } from '@polkadot/types/types';11import { expect } from "chai";11import { expect } from 'chai';121213describe('Integration Test removeFromContractWhiteList', () => {13describe('Integration Test removeFromContractWhiteList', () => {14 let bob: IKeyringPair;14 let bob: IKeyringPair;737374 it('fails when executed by non owner', async () => {74 it('fails when executed by non owner', async () => {75 await usingApi(async (api) => {75 await usingApi(async (api) => {76 const [flipper, _] = await deployFlipper(api);76 const [flipper] = await deployFlipper(api);777778 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);78 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);79 });79 });tests/src/removeFromWhiteList.test.tsdiffbeforeafterboth28 let bob: IKeyringPair;28 let bob: IKeyringPair;292930 before(async () => {30 before(async () => {31 await usingApi(async (api) => {31 await usingApi(async () => {32 alice = privateKey('//Alice');32 alice = privateKey('//Alice');33 bob = privateKey('//Bob');33 bob = privateKey('//Bob');34 });34 });62 let bob: IKeyringPair;62 let bob: IKeyringPair;636364 before(async () => {64 before(async () => {65 await usingApi(async (api) => {65 await usingApi(async () => {66 alice = privateKey('//Alice');66 alice = privateKey('//Alice');67 bob = privateKey('//Bob');67 bob = privateKey('//Bob');68 });68 });tests/src/rpc.load.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { expect, assert } from "chai";7import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";6import usingApi, { submitTransactionAsync } from './substrate/substrate-api';8import { IKeyringPair } from "@polkadot/types/types";7import { IKeyringPair } from '@polkadot/types/types';9import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";8import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from '@polkadot/api-contract';10import { ApiPromise, Keyring } from "@polkadot/api";9import { ApiPromise, Keyring } from '@polkadot/api';11import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";12import { BigNumber } from 'bignumber.js';10import { BigNumber } from 'bignumber.js';13import { findUnusedAddress } from './util/helpers'11import { findUnusedAddress } from './util/helpers';14import fs from "fs";12import fs from 'fs';15import privateKey from "./substrate/privateKey";13import privateKey from './substrate/privateKey';161417const value = 0;15const value = 0;18const gasLimit = 500000n * 1000000n;16const gasLimit = 500000n * 1000000n;19const endowment = `1000000000000000`;17const endowment = '1000000000000000';20182119/*eslint no-async-promise-executor: "off"*/22function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {20function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {23 return new Promise<Blueprint>(async (resolve, reject) => {21 return new Promise<Blueprint>(async (resolve) => {24 const unsub = await code22 const unsub = await code25 .createBlueprint()23 .createBlueprint()26 .signAndSend(alice, (result) => {24 .signAndSend(alice, (result) => {29 resolve(result.blueprint);27 resolve(result.blueprint);30 unsub();28 unsub();31 }29 }32 })30 });33 });31 });34}32}353334/*eslint no-async-promise-executor: "off"*/36function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {35function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {37 return new Promise<any>(async (resolve, reject) => {36 return new Promise<any>(async (resolve) => {38 const unsub = await blueprint.tx37 const unsub = await blueprint.tx39 .new(endowment, gasLimit)38 .new(endowment, gasLimit)40 .signAndSend(alice, (result) => {39 .signAndSend(alice, (result) => {525153 // Transfer balance to it52 // Transfer balance to it54 const keyring = new Keyring({ type: 'sr25519' });53 const keyring = new Keyring({ type: 'sr25519' });55 const alice = keyring.addFromUri(`//Alice`);54 const alice = keyring.addFromUri('//Alice');56 let amount = new BigNumber(endowment);55 let amount = new BigNumber(endowment);57 amount = amount.plus(1e15);56 amount = amount.plus(1e15);58 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());57 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());81 const result = await contract.query.get(deployer.address, value, gasLimit);80 const result = await contract.query.get(deployer.address, value, gasLimit);828183 if(!result.result.isSuccess) {82 if(!result.result.isSuccess) {84 throw `Failed to get value`;83 throw 'Failed to get value';85 }84 }86 return result.result.asSuccess.data;85 return result.result.asSuccess.data;87}86}96 let rate = 0;95 let rate = 0;97 const checkPoint = 1000;96 const checkPoint = 1000;9798 /* eslint no-constant-condition: "off" */98 while (true) {99 while (true) {99 await api.rpc.system.chain();100 await api.rpc.system.chain();100 count++;101 count++;101 process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s \r`);102 process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s \r`);102 103 103 if (count % checkPoint == 0) {104 if (count % checkPoint == 0) {104 hrTime = process.hrtime();105 hrTime = process.hrtime();105 let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106 const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106 rate = 1000000*checkPoint/(microsec2 - microsec1);107 rate = 1000000*checkPoint/(microsec2 - microsec1);107 microsec1 = microsec2;108 microsec1 = microsec2;108 }109 }117 const [contract, deployer] = await deployLoadTester(api);118 const [contract, deployer] = await deployLoadTester(api);118119119 // Fill smart contract up with data120 // Fill smart contract up with data120 const bob = privateKey("//Bob");121 const bob = privateKey('//Bob');121 const tx = contract.tx.bloat(value, gasLimit, 200);122 const tx = contract.tx.bloat(value, gasLimit, 200);122 await submitTransactionAsync(bob, tx);123 await submitTransactionAsync(bob, tx);123124128 let rate = 0;129 let rate = 0;129 const checkPoint = 10;130 const checkPoint = 10;131132 /* eslint no-constant-condition: "off" */130 while (true) {133 while (true) {131 await getScData(contract, deployer);134 await getScData(contract, deployer);132 count++;135 count++;133 process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s \r`);136 process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s \r`);134 137 135 if (count % checkPoint == 0) {138 if (count % checkPoint == 0) {136 hrTime = process.hrtime();139 hrTime = process.hrtime();137 let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;140 const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;138 rate = 1000000*checkPoint/(microsec2 - microsec1);141 rate = 1000000*checkPoint/(microsec2 - microsec1);139 microsec1 = microsec2;142 microsec1 = microsec2;140 }143 }tests/src/scheduler.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { IKeyringPair } from '@polkadot/types/types';7import chai from 'chai';6import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';8import privateKey from './substrate/privateKey';10import usingApi from './substrate/substrate-api';9import usingApi from './substrate/substrate-api';11import {10import {12 createItemExpectSuccess,11 createItemExpectSuccess,13 createCollectionExpectSuccess,12 createCollectionExpectSuccess,14 destroyCollectionExpectSuccess,15 findNotExistingCollection,16 queryCollectionExpectSuccess,17 setOffchainSchemaExpectFailure,18 setOffchainSchemaExpectSuccess,19 transferExpectSuccess,20 scheduleTransferExpectSuccess,13 scheduleTransferExpectSuccess,21 setCollectionSponsorExpectSuccess,14 setCollectionSponsorExpectSuccess,22 confirmSponsorshipExpectSuccess15 confirmSponsorshipExpectSuccess,23} from './util/helpers';16} from './util/helpers';24251726chai.use(chaiAsPromised);18chai.use(chaiAsPromised);27const expect = chai.expect;2829const DATA = [1, 2, 3, 4];301931describe('Integration Test scheduler base transaction', () => {20describe('Integration Test scheduler base transaction', () => {32 let alice: IKeyringPair;3334 before(async () => {35 await usingApi(async () => {36 alice = privateKey('//Alice');37 });38 });3940 it('User can transfer owned token with delay (scheduler)', async () => {21 it('User can transfer owned token with delay (scheduler)', async () => {41 await usingApi(async (api) => {22 await usingApi(async () => {42 const Alice = privateKey('//Alice');23 const Alice = privateKey('//Alice');43 const Bob = privateKey('//Bob');24 const Bob = privateKey('//Bob');44 // nft25 // nft54 55});34});5657// describe('Negative Integration Test setOffchainSchema', () => {58// let alice: IKeyringPair;59// let bob: IKeyringPair;6061// let validCollectionId: number;6263// before(async () => {64// await usingApi(async () => {65// alice = privateKey('//Alice');66// bob = privateKey('//Bob');6768// validCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });69// });70// });7172// it('fails on not existing collection id', async () => {73// const nonExistingCollectionId = await usingApi(findNotExistingCollection);7475// await setOffchainSchemaExpectFailure(alice, nonExistingCollectionId, DATA);76// });7778// it('fails on destroyed collection id', async () => {79// const destroyedCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });80// await destroyCollectionExpectSuccess(destroyedCollectionId);8182// await setOffchainSchemaExpectFailure(alice, destroyedCollectionId, DATA);83// });8485// it('fails on too long data', async () => {86// const tooLongData = new Array(4097).fill(0xff);8788// await setOffchainSchemaExpectFailure(alice, validCollectionId, tooLongData);89// });9091// it('fails on execution by non-owner', async () => {92// await setOffchainSchemaExpectFailure(bob, validCollectionId, DATA);93// });94// });9535tests/src/setCollectionLimits.test.tsdiffbeforeafterboth73 it('Set the same token limit twice', async () => {73 it('Set the same token limit twice', async () => {74 await usingApi(async (api: ApiPromise) => {74 await usingApi(async (api: ApiPromise) => {757576 let collectionLimits = {76 const collectionLimits = {77 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,77 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,78 SponsoredMintSize: sponsoredDataSize,78 SponsoredMintSize: sponsoredDataSize,79 TokenLimit: tokenLimit,79 TokenLimit: tokenLimit,206 });206 });207207208 it('Setting the higher token limit fails', async () => {208 it('Setting the higher token limit fails', async () => {209 await usingApi(async (api: ApiPromise) => {209 await usingApi(async () => {210210211 const collectionId = await createCollectionExpectSuccess();211 const collectionId = await createCollectionExpectSuccess();212 let collectionLimits = {212 const collectionLimits = {213 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,213 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,214 SponsoredMintSize: sponsoredDataSize,214 SponsoredMintSize: sponsoredDataSize,215 TokenLimit: tokenLimit,215 TokenLimit: tokenLimit,tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi } from "./substrate/substrate-api";8import { default as usingApi } from './substrate/substrate-api';9import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from "./util/helpers";9import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from './util/helpers';10import { Keyring } from "@polkadot/api";10import { Keyring } from '@polkadot/api';11import { IKeyringPair } from "@polkadot/types/types";11import { IKeyringPair } from '@polkadot/types/types';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;151416let bob: IKeyringPair;15let bob: IKeyringPair;171618describe('integration test: ext. setCollectionSponsor():', () => {17describe('integration test: ext. setCollectionSponsor():', () => {191820 before(async () => {19 before(async () => {21 await usingApi(async (api) => {20 await usingApi(async () => {22 const keyring = new Keyring({ type: 'sr25519' });21 const keyring = new Keyring({ type: 'sr25519' });23 bob = keyring.addFromUri(`//Bob`);22 bob = keyring.addFromUri('//Bob');24 });23 });25 });24 });262546 const collectionId = await createCollectionExpectSuccess();45 const collectionId = await createCollectionExpectSuccess();474648 const keyring = new Keyring({ type: 'sr25519' });47 const keyring = new Keyring({ type: 'sr25519' });49 const charlie = keyring.addFromUri(`//Charlie`);48 const charlie = keyring.addFromUri('//Charlie');50 await setCollectionSponsorExpectSuccess(collectionId, bob.address);49 await setCollectionSponsorExpectSuccess(collectionId, bob.address);51 await setCollectionSponsorExpectSuccess(collectionId, charlie.address);50 await setCollectionSponsorExpectSuccess(collectionId, charlie.address);52 });51 });53});52});545355describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {54describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {56 before(async () => {55 before(async () => {57 await usingApi(async (api) => {56 await usingApi(async () => {58 const keyring = new Keyring({ type: 'sr25519' });57 const keyring = new Keyring({ type: 'sr25519' });59 bob = keyring.addFromUri(`//Bob`);58 bob = keyring.addFromUri('//Bob');60 });59 });61 });60 });626166 });65 });67 it('(!negative test!) Add sponsor to a collection that never existed', async () => {66 it('(!negative test!) Add sponsor to a collection that never existed', async () => {68 // Find the collection that never existed67 // Find the collection that never existed69 const collectionId = 0;68 let collectionId = 0;70 await usingApi(async (api) => {69 await usingApi(async (api) => {71 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;70 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;72 });71 });737274 await setCollectionSponsorExpectFailure(collectionId, bob.address);73 await setCollectionSponsorExpectFailure(collectionId, bob.address);tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth23let largeShema: any;23let largeShema: any;242425before(async () => {25before(async () => {26 await usingApi(async (api) => {26 await usingApi(async () => {27 const keyring = new Keyring({ type: 'sr25519' });27 const keyring = new Keyring({ type: 'sr25519' });28 Alice = keyring.addFromUri('//Alice');28 Alice = keyring.addFromUri('//Alice');29 Bob = keyring.addFromUri('//Bob');29 Bob = keyring.addFromUri('//Bob');tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth595960 it('fails when called by non-owning user', async () => {60 it('fails when called by non-owning user', async () => {61 await usingApi(async (api) => {61 await usingApi(async (api) => {62 const [flipper, _] = await deployFlipper(api);62 const [flipper] = await deployFlipper(api);636364 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);64 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);65 });65 });tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth4//
4//5
56// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
6// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion7import { ApiPromise, Keyring } from '@polkadot/api';
7import { ApiPromise } from '@polkadot/api';8import { IKeyringPair } from '@polkadot/types/types';
8import { IKeyringPair } from '@polkadot/types/types';9import chai from 'chai';
9import chai from 'chai';10import chaiAsPromised from 'chai-as-promised';
10import chaiAsPromised from 'chai-as-promised';19 enableWhiteListExpectSuccess,
19 enableWhiteListExpectSuccess,20 normalizeAccountId,
20 normalizeAccountId,21} from './util/helpers';
21} from './util/helpers';22import { utf16ToStr } from './util/util';
2223
24chai.use(chaiAsPromised);
23chai.use(chaiAsPromised);25const expect = chai.expect;
24const expect = chai.expect;29
2830describe('Integration Test setPublicAccessMode(): ', () => {
29describe('Integration Test setPublicAccessMode(): ', () => {31 before(async () => {
30 before(async () => {32 await usingApi(async (api) => {
31 await usingApi(async () => {33 Alice = privateKey('//Alice');
32 Alice = privateKey('//Alice');34 Bob = privateKey('//Bob');
33 Bob = privateKey('//Bob');35 });
34 });36 });
35 });37
3638 it('Run extrinsic with collection id parameters, set the whitelist mode for the collection', async () => {
37 it('Run extrinsic with collection id parameters, set the whitelist mode for the collection', async () => {39 await usingApi(async (api: ApiPromise) => {
38 await usingApi(async () => {40 const collectionId: number = await createCollectionExpectSuccess();
39 const collectionId: number = await createCollectionExpectSuccess();41 await enableWhiteListExpectSuccess(Alice, collectionId);
40 await enableWhiteListExpectSuccess(Alice, collectionId);42 await enablePublicMintingExpectSuccess(Alice, collectionId);
41 await enablePublicMintingExpectSuccess(Alice, collectionId);77 });
76 });78
7779 it('Re-set the list mode already set in quantity', async () => {
78 it('Re-set the list mode already set in quantity', async () => {80 await usingApi(async (api: ApiPromise) => {
79 await usingApi(async () => {81 const collectionId: number = await createCollectionExpectSuccess();
80 const collectionId: number = await createCollectionExpectSuccess();82 await enableWhiteListExpectSuccess(Alice, collectionId);
81 await enableWhiteListExpectSuccess(Alice, collectionId);83 await enableWhiteListExpectSuccess(Alice, collectionId);
82 await enableWhiteListExpectSuccess(Alice, collectionId);tests/src/setSchemaVersion.test.tsdiffbeforeafterboth103 it('execute setSchemaVersion with not correct schema version', async () => {103 it('execute setSchemaVersion with not correct schema version', async () => {104 await usingApi(async (api: ApiPromise) => {104 await usingApi(async (api: ApiPromise) => {105 const consoleError = console.error;105 const consoleError = console.error;106 console.error = (message: string) => {};106 console.error = () => {};107 try {107 try {108 tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Test');108 tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Test');109 await submitTransactionAsync(alice, tx);109 await submitTransactionAsync(alice, tx);tests/src/setVariableMetaData.test.tsdiffbeforeafterboth49});49});505051describe('Negative Integration Test setVariableMetaData', () => {51describe('Negative Integration Test setVariableMetaData', () => {52 let data = [1];52 const data = [1];535354 let alice: IKeyringPair;54 let alice: IKeyringPair;55 let bob: IKeyringPair;55 let bob: IKeyringPair;696970 it('fails on not existing collection id', async () => {70 it('fails on not existing collection id', async () => {71 await usingApi(async api => {71 await usingApi(async api => {72 let nonExistingCollectionId = await findNotExistingCollection(api);72 const nonExistingCollectionId = await findNotExistingCollection(api);73 await setVariableMetaDataExpectFailure(alice, nonExistingCollectionId, 1, data);73 await setVariableMetaDataExpectFailure(alice, nonExistingCollectionId, 1, data);74 });74 });75 });75 });tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth23let largeSchema: any;23let largeSchema: any;242425before(async () => {25before(async () => {26 await usingApi(async (api) => {26 await usingApi(async () => {27 const keyring = new Keyring({ type: 'sr25519' });27 const keyring = new Keyring({ type: 'sr25519' });28 Alice = keyring.addFromUri('//Alice');28 Alice = keyring.addFromUri('//Alice');29 Bob = keyring.addFromUri('//Bob');29 Bob = keyring.addFromUri('//Bob');tests/src/substrate/privateKey.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { Keyring } from "@polkadot/api";6import { Keyring } from '@polkadot/api';7import { IKeyringPair } from "@polkadot/types/types";7import { IKeyringPair } from '@polkadot/types/types';889export default function privateKey(account: string): IKeyringPair {9export default function privateKey(account: string): IKeyringPair {10 const keyring = new Keyring({ type: 'sr25519' });10 const keyring = new Keyring({ type: 'sr25519' });tests/src/substrate/promisify-substrate.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';778type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;8type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;99tests/src/substrate/substrate-api.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { WsProvider, ApiPromise } from "@polkadot/api";6import { WsProvider, ApiPromise } from '@polkadot/api';7import { EventRecord } from '@polkadot/types/interfaces/system/types';7import { EventRecord } from '@polkadot/types/interfaces/system/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';9import { IKeyringPair } from "@polkadot/types/types";9import { IKeyringPair } from '@polkadot/types/types';101011import config from "../config";11import config from '../config';12import promisifySubstrate from "./promisify-substrate";12import promisifySubstrate from './promisify-substrate';13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from "@polkadot/api/types";13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from '@polkadot/api/types';14import rtt from "../../../runtime_types.json";14import rtt from '../../../runtime_types.json';151516function defaultApiOptions(): ApiOptions {16function defaultApiOptions(): ApiOptions {17 const wsProvider = new WsProvider(config.substrateUrl);17 const wsProvider = new WsProvider(config.substrateUrl);202021export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {21export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {22 settings = settings || defaultApiOptions();22 settings = settings || defaultApiOptions();23 let api: ApiPromise = new ApiPromise(settings);23 const api: ApiPromise = new ApiPromise(settings);24 let result: T = null as unknown as T;24 let result: T = null as unknown as T;252526 // TODO: Remove, this is temporary: Filter unneeded API output 26 // TODO: Remove, this is temporary: Filter unneeded API output 27 // (Jaco promised it will be removed in the next version)27 // (Jaco promised it will be removed in the next version)28 const consoleErr = console.error;28 const consoleErr = console.error;29 console.error = (message: string) => {29 console.error = (message: string) => {30 if (message.includes("StorageChangeSet:: WebSocket is not connected") || message.includes("2021-")) {}30 if (!message.includes('StorageChangeSet:: WebSocket is not connected') || message.includes('2021-'))31 else consoleErr(message);31 consoleErr(message);32 };32 };333334 try {34 try {727273export function73export function74submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {74submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {75 /* eslint no-async-promise-executor: "off" */75 return new Promise(async (resolve, reject) => {76 return new Promise(async (resolve, reject) => {76 try {77 try {77 await transaction.signAndSend(sender, ({ events = [], status }) => {78 await transaction.signAndSend(sender, ({ events = [], status }) => {97 console.error = () => {};98 console.error = () => {};98 console.log = () => {};99 console.log = () => {};99100101 /* eslint no-async-promise-executor: "off" */100 return new Promise<EventRecord[]>(async function(res, rej) {102 return new Promise<EventRecord[]>(async function(res, rej) {101 const resolve = (rec: EventRecord[]) => {103 const resolve = (rec: EventRecord[]) => {102 setTimeout(() => {104 setTimeout(() => {tests/src/substrate/wait-new-blocks.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';778/* eslint no-async-promise-executor: "off" */8export default function waitNewBlocks(api: ApiPromise, blocksCount: number = 1): Promise<void> {9export default function waitNewBlocks(api: ApiPromise, blocksCount = 1): Promise<void> {9 const promise = new Promise<void>(async (resolve, reject) => {10 const promise = new Promise<void>(async (resolve) => {10 11 11 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {12 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {12 if(blocksCount > 0) {13 if (blocksCount > 0) {13 blocksCount--;14 blocksCount--;14 }else {15 } else {tests/src/toggleContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import {10import {11 deployFlipper,11 deployFlipper,12 getFlipValue12 getFlipValue,13} from "./util/contracthelpers";13} from './util/contracthelpers';14import {14import {15 getGenericResult15 getGenericResult,16} from "./util/helpers"16} from './util/helpers';171718chai.use(chaiAsPromised);18chai.use(chaiAsPromised);19const expect = chai.expect;19const expect = chai.expect;232324describe('Integration Test toggleContractWhiteList', () => {24describe('Integration Test toggleContractWhiteList', () => {252526 it(`Enable white list contract mode`, async () => {26 it('Enable white list contract mode', async () => {27 await usingApi(async api => {27 await usingApi(async api => {28 const [contract, deployer] = await deployFlipper(api);28 const [contract, deployer] = await deployFlipper(api);292938 });38 });39 });39 });404041 it(`Only whitelisted account can call contract`, async () => {41 it('Only whitelisted account can call contract', async () => {42 await usingApi(async api => {42 await usingApi(async api => {43 const bob = privateKey("//Bob");43 const bob = privateKey('//Bob');444445 const [contract, deployer] = await deployFlipper(api);45 const [contract, deployer] = await deployFlipper(api);464647 let flipValueBefore = await getFlipValue(contract, deployer);47 let flipValueBefore = await getFlipValue(contract, deployer);48 const flip = contract.exec('flip', value, gasLimit);48 const flip = contract.exec('flip', value, gasLimit);49 await submitTransactionAsync(bob, flip);49 await submitTransactionAsync(bob, flip);50 const flipValueAfter = await getFlipValue(contract,deployer);50 const flipValueAfter = await getFlipValue(contract,deployer);51 expect(flipValueAfter).to.be.eq(!flipValueBefore, `Anyone can call new contract.`);51 expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');525253 const deployerCanFlip = async () => {53 const deployerCanFlip = async () => {54 let flipValueBefore = await getFlipValue(contract, deployer);54 const flipValueBefore = await getFlipValue(contract, deployer);55 const deployerFlip = contract.exec('flip', value, gasLimit);55 const deployerFlip = contract.exec('flip', value, gasLimit);56 await submitTransactionAsync(deployer, deployerFlip);56 await submitTransactionAsync(deployer, deployerFlip);57 const aliceFlip1Response = await getFlipValue(contract, deployer);57 const aliceFlip1Response = await getFlipValue(contract, deployer);58 expect(aliceFlip1Response).to.be.eq(!flipValueBefore, `Deployer always can flip.`);58 expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');59 };59 };60 await deployerCanFlip();60 await deployerCanFlip();616162 flipValueBefore = await getFlipValue(contract, deployer);62 flipValueBefore = await getFlipValue(contract, deployer);63 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);63 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);64 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);64 await submitTransactionAsync(deployer, enableWhiteListTx);65 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);65 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);66 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;66 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;67 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);67 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);68 expect(flipValueAfterEnableWhiteList).to.be.eq(flipValueBefore, `Enabling whitelist doesn't make it possible to call contract for everyone.`);68 expect(flipValueAfterEnableWhiteList).to.be.eq(flipValueBefore, 'Enabling whitelist doesn\'t make it possible to call contract for everyone.');696970 await deployerCanFlip();70 await deployerCanFlip();717172 flipValueBefore = await getFlipValue(contract, deployer);72 flipValueBefore = await getFlipValue(contract, deployer);73 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);73 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);74 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);74 await submitTransactionAsync(deployer, addBobToWhiteListTx);75 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);75 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);76 await submitTransactionAsync(bob, flipWithWhitelistedBob);76 await submitTransactionAsync(bob, flipWithWhitelistedBob);77 const flipAfterWhiteListed = await getFlipValue(contract,deployer);77 const flipAfterWhiteListed = await getFlipValue(contract,deployer);78 expect(flipAfterWhiteListed).to.be.eq(!flipValueBefore, `Bob was whitelisted, now he can flip.`);78 expect(flipAfterWhiteListed).to.be.eq(!flipValueBefore, 'Bob was whitelisted, now he can flip.');797980 await deployerCanFlip();80 await deployerCanFlip();818182 flipValueBefore = await getFlipValue(contract, deployer);82 flipValueBefore = await getFlipValue(contract, deployer);83 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);83 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);84 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);84 await submitTransactionAsync(deployer, removeBobFromWhiteListTx);85 const bobRemoved = contract.exec('flip', value, gasLimit);85 const bobRemoved = contract.exec('flip', value, gasLimit);86 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;86 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;87 const afterBobRemoved = await getFlipValue(contract, deployer);87 const afterBobRemoved = await getFlipValue(contract, deployer);88 expect(afterBobRemoved).to.be.eq(flipValueBefore, `Bob can't call contract, now when he is removeed from white list.`);88 expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from white list.');898990 await deployerCanFlip();90 await deployerCanFlip();919192 flipValueBefore = await getFlipValue(contract, deployer);92 flipValueBefore = await getFlipValue(contract, deployer);93 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);93 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);94 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);94 await submitTransactionAsync(deployer, disableWhiteListTx);95 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);95 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);96 await submitTransactionAsync(bob, whiteListDisabledFlip);96 await submitTransactionAsync(bob, whiteListDisabledFlip);97 const afterWhiteListDisabled = await getFlipValue(contract,deployer);97 const afterWhiteListDisabled = await getFlipValue(contract,deployer);98 expect(afterWhiteListDisabled).to.be.eq(!flipValueBefore, `Anyone can call contract with disabled whitelist.`);98 expect(afterWhiteListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled whitelist.');9999100 });100 });101 });101 });102102103 it(`Enabling white list repeatedly should not produce errors`, async () => {103 it('Enabling white list repeatedly should not produce errors', async () => {104 await usingApi(async api => {104 await usingApi(async api => {105 const [contract, deployer] = await deployFlipper(api);105 const [contract, deployer] = await deployFlipper(api);106106123123124describe('Negative Integration Test toggleContractWhiteList', () => {124describe('Negative Integration Test toggleContractWhiteList', () => {125125126 it(`Enable white list for a non-contract`, async () => {126 it('Enable white list for a non-contract', async () => {127 await usingApi(async api => {127 await usingApi(async api => {128 const alice = privateKey("//Alice");128 const alice = privateKey('//Alice');129 const bobGuineaPig = privateKey("//Bob");129 const bobGuineaPig = privateKey('//Bob');130130131 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();131 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();132 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(bobGuineaPig.address, true);132 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(bobGuineaPig.address, true);138 });138 });139 });139 });140140141 it(`Enable white list using a non-owner address`, async () => {141 it('Enable white list using a non-owner address', async () => {142 await usingApi(async api => {142 await usingApi(async api => {143 const bob = privateKey("//Bob");143 const bob = privateKey('//Bob');144 const [contract, deployer] = await deployFlipper(api);144 const [contract] = await deployFlipper(api);145145146 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();146 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();147 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);147 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);tests/src/transfer.nload.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';2import { IKeyringPair } from '@polkadot/types/types';7import { IKeyringPair } from '@polkadot/types/types';3import privateKey from "./substrate/privateKey";8import privateKey from './substrate/privateKey';4import usingApi, { submitTransactionAsync } from "./substrate/substrate-api";9import usingApi, { submitTransactionAsync } from './substrate/substrate-api';5import waitNewBlocks from "./substrate/wait-new-blocks";10import waitNewBlocks from './substrate/wait-new-blocks';6import { findUnusedAddresses } from "./util/helpers";11import { findUnusedAddresses } from './util/helpers';7import * as cluster from 'cluster';12import * as cluster from 'cluster';8import os from 'os';13import os from 'os';91426}31}273228async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {33async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {29 let accounts = [source];34 const accounts = [source];30 // we don't need source in output array35 // we don't need source in output array31 const failedAccounts = [0];36 const failedAccounts = [0];323736 increaseCounter('requests', finalUserAmount);41 increaseCounter('requests', finalUserAmount);374238 for (let stage = 0; stage < stages; stage++) {43 for (let stage = 0; stage < stages; stage++) {39 let usersWithBalance = 2 ** stage;44 const usersWithBalance = 2 ** stage;40 let amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);45 const amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);41 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);46 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);42 let txs = [];47 const txs = [];43 for (let i = 0; i < usersWithBalance; i++) {48 for (let i = 0; i < usersWithBalance; i++) {44 let newUser = accounts[i + usersWithBalance];49 const newUser = accounts[i + usersWithBalance];45 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);50 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);46 const tx = api.tx.balances.transfer(newUser.address, amount);51 const tx = api.tx.balances.transfer(newUser.address, amount);47 txs.push(submitTransactionAsync(accounts[i], tx).catch(e => {52 txs.push(submitTransactionAsync(accounts[i], tx).catch(() => {48 failedAccounts.push(i + usersWithBalance);53 failedAccounts.push(i + usersWithBalance);49 increaseCounter('txFailed', 1);54 increaseCounter('txFailed', 1);50 }));55 }));53 await Promise.all(txs);58 await Promise.all(txs);54 }59 }556056 for (let account of failedAccounts.reverse()) {61 for (const account of failedAccounts.reverse()) {57 accounts.splice(account, 1);62 accounts.splice(account, 1);58 }63 }59 return accounts;64 return accounts;62if (cluster.isMaster) {67if (cluster.isMaster) {63 let testDone = false;68 let testDone = false;64 usingApi(async (api) => {69 usingApi(async (api) => {65 let prevCounters: { [key: string]: number } = {};70 const prevCounters: { [key: string]: number } = {};66 while (!testDone) {71 while (!testDone) {67 for (let name in counters) {72 for (const name in counters) {68 if (!(name in prevCounters)) {73 if (!(name in prevCounters)) {69 prevCounters[name] = 0;74 prevCounters[name] = 0;70 }75 }77 await waitNewBlocks(api, 1);82 await waitNewBlocks(api, 1);78 }83 }79 });84 });80 let waiting: Promise<void>[] = [];85 const waiting: Promise<void>[] = [];81 console.log(`Starting ${os.cpus().length} workers`);86 console.log(`Starting ${os.cpus().length} workers`);82 usingApi(async (api) => {87 usingApi(async (api) => {83 const alice = privateKey('//Alice');88 const alice = privateKey('//Alice');84 for (let id in os.cpus()) {89 for (const id in os.cpus()) {85 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;90 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;86 const workerAccount = privateKey(WORKER_NAME);91 const workerAccount = privateKey(WORKER_NAME);87 const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);92 const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);88 await submitTransactionAsync(alice, tx);93 await submitTransactionAsync(alice, tx);899490 let worker = cluster.fork({95 const worker = cluster.fork({91 WORKER_NAME,96 WORKER_NAME,92 STAGES: id + 297 STAGES: id + 2,93 });98 });94 worker.on('message', msg => {99 worker.on('message', msg => {95 for (let key in msg) {100 for (const key in msg) {96 increaseCounter(key, msg[key]);101 increaseCounter(key, msg[key]);97 }102 }98 });103 });99 waiting.push(new Promise(res => worker.on('exit', res)));104 waiting.push(new Promise(res => worker.on('exit', res)));100 }105 }101 await Promise.all(waiting);106 await Promise.all(waiting);102 testDone = true;107 testDone = true;103 })108 });104} else {109} else {105 increaseCounter('startedWorkers', 1);110 increaseCounter('startedWorkers', 1);106 usingApi(async (api) => {111 usingApi(async (api) => {tests/src/transfer.test.tsdiffbeforeafterboth64 });64 });656566 it('User can transfer owned token', async () => {66 it('User can transfer owned token', async () => {67 await usingApi(async (api) => {67 await usingApi(async () => {68 const Alice = privateKey('//Alice');68 const Alice = privateKey('//Alice');69 const Bob = privateKey('//Bob');69 const Bob = privateKey('//Bob');70 // nft70 // nft879388describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {94describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {89 before(async () => {95 before(async () => {90 await usingApi(async (api: ApiPromise) => {96 await usingApi(async () => {91 Alice = privateKey('//Alice');97 Alice = privateKey('//Alice');92 Bob = privateKey('//Bob');98 Bob = privateKey('//Bob');93 Charlie = privateKey('//Charlie');99 Charlie = privateKey('//Charlie');tests/src/transferFrom.test.tsdiffbeforeafterboth14 createCollectionExpectSuccess,14 createCollectionExpectSuccess,15 createFungibleItemExpectSuccess,15 createFungibleItemExpectSuccess,16 createItemExpectSuccess,16 createItemExpectSuccess,17 destroyCollectionExpectSuccess,18 getAllowance,17 getAllowance,19 transferFromExpectFail,18 transferFromExpectFail,20 transferFromExpectSuccess,19 transferFromExpectSuccess,31 let Charlie: IKeyringPair;30 let Charlie: IKeyringPair;323133 before(async () => {32 before(async () => {34 await usingApi(async (api) => {33 await usingApi(async () => {35 Alice = privateKey('//Alice');34 Alice = privateKey('//Alice');36 Bob = privateKey('//Bob');35 Bob = privateKey('//Bob');37 Charlie = privateKey('//Charlie');36 Charlie = privateKey('//Charlie');38 });37 });39 });38 });403941 it('Execute the extrinsic and check nftItemList - owner of token', async () => {40 it('Execute the extrinsic and check nftItemList - owner of token', async () => {42 await usingApi(async (api: ApiPromise) => {41 await usingApi(async () => {43 // nft42 // nft44 const nftCollectionId = await createCollectionExpectSuccess();43 const nftCollectionId = await createCollectionExpectSuccess();45 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');44 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');92 let Charlie: IKeyringPair;99 let Charlie: IKeyringPair;9310094 before(async () => {101 before(async () => {95 await usingApi(async (api) => {102 await usingApi(async () => {96 Alice = privateKey('//Alice');103 Alice = privateKey('//Alice');97 Bob = privateKey('//Bob');104 Bob = privateKey('//Bob');98 Charlie = privateKey('//Charlie');105 Charlie = privateKey('//Charlie');139 }); */146 }); */140147141 it('transferFrom for not approved address', async () => {148 it('transferFrom for not approved address', async () => {142 await usingApi(async (api: ApiPromise) => {149 await usingApi(async () => {143 // nft150 // nft144 const nftCollectionId = await createCollectionExpectSuccess();151 const nftCollectionId = await createCollectionExpectSuccess();145 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');152 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');160 });173 });161174162 it('transferFrom incorrect token count', async () => {175 it('transferFrom incorrect token count', async () => {163 await usingApi(async (api: ApiPromise) => {176 await usingApi(async () => {164 // nft177 // nft165 const nftCollectionId = await createCollectionExpectSuccess();178 const nftCollectionId = await createCollectionExpectSuccess();166 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');179 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');184 });203 });185204186 it('execute transferFrom from account that is not owner of collection', async () => {205 it('execute transferFrom from account that is not owner of collection', async () => {187 await usingApi(async (api: ApiPromise) => {206 await usingApi(async () => {188 const Dave = privateKey('//Dave');207 const Dave = privateKey('//Dave');189 // nft208 // nft190 const nftCollectionId = await createCollectionExpectSuccess();209 const nftCollectionId = await createCollectionExpectSuccess();223 });242 });224 });243 });225 it( 'transferFrom burnt token before approve NFT', async () => {244 it( 'transferFrom burnt token before approve NFT', async () => {226 await usingApi(async (api: ApiPromise) => {245 await usingApi(async () => {227 // nft246 // nft228 const nftCollectionId = await createCollectionExpectSuccess();247 const nftCollectionId = await createCollectionExpectSuccess();229 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');248 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');233 });252 });234 });253 });235 it( 'transferFrom burnt token before approve Fungible', async () => {254 it( 'transferFrom burnt token before approve Fungible', async () => {236 await usingApi(async (api: ApiPromise) => {255 await usingApi(async () => {237 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});256 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});238 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');257 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');239 await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);258 await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);243 });262 });244 }); 263 }); 245 it( 'transferFrom burnt token before approve ReFungible', async () => {264 it( 'transferFrom burnt token before approve ReFungible', async () => {246 await usingApi(async (api: ApiPromise) => {265 await usingApi(async () => {247 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});266 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});248 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');267 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');249 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);268 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);254 });273 });255 274 256 it( 'transferFrom burnt token after approve NFT', async () => {275 it( 'transferFrom burnt token after approve NFT', async () => {257 await usingApi(async (api: ApiPromise) => {276 await usingApi(async () => {258 // nft277 // nft259 const nftCollectionId = await createCollectionExpectSuccess();278 const nftCollectionId = await createCollectionExpectSuccess();260 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');279 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');264 });283 });265 });284 });266 it( 'transferFrom burnt token after approve Fungible', async () => {285 it( 'transferFrom burnt token after approve Fungible', async () => {267 await usingApi(async (api: ApiPromise) => {286 await usingApi(async () => {268 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});287 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});269 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');288 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');270 await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);289 await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);274 });293 });275 }); 294 }); 276 it( 'transferFrom burnt token after approve ReFungible', async () => {295 it( 'transferFrom burnt token after approve ReFungible', async () => {277 await usingApi(async (api: ApiPromise) => {296 await usingApi(async () => {278 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});297 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});279 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');298 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');280 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);299 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);tests/src/util/contracthelpers.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";8import { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';9import fs from "fs";9import fs from 'fs';10import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";10import { Abi, CodePromise, ContractPromise as Contract } from '@polkadot/api-contract';11import { IKeyringPair } from "@polkadot/types/types";11import { IKeyringPair } from '@polkadot/types/types';12import { ApiPromise, Keyring } from "@polkadot/api";12import { ApiPromise, Keyring } from '@polkadot/api';131314chai.use(chaiAsPromised);14chai.use(chaiAsPromised);15const expect = chai.expect;15const expect = chai.expect;20const gasLimit = '200000000000';20const gasLimit = '200000000000';21const endowment = '100000000000000000';21const endowment = '100000000000000000';222223/* eslint no-async-promise-executor: "off" */23function deployContract(alice: IKeyringPair, code: CodePromise, constructor: string = 'default', ...args: any[]): Promise<Contract> {24function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {24 return new Promise<Contract>(async (resolve, reject) => {25 return new Promise<Contract>(async (resolve) => {25 const unsub = await (code as any)26 const unsub = await (code as any)26 .tx[constructor]({value: endowment, gasLimit}, ...args)27 .tx[constructor]({value: endowment, gasLimit}, ...args)27 .signAndSend(alice, (result: any) => {28 .signAndSend(alice, (result: any) => {30 resolve((result as any).contract);31 resolve((result as any).contract);31 unsub();32 unsub();32 }33 }33 })34 });34 });35 });35}36}3637404141 // Transfer balance to it42 // Transfer balance to it42 const keyring = new Keyring({ type: 'sr25519' });43 const keyring = new Keyring({ type: 'sr25519' });43 const alice = keyring.addFromUri(`//Alice`);44 const alice = keyring.addFromUri('//Alice');44 let amount = new BigNumber(endowment);45 let amount = new BigNumber(endowment);45 amount = amount.plus(100e15);46 amount = amount.plus(100e15);46 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());47 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());71 const result = await contract.query.get(deployer.address, value, gasLimit);72 const result = await contract.query.get(deployer.address, value, gasLimit);727373 if(!result.result.isOk) {74 if(!result.result.isOk) {74 throw `Failed to get flipper value`;75 throw 'Failed to get flipper value';75 }76 }76 return (result.result.asOk.data[0] == 0x00) ? false : true;77 return (result.result.asOk.data[0] == 0x00) ? false : true;77}78}89 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;90 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;90}91}9192function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {93 return new Promise<any>(async (resolve, reject) => {94 const unsub = await blueprint.tx95 .default(endowment, gasLimit)96 .signAndSend(alice, (result) => {97 if (result.status.isInBlock || result.status.isFinalized) {98 unsub();99 resolve(result);100 }101 }); 102 });103}10492105export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {93export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {106 const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));94 const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));tests/src/util/helpers.tsdiffbeforeafterboth4//4//556import { ApiPromise, Keyring } from '@polkadot/api';6import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, EventRecord } from '@polkadot/types/interfaces';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';8import { IKeyringPair } from '@polkadot/types/types';11import { evmToAddress } from '@polkadot/util-crypto';9import { evmToAddress } from '@polkadot/util-crypto';12import { BigNumber } from 'bignumber.js';10import { BigNumber } from 'bignumber.js';13import BN from 'bn.js';11import BN from 'bn.js';14import chai from 'chai';12import chai from 'chai';15import chaiAsPromised from 'chai-as-promised';13import chaiAsPromised from 'chai-as-promised';16import { alicesPublicKey, nullPublicKey } from '../accounts';14import { alicesPublicKey } from '../accounts';17import privateKey from '../substrate/privateKey';15import privateKey from '../substrate/privateKey';18import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';19import { ICollectionInterface } from '../types';17import { ICollectionInterface } from '../types';20import { hexToStr, strToUTF16, utf16ToStr } from './util';18import { hexToStr, strToUTF16, utf16ToStr } from './util';21import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';22// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';231924chai.use(chaiAsPromised);20chai.use(chaiAsPromised);25const expect = chai.expect;21const expect = chai.expect;87 VariableData: number[];83 VariableData: number[];88}84}8990interface IFungibleTokenDataType {91 Value: BN;92}938594interface IGetMessage {86interface IGetMessage {95 checkMsgNftMethod: string;87 checkMsgNftMethod: string;104}96}10597106export function nftEventMessage(events: EventRecord[]): IGetMessage {98export function nftEventMessage(events: EventRecord[]): IGetMessage {107 let checkMsgNftMethod: string = '';99 let checkMsgNftMethod = '';108 let checkMsgTrsMethod: string = '';100 let checkMsgTrsMethod = '';109 let checkMsgSysMethod: string = '';101 let checkMsgSysMethod = '';110 events.forEach(({ event: { method, section } }) => {102 events.forEach(({ event: { method, section } }) => {111 if (section === 'nft') {103 if (section === 'nft') {112 checkMsgNftMethod = method;104 checkMsgNftMethod = method;128 const result: GenericResult = {120 const result: GenericResult = {129 success: false,121 success: false,130 };122 };131 events.forEach(({ phase, event: { data, method, section } }) => {123 events.forEach(({ event: { method } }) => {132 // console.log(` ${phase}: ${section}.${method}:: ${data}`);124 // console.log(` ${phase}: ${section}.${method}:: ${data}`);133 if (method === 'ExtrinsicSuccess') {125 if (method === 'ExtrinsicSuccess') {134 result.success = true;126 result.success = true;141133142export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {134export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {143 let success = false;135 let success = false;144 let collectionId: number = 0;136 let collectionId = 0;145 events.forEach(({ phase, event: { data, method, section } }) => {137 events.forEach(({ event: { data, method, section } }) => {146 // console.log(` ${phase}: ${section}.${method}:: ${data}`);138 // console.log(` ${phase}: ${section}.${method}:: ${data}`);147 if (method == 'ExtrinsicSuccess') {139 if (method == 'ExtrinsicSuccess') {148 success = true;140 success = true;159151160export function getCreateItemResult(events: EventRecord[]): CreateItemResult {152export function getCreateItemResult(events: EventRecord[]): CreateItemResult {161 let success = false;153 let success = false;162 let collectionId: number = 0;154 let collectionId = 0;163 let itemId: number = 0;155 let itemId = 0;164 let recipient;156 let recipient;165 events.forEach(({ phase, event: { data, method, section } }) => {157 events.forEach(({ event: { data, method, section } }) => {166 // console.log(` ${phase}: ${section}.${method}:: ${data}`);158 // console.log(` ${phase}: ${section}.${method}:: ${data}`);167 if (method == 'ExtrinsicSuccess') {159 if (method == 'ExtrinsicSuccess') {168 success = true;160 success = true;235 mode: { type: 'NFT' },227 mode: { type: 'NFT' },236 name: 'name',228 name: 'name',237 tokenPrefix: 'prefix',229 tokenPrefix: 'prefix',238}230};239231240export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {232export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {241 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };233 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };242234243 let collectionId: number = 0;235 let collectionId = 0;244 await usingApi(async (api) => {236 await usingApi(async (api) => {245 // Get number of collections before the transaction237 // Get number of collections before the transaction246 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);238 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);351}343}352344353function getDestroyResult(events: EventRecord[]): boolean {345function getDestroyResult(events: EventRecord[]): boolean {354 let success: boolean = false;346 let success = false;355 events.forEach(({ phase, event: { data, method, section } }) => {347 events.forEach(({ event: { method } }) => {356 // console.log(` ${phase}: ${section}.${method}:: ${data}`);357 if (method == 'ExtrinsicSuccess') {348 if (method == 'ExtrinsicSuccess') {358 success = true;349 success = true;359 }350 }360 });351 });361 return success;352 return success;362}353}363354364export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {355export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {365 await usingApi(async (api) => {356 await usingApi(async (api) => {366 // Run the DestroyCollection transaction357 // Run the DestroyCollection transaction367 const alicePrivateKey = privateKey(senderSeed);358 const alicePrivateKey = privateKey(senderSeed);370 });361 });371}362}372363373export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {364export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {374 await usingApi(async (api) => {365 await usingApi(async (api) => {375 // Run the DestroyCollection transaction366 // Run the DestroyCollection transaction376 const alicePrivateKey = privateKey(senderSeed);367 const alicePrivateKey = privateKey(senderSeed);465 });456 });466}457}467458468export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {459export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {469 await usingApi(async (api) => {460 await usingApi(async (api) => {470461471 // Run the transaction462 // Run the transaction475 });466 });476}467}477468478export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {469export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {479 await usingApi(async (api) => {470 await usingApi(async (api) => {480471481 // Run the transaction472 // Run the transaction496}487}497488498489499export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {490export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {500 await usingApi(async (api) => {491 await usingApi(async (api) => {501492502 // Run the transaction493 // Run the transaction546 });537 });547}538}548539549export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {540export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string) {550 await usingApi(async (api) => {541 await usingApi(async (api) => {551 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);542 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);552 const events = await submitTransactionAsync(sender, tx);543 const events = await submitTransactionAsync(sender, tx);557}548}558549559export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {550export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {560 let whitelisted: boolean = false;551 let whitelisted = false;561 await usingApi(async (api) => {552 await usingApi(async (api) => {562 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;553 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;563 });554 });683 accountFrom: IKeyringPair | CrossAccountId,677 accountFrom: IKeyringPair | CrossAccountId,684 accountTo: IKeyringPair | CrossAccountId,678 accountTo: IKeyringPair | CrossAccountId,685 value: number | bigint = 1,679 value: number | bigint = 1,686 type: string = 'NFT') {680 type = 'NFT',681) {687 await usingApi(async (api: ApiPromise) => {682 await usingApi(async (api: ApiPromise) => {688 const to = normalizeAccountId(accountTo);683 const to = normalizeAccountId(accountTo);730 });725 });731}726}732727728/* eslint no-async-promise-executor: "off" */733async function getBlockNumber(api: ApiPromise): Promise<number> {729async function getBlockNumber(api: ApiPromise): Promise<number> {734 return new Promise<number>(async (resolve, reject) => {730 return new Promise<number>(async (resolve) => {735 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {731 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {736 unsubscribe();732 unsubscribe();737 resolve(head.number.toNumber());733 resolve(head.number.toNumber());745 sender: IKeyringPair,742 sender: IKeyringPair,746 recipient: IKeyringPair,743 recipient: IKeyringPair,747 value: number | bigint = 1,744 value: number | bigint = 1,748 type: string = 'NFT') {745) {749 await usingApi(async (api: ApiPromise) => {746 await usingApi(async (api: ApiPromise) => {750 let balanceBefore = new BN(0);751752753 let blockNumber: number | undefined = await getBlockNumber(api);747 const blockNumber: number | undefined = await getBlockNumber(api);754 let expectedBlockNumber = blockNumber + 2;748 const expectedBlockNumber = blockNumber + 2;755749756 expect(blockNumber).to.be.greaterThan(0);750 expect(blockNumber).to.be.greaterThan(0);757 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 751 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 758 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);752 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);759753760 const events = await submitTransactionAsync(sender, scheduleTx);754 await submitTransactionAsync(sender, scheduleTx);761755762 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());763 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());756 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());764757765 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;758 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;768 // sleep for 2 blocks761 // sleep for 2 blocks769 await new Promise(resolve => setTimeout(resolve, 6000 * 2));762 await new Promise(resolve => setTimeout(resolve, 6000 * 2));770763771 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());772 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());764 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());773765774 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;766 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;784 sender: IKeyringPair,777 sender: IKeyringPair,785 recipient: IKeyringPair | CrossAccountId,778 recipient: IKeyringPair | CrossAccountId,786 value: number | bigint = 1,779 value: number | bigint = 1,787 type: string = 'NFT') {780 type = 'NFT',781) {788 await usingApi(async (api: ApiPromise) => {782 await usingApi(async (api: ApiPromise) => {789 const to = normalizeAccountId(recipient);783 const to = normalizeAccountId(recipient);825 sender: IKeyringPair,820 sender: IKeyringPair,826 recipient: IKeyringPair,821 recipient: IKeyringPair,827 value: number | bigint = 1,822 value: number | bigint = 1,828 type: string = 'NFT') {823) {829 await usingApi(async (api: ApiPromise) => {824 await usingApi(async (api: ApiPromise) => {830 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);825 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);831 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;826 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;878875879export async function createItemExpectSuccess(876export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {880 sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {881 let newItemId: number = 0;877 let newItemId = 0;882 await usingApi(async (api) => {878 await usingApi(async (api) => {883 const to = normalizeAccountId(owner);879 const to = normalizeAccountId(owner);884 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);880 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);994}989}995990996export async function isWhitelisted(collectionId: number, address: string) {991export async function isWhitelisted(collectionId: number, address: string) {997 let whitelisted: boolean = false;992 let whitelisted = false;998 await usingApi(async (api) => {993 await usingApi(async (api) => {999 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;994 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1000 });995 });tests/src/util/util.tsdiffbeforeafterboth4//4//556export function strToUTF16(str: string): any {6export function strToUTF16(str: string): any {7 let buf: number[] = [];7 const buf: number[] = [];8 for (let i=0, strLen=str.length; i < strLen; i++) {8 for (let i=0, strLen=str.length; i < strLen; i++) {9 buf.push(str.charCodeAt(i));9 buf.push(str.charCodeAt(i));10 }10 }11 return buf;11 return buf;12}12}131314export function utf16ToStr(buf: number[]): string {14export function utf16ToStr(buf: number[]): string {15 let str: string = "";15 let str = '';16 for (let i=0, strLen=buf.length; i < strLen; i++) {16 for (let i=0, strLen=buf.length; i < strLen; i++) {17 if (buf[i] != 0) str += String.fromCharCode(buf[i]);17 if (buf[i] != 0) str += String.fromCharCode(buf[i]);18 else break;18 else break;21}21}222223export function hexToStr(buf: string): string {23export function hexToStr(buf: string): string {24 let str: string = "";24 let str = '';25 let hexStart = buf.indexOf("0x");25 let hexStart = buf.indexOf('0x');26 if (hexStart < 0) hexStart = 0;26 if (hexStart < 0) hexStart = 0;27 else hexStart = 2; 27 else hexStart = 2; 28 for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {28 for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {29 let ch = buf[i] + buf[i+1];29 const ch = buf[i] + buf[i+1];30 let num = parseInt(ch, 16);30 const num = parseInt(ch, 16);31 if (num != 0) str += String.fromCharCode(num);31 if (num != 0) str += String.fromCharCode(num);32 else break;32 else break;33 }33 }