difftreelog
Merge branch 'develop' into feature/NFTPAR-243_enableContractSponsoring
in: master
12 files changed
.devcontainer/Dockerfilediffbeforeafterboth--- /dev/null
+++ b/.devcontainer/Dockerfile
@@ -0,0 +1,14 @@
+FROM mcr.microsoft.com/vscode/devcontainers/rust:0-1
+
+RUN apt-get update && export DEBIAN_FRONTEND=noninteractive && \
+ apt-get -y install --no-install-recommends libssl-dev pkg-config libclang-dev clang
+
+USER vscode
+
+RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash && \
+ export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" && \
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+ nvm install v12.20.1 && \
+ rustup toolchain install nightly-2020-10-01 && \
+ rustup default nightly-2020-10-01 && \
+ rustup target add wasm32-unknown-unknown
\ No newline at end of file
.devcontainer/devcontainer.jsondiffbeforeafterboth--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,18 @@
+{
+ "name": "Rust",
+ "build": {
+ "dockerfile": "Dockerfile"
+ },
+ "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ],
+ "settings": {
+ "terminal.integrated.shell.linux": "/bin/bash",
+ "lldb.executable": "/usr/bin/lldb",
+ "files.watcherExclude": {
+ "**/target/**": true
+ }
+ },
+ "extensions": [
+ "matklad.rust-analyzer"
+ ],
+ "remoteUser": "vscode"
+}
README.mddiffbeforeafterboth--- a/README.md
+++ b/README.md
@@ -56,7 +56,7 @@
```bash
rustup toolchain install 1.49.0
-rustup toolchain install nightly-2020-10-01
+rustup toolchain install nightly-2020-01-27
rustup default nightly-2021-01-27
```
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -1122,8 +1122,8 @@
// Check approval
let mut approval: u128 = 0;
- if <Allowances<T>>::contains_key(collection_id, (item_id, &from, &recipient)) {
- approval = <Allowances<T>>::get(collection_id, (item_id, &from, &recipient));
+ if <Allowances<T>>::contains_key(collection_id, (item_id, &from, &sender)) {
+ approval = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));
ensure!(approval >= value, Error::<T>::TokenValueNotEnough);
appoved_transfer = true;
}
@@ -1144,10 +1144,10 @@
// Reduce approval by transferred amount or remove if remaining approval drops to 0
if approval.checked_sub(value).unwrap_or(0) > 0 {
- <Allowances<T>>::insert(collection_id, (item_id, &from, &recipient), approval - value);
+ <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);
}
else {
- <Allowances<T>>::remove(collection_id, (item_id, &from, &recipient));
+ <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));
}
match target_collection.mode
tests/README.mddiffbeforeafterboth--- a/tests/README.md
+++ b/tests/README.md
@@ -2,8 +2,8 @@
## How to run
-1. Run `npm install`.
+1. Run `yarn install`.
2. Setup a test node. You can do it using `docker-compose up -d` in parent directory.
3. Optional step - configure tests with env variables or by editing [configuration file](src/config.ts).
-4. Run `npm test`.
+4. Run `yarn test`.
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -25,8 +25,10 @@
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+ "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
+ "testCreateMultipleItems": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItems.test.ts",
"testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
"testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",
"testCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
@@ -35,7 +37,8 @@
"testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",
"testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",
"testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.test.ts",
- "testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts"
+ "testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",
+ "testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts"
},
"author": "",
"license": "SEE LICENSE IN ../LICENSE",
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -2,68 +2,177 @@
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
//
+import { ApiPromise } from '@polkadot/api';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ destroyCollectionExpectSuccess,
+ IReFungibleTokenDataType,
+} from './util/helpers';
-import { assert } from 'chai';
-import { alicesPublicKey } from './accounts';
-import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
-import waitNewBlocks from './substrate/wait-new-blocks';
+chai.use(chaiAsPromised);
+const expect = chai.expect;
-const idCollection = 12;
+interface ITokenDataType {
+ Owner: number[];
+ ConstData: number[];
+ VariableData: number[];
+}
-describe.skip('integration test: ext. createMultipleItems():', () => {
- it('Create two NFT tokens in active NFT collection', async () => {
- await usingApi(async (api) => {
- const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (before): ${AitemListIndex}`);
- const args = ['NFT', 'NFT'];
- const alicePrivateKey = privateKey('//Alice');
- const createMultipleItems = await api.tx.nft
- .createMultipleItems(idCollection, alicesPublicKey, args)
- .signAndSend(alicePrivateKey);
- // tslint:disable-next-line: no-unused-expression
- assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
- console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
- await waitNewBlocks(api);
- const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (after): ${BitemListIndex}`);
- if (BitemListIndex === AitemListIndex) { assert.fail('Corret token not added in collection!'); }
+describe('Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
+ it('Create 0x31, 0x32, 0x33 items in active NFT collection and verify tokens data in chain', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemsListIndexBefore = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+ const Alice = privateKey('//Alice');
+ const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, args);
+ await submitTransactionAsync(Alice, createMultipleItemsTx);
+ const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
+ const token1Data = await api.query.nft.nftItemList(collectionId, 1) as unknown as ITokenDataType;
+ const token2Data = await api.query.nft.nftItemList(collectionId, 2) as unknown as ITokenDataType;
+ const token3Data = await api.query.nft.nftItemList(collectionId, 3) as unknown as ITokenDataType;
+
+ expect(token1Data.Owner.toString()).to.be.equal(Alice.address);
+ expect(token2Data.Owner.toString()).to.be.equal(Alice.address);
+ expect(token3Data.Owner.toString()).to.be.equal(Alice.address);
+
+ expect(token1Data.ConstData.toString()).to.be.equal('0x31');
+ expect(token2Data.ConstData.toString()).to.be.equal('0x32');
+ expect(token3Data.ConstData.toString()).to.be.equal('0x33');
+
+ expect(token1Data.VariableData.toString()).to.be.equal('0x31');
+ expect(token2Data.VariableData.toString()).to.be.equal('0x32');
+ expect(token3Data.VariableData.toString()).to.be.equal('0x33');
});
});
- it('(!negative test!) Create two Fungible tokens in active NFT collection', async () => {
- await usingApi(async (api) => {
- const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (before): ${AitemListIndex}`);
- const args = ['Fungible', 'Fungible'];
- const alicePrivateKey = privateKey('//Alice');
- const createMultipleItems = await api.tx.nft
- .createMultipleItems(idCollection, alicesPublicKey, args)
- .signAndSend(alicePrivateKey);
- // tslint:disable-next-line: no-unused-expression
- assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
- console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
- await waitNewBlocks(api);
- const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (after): ${BitemListIndex}`);
- if (BitemListIndex > AitemListIndex) { assert.fail('Incorrect token added in collection!'); }
+
+ it('Create 0x31, 0x32, 0x33 items in active ReFungible collection and verify tokens data in chain', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+ const itemsListIndexBefore = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+ const Alice = privateKey('//Alice');
+ const args = [
+ { Refungible: ['0x31', '0x31'] },
+ { Refungible: ['0x32', '0x32'] },
+ { Refungible: ['0x33', '0x33'] },
+ ];
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, args);
+ await submitTransactionAsync(Alice, createMultipleItemsTx);
+ const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
+ const token1Data = await api.query.nft.reFungibleItemList(collectionId, 1) as unknown as IReFungibleTokenDataType;
+ const token2Data = await api.query.nft.reFungibleItemList(collectionId, 2) as unknown as IReFungibleTokenDataType;
+ const token3Data = await api.query.nft.reFungibleItemList(collectionId, 3) as unknown as IReFungibleTokenDataType;
+
+ expect(token1Data.Owner[0].Owner.toString()).to.be.equal(Alice.address);
+ expect(token1Data.Owner[0].Fraction.toNumber()).to.be.equal(1);
+
+ expect(token2Data.Owner[0].Owner.toString()).to.be.equal(Alice.address);
+ expect(token2Data.Owner[0].Fraction.toNumber()).to.be.equal(1);
+
+ expect(token3Data.Owner[0].Owner.toString()).to.be.equal(Alice.address);
+ expect(token3Data.Owner[0].Fraction.toNumber()).to.be.equal(1);
+
+ expect(token1Data.ConstData.toString()).to.be.equal('0x31');
+ expect(token2Data.ConstData.toString()).to.be.equal('0x32');
+ expect(token3Data.ConstData.toString()).to.be.equal('0x33');
+
+ expect(token1Data.VariableData.toString()).to.be.equal('0x31');
+ expect(token2Data.VariableData.toString()).to.be.equal('0x32');
+ expect(token3Data.VariableData.toString()).to.be.equal('0x33');
});
});
- it('(!negative test!) Create two ReFungible tokens in active NFT collection', async () => {
- await usingApi(async (api) => {
- const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (before): ${AitemListIndex}`);
- const args = ['ReFungible', 'ReFungible'];
- const alicePrivateKey = privateKey('//Alice');
- const createMultipleItems = await api.tx.nft
- .createMultipleItems(idCollection, alicesPublicKey, args)
- .signAndSend(alicePrivateKey);
- // tslint:disable-next-line: no-unused-expression
- assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
- console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
- await waitNewBlocks(api);
- const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
- console.log(`itemListIndex count (after): ${BitemListIndex}`);
- if (BitemListIndex > AitemListIndex) { assert.fail('Incorrect token added in collection!'); }
+});
+
+describe('Negative Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
+ it('Create token with not existing type', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ try {
+ const args = [{ invalid: null }, { invalid: null }, { invalid: null }];
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, args);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
+ } catch (e) {
+ // tslint:disable-next-line:no-unused-expression
+ expect(e).to.be.exist;
+ }
+ });
+ });
+
+ it('Create token in not existing collection', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
+ const Alice = privateKey('//Alice');
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, ['NFT', 'NFT', 'NFT']);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
+ });
+ });
+
+ it('Create NFT and Re-fungible tokens that has reached the maximum data limit', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ // NFT
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ const args = [
+ { nft: ['A'.repeat(2049), 'A'.repeat(2049)] },
+ { nft: ['B'.repeat(2049), 'B'.repeat(2049)] },
+ { nft: ['C'.repeat(2049), 'C'.repeat(2049)] },
+ ];
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, args);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
+
+ // ReFungible
+ const collectionIdReFungible =
+ await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+ const argsReFungible = [
+ { ReFungible: ['1'.repeat(2049), '1'.repeat(2049)] },
+ { ReFungible: ['2'.repeat(2049), '2'.repeat(2049)] },
+ { ReFungible: ['3'.repeat(2049), '3'.repeat(2049)] },
+ ];
+ const createMultipleItemsTxFungible = await api.tx.nft
+ .createMultipleItems(collectionIdReFungible, Alice.address, argsReFungible);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTxFungible)).to.be.rejected;
+ });
+ });
+
+ it('Create tokens with different types', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, ['NFT', 'Fungible', 'ReFungible']);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
+ // garbage collection :-D
+ await destroyCollectionExpectSuccess(collectionId);
+ });
+ });
+
+ it('Create tokens with different data limits <> maximum data limit', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ const args = [
+ { nft: ['A', 'A'] },
+ { nft: ['B', 'B'.repeat(2049)] },
+ { nft: ['C'.repeat(2049), 'C'] },
+ ];
+ const createMultipleItemsTx = await api.tx.nft
+ .createMultipleItems(collectionId, Alice.address, args);
+ await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
});
});
});
tests/src/removeFromWhiteList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/removeFromWhiteList.test.ts
@@ -0,0 +1,84 @@
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from './substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ destroyCollectionExpectSuccess,
+ enableWhiteListExpectSuccess,
+ addToWhiteListExpectSuccess,
+ removeFromWhiteListExpectSuccess,
+ isWhitelisted,
+ findNotExistingCollection,
+ removeFromWhiteListExpectFailure,
+ disableWhiteListExpectSuccess,
+} from './util/helpers';
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Integration Test removeFromWhiteList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api) => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('ensure bob is not in whitelist after removal', async () => {
+ await usingApi(async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+ await enableWhiteListExpectSuccess(alice, collectionId);
+ await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+
+ await removeFromWhiteListExpectSuccess(alice, collectionId, bob.address);
+ expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+ });
+ });
+
+ it('allows removal from collection with unset whitelist status', async () => {
+ await usingApi(async () => {
+ const collectionWithoutWhitelistId = await createCollectionExpectSuccess();
+ await enableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
+ await addToWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, bob.address);
+ await disableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
+
+ await removeFromWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, bob.address);
+ });
+ });
+});
+
+describe('Negative Integration Test removeFromWhiteList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api) => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('fails on removal from not existing collection', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await findNotExistingCollection(api);
+
+ await removeFromWhiteListExpectFailure(alice, collectionId, bob.address);
+ });
+ });
+
+ it('fails on removal from removed collection', async () => {
+ await usingApi(async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableWhiteListExpectSuccess(alice, collectionId);
+ await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await destroyCollectionExpectSuccess(collectionId);
+
+ await removeFromWhiteListExpectFailure(alice, collectionId, bob.address);
+ });
+ });
+});
tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/setContractSponsoringRateLimit.test.ts
@@ -0,0 +1,62 @@
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import waitNewBlocks from './substrate/wait-new-blocks';
+import { deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess } from './util/contracthelpers';
+import {
+ enableContractSponsoringExpectSuccess,
+ findUnusedAddress,
+ setContractSponsoringRateLimitExpectFailure,
+ setContractSponsoringRateLimitExpectSuccess,
+} from './util/helpers';
+
+describe('Integration Test setContractSponsoringRateLimit', () => {
+ it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
+ await usingApi(async (api) => {
+ const user = await findUnusedAddress(api);
+
+ const [flipper, deployer] = await deployFlipper(api);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 10);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ await toggleFlipValueExpectFailure(user, flipper);
+ });
+ });
+
+ it('ensure sponsored contract can be called twice with pause for free', async () => {
+ await usingApi(async (api) => {
+ const user = await findUnusedAddress(api);
+
+ const [flipper, deployer] = await deployFlipper(api);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ await waitNewBlocks(api, 1);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ });
+ });
+});
+
+describe('Negative Integration Test setContractSponsoringRateLimit', () => {
+ let alice: IKeyringPair;
+
+ before(async () => {
+ alice = privateKey('//Alice');
+ });
+
+ it('fails when called for non-contract address', async () => {
+ await usingApi(async (api) => {
+ const user = await findUnusedAddress(api);
+
+ await setContractSponsoringRateLimitExpectFailure(alice, user.address, 1);
+ });
+ });
+
+ it('fails when called by non-owning user', async () => {
+ await usingApi(async (api) => {
+ const [flipper, _] = await deployFlipper(api);
+
+ await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);
+ });
+ });
+});
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -123,9 +123,9 @@
// console.log('transactionStatus', transactionStatus, 'events', events);
- if (transactionStatus == TransactionStatus.Success) {
+ if (transactionStatus === TransactionStatus.Success) {
resolve(events);
- } else if (transactionStatus == TransactionStatus.Fail) {
+ } else if (transactionStatus === TransactionStatus.Fail) {
reject(events);
}
});
tests/src/util/contracthelpers.tsdiffbeforeafterboth--- a/tests/src/util/contracthelpers.ts
+++ b/tests/src/util/contracthelpers.ts
@@ -5,7 +5,7 @@
import chai from "chai";
import chaiAsPromised from 'chai-as-promised';
-import { submitTransactionAsync } from "../substrate/substrate-api";
+import { submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";
import fs from "fs";
import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";
import { IKeyringPair } from "@polkadot/types/types";
@@ -100,6 +100,11 @@
expect(result.success).to.be.true;
}
+export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
+ const tx = contract.tx.flip(value, gasLimit);
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+}
+
function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {
return new Promise<any>(async (resolve, reject) => {
const unsub = await blueprint.tx
tests/src/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//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25 success: boolean,26};2728interface CreateCollectionResult {29 success: boolean;30 collectionId: number;31}3233interface CreateItemResult {34 success: boolean;35 collectionId: number;36 itemId: number;37}3839interface IReFungibleOwner {40 Fraction: BN;41 Owner: number[];42}4344interface ITokenDataType {45 Owner: number[];46 ConstData: number[];47 VariableData: number[];48}4950interface IFungibleTokenDataType {51 Value: BN;52}5354interface IReFungibleTokenDataType {55 Owner: IReFungibleOwner[];56 ConstData: number[];57 VariableData: number[];58}5960export function getGenericResult(events: EventRecord[]): GenericResult {61 const result: GenericResult = {62 success: false,63 };64 events.forEach(({ phase, event: { data, method, section } }) => {65 // console.log(` ${phase}: ${section}.${method}:: ${data}`);66 if (method === 'ExtrinsicSuccess') {67 result.success = true;68 }69 });70 return result;71}7273export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {74 let success = false;75 let collectionId: number = 0;76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method == 'ExtrinsicSuccess') {79 success = true;80 } else if ((section == 'nft') && (method == 'Created')) {81 collectionId = parseInt(data[0].toString());82 }83 });84 const result: CreateCollectionResult = {85 success,86 collectionId,87 };88 return result;89}9091export function getCreateItemResult(events: EventRecord[]): CreateItemResult {92 let success = false;93 let collectionId: number = 0;94 let itemId: number = 0;95 events.forEach(({ phase, event: { data, method, section } }) => {96 // console.log(` ${phase}: ${section}.${method}:: ${data}`);97 if (method == 'ExtrinsicSuccess') {98 success = true;99 } else if ((section == 'nft') && (method == 'ItemCreated')) {100 collectionId = parseInt(data[0].toString());101 itemId = parseInt(data[1].toString());102 }103 });104 const result: CreateItemResult = {105 success,106 collectionId,107 itemId,108 };109 return result;110}111112interface Invalid {113 type: 'Invalid';114}115116interface Nft {117 type: 'NFT';118}119120interface Fungible {121 type: 'Fungible';122 decimalPoints: number;123}124125interface ReFungible {126 type: 'ReFungible';127 decimalPoints: number;128}129130interface Nft {131 type: 'NFT'132}133134interface Fungible {135 type: 'Fungible',136 decimalPoints: number137}138139interface ReFungible {140 type: 'ReFungible',141 decimalPoints: number142}143144type CollectionMode = Nft | Fungible | ReFungible | Invalid;145146export type CreateCollectionParams = {147 mode: CollectionMode,148 name: string,149 description: string,150 tokenPrefix: string,151};152153const defaultCreateCollectionParams: CreateCollectionParams = {154 description: 'description',155 mode: { type: 'NFT' },156 name: 'name',157 tokenPrefix: 'prefix',158}159160export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {161 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};162163 let collectionId: number = 0;164 await usingApi(async (api) => {165 // Get number of collections before the transaction166 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168 // Run the CreateCollection transaction169 const alicePrivateKey = privateKey('//Alice');170171 let modeprm = {};172 if (mode.type === 'NFT') {173 modeprm = {nft: null};174 } else if (mode.type === 'Fungible') {175 modeprm = {fungible: mode.decimalPoints};176 } else if (mode.type === 'ReFungible') {177 modeprm = {refungible: mode.decimalPoints};178 } else if (mode.type === 'Invalid') {179 modeprm = {invalid: null};180 }181182 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);183 const events = await submitTransactionAsync(alicePrivateKey, tx);184 const result = getCreateCollectionResult(events);185186 // Get number of collections after the transaction187 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189 // Get the collection190 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192 // What to expect193 // tslint:disable-next-line:no-unused-expression194 expect(result.success).to.be.true;195 expect(result.collectionId).to.be.equal(BcollectionCount);196 // tslint:disable-next-line:no-unused-expression197 expect(collection).to.be.not.null;198 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');199 expect(collection.Owner).to.be.equal(alicesPublicKey);200 expect(utf16ToStr(collection.Name)).to.be.equal(name);201 expect(utf16ToStr(collection.Description)).to.be.equal(description);202 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);203204 collectionId = result.collectionId;205 });206207 return collectionId;208}209210export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {211 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};212213 let modeprm = {};214 if (mode.type === 'NFT') {215 modeprm = {nft: null};216 } else if (mode.type === 'Fungible') {217 modeprm = {fungible: mode.decimalPoints};218 } else if (mode.type === 'ReFungible') {219 modeprm = {refungible: mode.decimalPoints};220 } else if (mode.type === 'Invalid') {221 modeprm = {invalid: null};222 }223224 await usingApi(async (api) => {225 // Get number of collections before the transaction226 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228 // Run the CreateCollection transaction229 const alicePrivateKey = privateKey('//Alice');230 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);231 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;232 const result = getCreateCollectionResult(events);233234 // Get number of collections after the transaction235 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237 // What to expect238 // tslint:disable-next-line:no-unused-expression239 expect(result.success).to.be.false;240 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');241 });242}243244export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {245 let bal = new BigNumber(0);246 let unused;247 do {248 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));249 const keyring = new Keyring({ type: 'sr25519' });250 unused = keyring.addFromUri(`//${randomSeed}`);251 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());252 } while (bal.toFixed() != '0');253 return unused;254}255256export async function findNotExistingCollection(api: ApiPromise): Promise<number> {257 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;258 const newCollection: number = totalNumber + 1;259 return newCollection;260}261262function getDestroyResult(events: EventRecord[]): boolean {263 let success: boolean = false;264 events.forEach(({ phase, event: { data, method, section } }) => {265 // console.log(` ${phase}: ${section}.${method}:: ${data}`);266 if (method == 'ExtrinsicSuccess') {267 success = true;268 }269 });270 return success;271}272273export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {274 await usingApi(async (api) => {275 // Run the DestroyCollection transaction276 const alicePrivateKey = privateKey(senderSeed);277 const tx = api.tx.nft.destroyCollection(collectionId);278 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;279 });280}281282export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {283 await usingApi(async (api) => {284 // Run the DestroyCollection transaction285 const alicePrivateKey = privateKey(senderSeed);286 const tx = api.tx.nft.destroyCollection(collectionId);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getDestroyResult(events);289290 // Get the collection291 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();292293 // What to expect294 expect(result).to.be.true;295 expect(collection).to.be.not.null;296 expect(collection.Owner).to.be.equal(nullPublicKey);297 });298}299300export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {301 await usingApi(async (api) => {302303 // Run the transaction304 const alicePrivateKey = privateKey('//Alice');305 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);306 const events = await submitTransactionAsync(alicePrivateKey, tx);307 const result = getGenericResult(events);308309 // Get the collection310 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();311312 // What to expect313 expect(result.success).to.be.true;314 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());315 expect(collection.SponsorConfirmed).to.be.false;316 });317}318319export async function removeCollectionSponsorExpectSuccess(collectionId: number) {320 await usingApi(async (api) => {321322 // Run the transaction323 const alicePrivateKey = privateKey('//Alice');324 const tx = api.tx.nft.removeCollectionSponsor(collectionId);325 const events = await submitTransactionAsync(alicePrivateKey, tx);326 const result = getGenericResult(events);327328 // Get the collection329 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();330331 // What to expect332 expect(result.success).to.be.true;333 expect(collection.Sponsor).to.be.equal(nullPublicKey);334 expect(collection.SponsorConfirmed).to.be.false;335 });336}337338export async function removeCollectionSponsorExpectFailure(collectionId: number) {339 await usingApi(async (api) => {340341 // Run the transaction342 const alicePrivateKey = privateKey('//Alice');343 const tx = api.tx.nft.removeCollectionSponsor(collectionId);344 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;345 });346}347348export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {349 await usingApi(async (api) => {350351 // Run the transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);354 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;355 });356}357358export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {359 await usingApi(async (api) => {360361 // Run the transaction362 const sender = privateKey(senderSeed);363 const tx = api.tx.nft.confirmSponsorship(collectionId);364 const events = await submitTransactionAsync(sender, tx);365 const result = getGenericResult(events);366367 // Get the collection368 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();369370 // What to expect371 expect(result.success).to.be.true;372 expect(collection.Sponsor).to.be.equal(sender.address);373 expect(collection.SponsorConfirmed).to.be.true;374 });375}376377export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {378 await usingApi(async (api) => {379380 // Run the transaction381 const sender = privateKey(senderSeed);382 const tx = api.tx.nft.confirmSponsorship(collectionId);383 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;384 });385}386387export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {388 await usingApi(async (api) => {389 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);390 const events = await submitTransactionAsync(sender, tx);391 const result = getGenericResult(events);392393 expect(result.success).to.be.true;394 });395}396397export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {398 await usingApi(async (api) => {399 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);400 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;401 const result = getGenericResult(events);402403 expect(result.success).to.be.false;404 });405}406407export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {408 await usingApi(async (api) => {409 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);410 const events = await submitTransactionAsync(sender, tx);411 const result = getGenericResult(events);412413 expect(result.success).to.be.true;414 });415}416417export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {418 await usingApi(async (api) => {419 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));420 const events = await submitTransactionAsync(sender, tx);421 const result = getGenericResult(events);422423 expect(result.success).to.be.true;424 });425}426427export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {428 await usingApi(async (api) => {429 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));430 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;431 });432}433434export interface CreateFungibleData extends Struct {435 readonly value: u128;436}437438export interface CreateReFungibleData extends Struct {}439export interface CreateNftData extends Struct {}440441export interface CreateItemData extends Enum {442 NFT: CreateNftData;443 Fungible: CreateFungibleData;444 ReFungible: CreateReFungibleData;445}446447export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {448 await usingApi(async (api) => {449 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);450 const events = await submitTransactionAsync(owner, tx);451 const result = getGenericResult(events);452 // Get the item453 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();454 // What to expect455 // tslint:disable-next-line:no-unused-expression456 expect(result.success).to.be.true;457 // tslint:disable-next-line:no-unused-expression458 expect(item).to.be.not.null;459 expect(item.Owner).to.be.equal(nullPublicKey);460 });461}462463export async function464approveExpectSuccess(collectionId: number,465 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {466 await usingApi(async (api: ApiPromise) => {467 const allowanceBefore =468 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;469 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);470 const events = await submitTransactionAsync(owner, approveNftTx);471 const result = getCreateItemResult(events);472 // tslint:disable-next-line:no-unused-expression473 expect(result.success).to.be.true;474 const allowanceAfter =475 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;476 expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);477 });478}479480export async function481transferFromExpectSuccess(collectionId: number,482 tokenId: number,483 accountApproved: IKeyringPair,484 accountFrom: IKeyringPair,485 accountTo: IKeyringPair,486 value: number = 1,487 type: string = 'NFT') {488 await usingApi(async (api: ApiPromise) => {489 let balanceBefore = new BN(0);490 if (type === 'Fungible') {491 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;492 }493 const transferFromTx = await api.tx.nft.transferFrom(494 accountFrom.address, accountTo.address, collectionId, tokenId, value);495 const events = await submitTransactionAsync(accountFrom, transferFromTx);496 const result = getCreateItemResult(events);497 // tslint:disable-next-line:no-unused-expression498 expect(result.success).to.be.true;499 if (type === 'NFT') {500 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;501 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);502 }503 if (type === 'Fungible') {504 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;505 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);506 }507 if (type === 'ReFungible') {508 const nftItemData =509 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;510 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);511 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);512 }513 });514}515516export async function517transferFromExpectFail(collectionId: number,518 tokenId: number,519 accountApproved: IKeyringPair,520 accountFrom: IKeyringPair,521 accountTo: IKeyringPair,522 value: number = 1) {523 await usingApi(async (api: ApiPromise) => {524 const transferFromTx = await api.tx.nft.transferFrom(525 accountFrom.address, accountTo.address, collectionId, tokenId, value);526 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;527 const result = getCreateCollectionResult(events);528 // tslint:disable-next-line:no-unused-expression529 expect(result.success).to.be.false;530 });531}532533export async function534transferExpectSuccess(collectionId: number,535 tokenId: number,536 sender: IKeyringPair,537 recipient: IKeyringPair,538 value: number = 1,539 type: string = 'NFT') {540 await usingApi(async (api: ApiPromise) => {541 let balanceBefore = new BN(0);542 if (type === 'Fungible') {543 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;544 }545 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);546 const events = await submitTransactionAsync(sender, transferTx);547 const result = getCreateItemResult(events);548 // tslint:disable-next-line:no-unused-expression549 expect(result.success).to.be.true;550 if (type === 'NFT') {551 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;552 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);553 }554 if (type === 'Fungible') {555 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;556 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);557 }558 if (type === 'ReFungible') {559 const nftItemData =560 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;561 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);562 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);563 }564 });565}566567export async function568transferExpectFail(collectionId: number,569 tokenId: number,570 sender: IKeyringPair,571 recipient: IKeyringPair,572 value: number = 1,573 type: string = 'NFT') {574 await usingApi(async (api: ApiPromise) => {575 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);576 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;577 if (events && Array.isArray(events)) {578 const result = getCreateCollectionResult(events);579 // tslint:disable-next-line:no-unused-expression580 expect(result.success).to.be.false;581 }582 });583}584585export async function586approveExpectFail(collectionId: number,587 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {588 await usingApi(async (api: ApiPromise) => {589 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);590 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;591 const result = getCreateCollectionResult(events);592 // tslint:disable-next-line:no-unused-expression593 expect(result.success).to.be.false;594 });595}596597export async function createItemExpectSuccess(598 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {599 let newItemId: number = 0;600 await usingApi(async (api) => {601 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);602 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();603 const AItemBalance = new BigNumber(Aitem.Value);604605 if (owner === '') {606 owner = sender.address;607 }608609 let tx;610 if (createMode === 'Fungible') {611 const createData = {fungible: {value: 10}};612 tx = api.tx.nft.createItem(collectionId, owner, createData);613 } else {614 tx = api.tx.nft.createItem(collectionId, owner, createMode);615 }616 const events = await submitTransactionAsync(sender, tx);617 const result = getCreateItemResult(events);618619 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);620 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();621 const BItemBalance = new BigNumber(Bitem.Value);622623 // What to expect624 // tslint:disable-next-line:no-unused-expression625 expect(result.success).to.be.true;626 if (createMode === 'Fungible') {627 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);628 } else {629 expect(BItemCount).to.be.equal(AItemCount + 1);630 }631 expect(collectionId).to.be.equal(result.collectionId);632 expect(BItemCount).to.be.equal(result.itemId);633 newItemId = result.itemId;634 });635 return newItemId;636}637638export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {639 await usingApi(async (api) => {640641 // Run the transaction642 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');643 const events = await submitTransactionAsync(sender, tx);644 const result = getGenericResult(events);645646 // Get the collection647 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();648649 // What to expect650 // tslint:disable-next-line:no-unused-expression651 expect(result.success).to.be.true;652 expect(collection.Access).to.be.equal('WhiteList');653 });654}655656export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {657 await usingApi(async (api) => {658659 // Run the transaction660 const tx = api.tx.nft.setMintPermission(collectionId, true);661 const events = await submitTransactionAsync(sender, tx);662 const result = getGenericResult(events);663664 // Get the collection665 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();666667 // What to expect668 expect(result.success).to.be.true;669 expect(collection.MintMode).to.be.equal(true);670 });671}672673export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {674 await usingApi(async (api) => {675676 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();677678 // Run the transaction679 const tx = api.tx.nft.addToWhiteList(collectionId, address);680 const events = await submitTransactionAsync(sender, tx);681 const result = getGenericResult(events);682683 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();684685 // What to expect686 // tslint:disable-next-line:no-unused-expression687 expect(result.success).to.be.true;688 // tslint:disable-next-line: no-unused-expression689 expect(whiteListedBefore).to.be.false;690 // tslint:disable-next-line: no-unused-expression691 expect(whiteListedAfter).to.be.true;692 });693}694695export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)696 : Promise<ICollectionInterface | null> => {697 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;698};699700export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {701 // set global object - collectionsCount702 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();703};1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25 success: boolean,26};2728interface CreateCollectionResult {29 success: boolean;30 collectionId: number;31}3233interface CreateItemResult {34 success: boolean;35 collectionId: number;36 itemId: number;37}3839interface IReFungibleOwner {40 Fraction: BN;41 Owner: number[];42}4344interface ITokenDataType {45 Owner: number[];46 ConstData: number[];47 VariableData: number[];48}4950interface IFungibleTokenDataType {51 Value: BN;52}5354export interface IReFungibleTokenDataType {55 Owner: IReFungibleOwner[];56 ConstData: number[];57 VariableData: number[];58}5960export function getGenericResult(events: EventRecord[]): GenericResult {61 const result: GenericResult = {62 success: false,63 };64 events.forEach(({ phase, event: { data, method, section } }) => {65 // console.log(` ${phase}: ${section}.${method}:: ${data}`);66 if (method === 'ExtrinsicSuccess') {67 result.success = true;68 }69 });70 return result;71}7273export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {74 let success = false;75 let collectionId: number = 0;76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method == 'ExtrinsicSuccess') {79 success = true;80 } else if ((section == 'nft') && (method == 'Created')) {81 collectionId = parseInt(data[0].toString());82 }83 });84 const result: CreateCollectionResult = {85 success,86 collectionId,87 };88 return result;89}9091export function getCreateItemResult(events: EventRecord[]): CreateItemResult {92 let success = false;93 let collectionId: number = 0;94 let itemId: number = 0;95 events.forEach(({ phase, event: { data, method, section } }) => {96 // console.log(` ${phase}: ${section}.${method}:: ${data}`);97 if (method == 'ExtrinsicSuccess') {98 success = true;99 } else if ((section == 'nft') && (method == 'ItemCreated')) {100 collectionId = parseInt(data[0].toString());101 itemId = parseInt(data[1].toString());102 }103 });104 const result: CreateItemResult = {105 success,106 collectionId,107 itemId,108 };109 return result;110}111112interface Invalid {113 type: 'Invalid';114}115116interface Nft {117 type: 'NFT';118}119120interface Fungible {121 type: 'Fungible';122 decimalPoints: number;123}124125interface ReFungible {126 type: 'ReFungible';127 decimalPoints: number;128}129130interface Nft {131 type: 'NFT'132}133134interface Fungible {135 type: 'Fungible',136 decimalPoints: number137}138139interface ReFungible {140 type: 'ReFungible',141 decimalPoints: number142}143144type CollectionMode = Nft | Fungible | ReFungible | Invalid;145146export type CreateCollectionParams = {147 mode: CollectionMode,148 name: string,149 description: string,150 tokenPrefix: string,151};152153const defaultCreateCollectionParams: CreateCollectionParams = {154 description: 'description',155 mode: { type: 'NFT' },156 name: 'name',157 tokenPrefix: 'prefix',158}159160export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {161 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};162163 let collectionId: number = 0;164 await usingApi(async (api) => {165 // Get number of collections before the transaction166 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168 // Run the CreateCollection transaction169 const alicePrivateKey = privateKey('//Alice');170171 let modeprm = {};172 if (mode.type === 'NFT') {173 modeprm = {nft: null};174 } else if (mode.type === 'Fungible') {175 modeprm = {fungible: mode.decimalPoints};176 } else if (mode.type === 'ReFungible') {177 modeprm = {refungible: mode.decimalPoints};178 } else if (mode.type === 'Invalid') {179 modeprm = {invalid: null};180 }181182 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);183 const events = await submitTransactionAsync(alicePrivateKey, tx);184 const result = getCreateCollectionResult(events);185186 // Get number of collections after the transaction187 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189 // Get the collection190 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192 // What to expect193 // tslint:disable-next-line:no-unused-expression194 expect(result.success).to.be.true;195 expect(result.collectionId).to.be.equal(BcollectionCount);196 // tslint:disable-next-line:no-unused-expression197 expect(collection).to.be.not.null;198 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');199 expect(collection.Owner).to.be.equal(alicesPublicKey);200 expect(utf16ToStr(collection.Name)).to.be.equal(name);201 expect(utf16ToStr(collection.Description)).to.be.equal(description);202 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);203204 collectionId = result.collectionId;205 });206207 return collectionId;208}209210export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {211 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};212213 let modeprm = {};214 if (mode.type === 'NFT') {215 modeprm = {nft: null};216 } else if (mode.type === 'Fungible') {217 modeprm = {fungible: mode.decimalPoints};218 } else if (mode.type === 'ReFungible') {219 modeprm = {refungible: mode.decimalPoints};220 } else if (mode.type === 'Invalid') {221 modeprm = {invalid: null};222 }223224 await usingApi(async (api) => {225 // Get number of collections before the transaction226 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228 // Run the CreateCollection transaction229 const alicePrivateKey = privateKey('//Alice');230 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);231 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;232 const result = getCreateCollectionResult(events);233234 // Get number of collections after the transaction235 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237 // What to expect238 // tslint:disable-next-line:no-unused-expression239 expect(result.success).to.be.false;240 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');241 });242}243244export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {245 let bal = new BigNumber(0);246 let unused;247 do {248 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));249 const keyring = new Keyring({ type: 'sr25519' });250 unused = keyring.addFromUri(`//${randomSeed}`);251 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());252 } while (bal.toFixed() != '0');253 return unused;254}255256export async function findNotExistingCollection(api: ApiPromise): Promise<number> {257 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;258 const newCollection: number = totalNumber + 1;259 return newCollection;260}261262function getDestroyResult(events: EventRecord[]): boolean {263 let success: boolean = false;264 events.forEach(({ phase, event: { data, method, section } }) => {265 // console.log(` ${phase}: ${section}.${method}:: ${data}`);266 if (method == 'ExtrinsicSuccess') {267 success = true;268 }269 });270 return success;271}272273export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {274 await usingApi(async (api) => {275 // Run the DestroyCollection transaction276 const alicePrivateKey = privateKey(senderSeed);277 const tx = api.tx.nft.destroyCollection(collectionId);278 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;279 });280}281282export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {283 await usingApi(async (api) => {284 // Run the DestroyCollection transaction285 const alicePrivateKey = privateKey(senderSeed);286 const tx = api.tx.nft.destroyCollection(collectionId);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getDestroyResult(events);289290 // Get the collection291 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();292293 // What to expect294 expect(result).to.be.true;295 expect(collection).to.be.not.null;296 expect(collection.Owner).to.be.equal(nullPublicKey);297 });298}299300export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {301 await usingApi(async (api) => {302303 // Run the transaction304 const alicePrivateKey = privateKey('//Alice');305 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);306 const events = await submitTransactionAsync(alicePrivateKey, tx);307 const result = getGenericResult(events);308309 // Get the collection310 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();311312 // What to expect313 expect(result.success).to.be.true;314 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());315 expect(collection.SponsorConfirmed).to.be.false;316 });317}318319export async function removeCollectionSponsorExpectSuccess(collectionId: number) {320 await usingApi(async (api) => {321322 // Run the transaction323 const alicePrivateKey = privateKey('//Alice');324 const tx = api.tx.nft.removeCollectionSponsor(collectionId);325 const events = await submitTransactionAsync(alicePrivateKey, tx);326 const result = getGenericResult(events);327328 // Get the collection329 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();330331 // What to expect332 expect(result.success).to.be.true;333 expect(collection.Sponsor).to.be.equal(nullPublicKey);334 expect(collection.SponsorConfirmed).to.be.false;335 });336}337338export async function removeCollectionSponsorExpectFailure(collectionId: number) {339 await usingApi(async (api) => {340341 // Run the transaction342 const alicePrivateKey = privateKey('//Alice');343 const tx = api.tx.nft.removeCollectionSponsor(collectionId);344 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;345 });346}347348export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {349 await usingApi(async (api) => {350351 // Run the transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);354 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;355 });356}357358export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {359 await usingApi(async (api) => {360361 // Run the transaction362 const sender = privateKey(senderSeed);363 const tx = api.tx.nft.confirmSponsorship(collectionId);364 const events = await submitTransactionAsync(sender, tx);365 const result = getGenericResult(events);366367 // Get the collection368 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();369370 // What to expect371 expect(result.success).to.be.true;372 expect(collection.Sponsor).to.be.equal(sender.address);373 expect(collection.SponsorConfirmed).to.be.true;374 });375}376377export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {378 await usingApi(async (api) => {379380 // Run the transaction381 const sender = privateKey(senderSeed);382 const tx = api.tx.nft.confirmSponsorship(collectionId);383 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;384 });385}386387export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {388 await usingApi(async (api) => {389 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);390 const events = await submitTransactionAsync(sender, tx);391 const result = getGenericResult(events);392393 expect(result.success).to.be.true;394 });395}396397export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {398 await usingApi(async (api) => {399 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);400 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;401 const result = getGenericResult(events);402403 expect(result.success).to.be.false;404 });405}406407export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {408 await usingApi(async (api) => {409 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);410 const events = await submitTransactionAsync(sender, tx);411 const result = getGenericResult(events);412413 expect(result.success).to.be.true;414 });415}416417export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {418 await usingApi(async (api) => {419 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);420 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;421 const result = getGenericResult(events);422423 expect(result.success).to.be.false;424 });425}426427export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {428 await usingApi(async (api) => {429 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));430 const events = await submitTransactionAsync(sender, tx);431 const result = getGenericResult(events);432433 expect(result.success).to.be.true;434 });435}436437export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {438 await usingApi(async (api) => {439 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));440 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;441 });442}443444export interface CreateFungibleData extends Struct {445 readonly value: u128;446}447448export interface CreateReFungibleData extends Struct {}449export interface CreateNftData extends Struct {}450451export interface CreateItemData extends Enum {452 NFT: CreateNftData;453 Fungible: CreateFungibleData;454 ReFungible: CreateReFungibleData;455}456457export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {458 await usingApi(async (api) => {459 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);460 const events = await submitTransactionAsync(owner, tx);461 const result = getGenericResult(events);462 // Get the item463 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();464 // What to expect465 // tslint:disable-next-line:no-unused-expression466 expect(result.success).to.be.true;467 // tslint:disable-next-line:no-unused-expression468 expect(item).to.be.not.null;469 expect(item.Owner).to.be.equal(nullPublicKey);470 });471}472473export async function474approveExpectSuccess(collectionId: number,475 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {476 await usingApi(async (api: ApiPromise) => {477 const allowanceBefore =478 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;479 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);480 const events = await submitTransactionAsync(owner, approveNftTx);481 const result = getCreateItemResult(events);482 // tslint:disable-next-line:no-unused-expression483 expect(result.success).to.be.true;484 const allowanceAfter =485 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;486 expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);487 });488}489490export async function491transferFromExpectSuccess(collectionId: number,492 tokenId: number,493 accountApproved: IKeyringPair,494 accountFrom: IKeyringPair,495 accountTo: IKeyringPair,496 value: number = 1,497 type: string = 'NFT') {498 await usingApi(async (api: ApiPromise) => {499 let balanceBefore = new BN(0);500 if (type === 'Fungible') {501 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;502 }503 const transferFromTx = await api.tx.nft.transferFrom(504 accountFrom.address, accountTo.address, collectionId, tokenId, value);505 const events = await submitTransactionAsync(accountApproved, transferFromTx);506 const result = getCreateItemResult(events);507 // tslint:disable-next-line:no-unused-expression508 expect(result.success).to.be.true;509 if (type === 'NFT') {510 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;511 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);512 }513 if (type === 'Fungible') {514 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;515 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);516 }517 if (type === 'ReFungible') {518 const nftItemData =519 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;520 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);521 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);522 }523 });524}525526export async function527transferFromExpectFail(collectionId: number,528 tokenId: number,529 accountApproved: IKeyringPair,530 accountFrom: IKeyringPair,531 accountTo: IKeyringPair,532 value: number = 1) {533 await usingApi(async (api: ApiPromise) => {534 const transferFromTx = await api.tx.nft.transferFrom(535 accountFrom.address, accountTo.address, collectionId, tokenId, value);536 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;537 const result = getCreateCollectionResult(events);538 // tslint:disable-next-line:no-unused-expression539 expect(result.success).to.be.false;540 });541}542543export async function544transferExpectSuccess(collectionId: number,545 tokenId: number,546 sender: IKeyringPair,547 recipient: IKeyringPair,548 value: number = 1,549 type: string = 'NFT') {550 await usingApi(async (api: ApiPromise) => {551 let balanceBefore = new BN(0);552 if (type === 'Fungible') {553 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;554 }555 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);556 const events = await submitTransactionAsync(sender, transferTx);557 const result = getCreateItemResult(events);558 // tslint:disable-next-line:no-unused-expression559 expect(result.success).to.be.true;560 if (type === 'NFT') {561 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;562 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);563 }564 if (type === 'Fungible') {565 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;566 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);567 }568 if (type === 'ReFungible') {569 const nftItemData =570 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;571 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);572 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);573 }574 });575}576577export async function578transferExpectFail(collectionId: number,579 tokenId: number,580 sender: IKeyringPair,581 recipient: IKeyringPair,582 value: number = 1,583 type: string = 'NFT') {584 await usingApi(async (api: ApiPromise) => {585 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);586 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;587 if (events && Array.isArray(events)) {588 const result = getCreateCollectionResult(events);589 // tslint:disable-next-line:no-unused-expression590 expect(result.success).to.be.false;591 }592 });593}594595export async function596approveExpectFail(collectionId: number,597 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {598 await usingApi(async (api: ApiPromise) => {599 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);600 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;601 const result = getCreateCollectionResult(events);602 // tslint:disable-next-line:no-unused-expression603 expect(result.success).to.be.false;604 });605}606607export async function createItemExpectSuccess(608 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {609 let newItemId: number = 0;610 await usingApi(async (api) => {611 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);612 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();613 const AItemBalance = new BigNumber(Aitem.Value);614615 if (owner === '') {616 owner = sender.address;617 }618619 let tx;620 if (createMode === 'Fungible') {621 const createData = {fungible: {value: 10}};622 tx = api.tx.nft.createItem(collectionId, owner, createData);623 } else {624 tx = api.tx.nft.createItem(collectionId, owner, createMode);625 }626 const events = await submitTransactionAsync(sender, tx);627 const result = getCreateItemResult(events);628629 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);630 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();631 const BItemBalance = new BigNumber(Bitem.Value);632633 // What to expect634 // tslint:disable-next-line:no-unused-expression635 expect(result.success).to.be.true;636 if (createMode === 'Fungible') {637 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);638 } else {639 expect(BItemCount).to.be.equal(AItemCount + 1);640 }641 expect(collectionId).to.be.equal(result.collectionId);642 expect(BItemCount).to.be.equal(result.itemId);643 newItemId = result.itemId;644 });645 return newItemId;646}647648export async function setPublicAccessModeExpectSuccess(649 sender: IKeyringPair, collectionId: number,650 accessMode: 'Normal' | 'WhiteList',651) {652 await usingApi(async (api) => {653654 // Run the transaction655 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);656 const events = await submitTransactionAsync(sender, tx);657 const result = getGenericResult(events);658659 // Get the collection660 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();661662 // What to expect663 // tslint:disable-next-line:no-unused-expression664 expect(result.success).to.be.true;665 expect(collection.Access).to.be.equal(accessMode);666 });667}668669export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {670 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');671}672673export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {674 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');675}676677export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {678 await usingApi(async (api) => {679680 // Run the transaction681 const tx = api.tx.nft.setMintPermission(collectionId, true);682 const events = await submitTransactionAsync(sender, tx);683 const result = getGenericResult(events);684685 // Get the collection686 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();687688 // What to expect689 expect(result.success).to.be.true;690 expect(collection.MintMode).to.be.equal(true);691 });692}693694export async function isWhitelisted(collectionId: number, address: string) {695 let whitelisted: boolean = false;696 await usingApi(async (api) => {697 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;698 });699 return whitelisted;700}701702export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {703 await usingApi(async (api) => {704705 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();706707 // Run the transaction708 const tx = api.tx.nft.addToWhiteList(collectionId, address);709 const events = await submitTransactionAsync(sender, tx);710 const result = getGenericResult(events);711712 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();713714 // What to expect715 // tslint:disable-next-line:no-unused-expression716 expect(result.success).to.be.true;717 // tslint:disable-next-line: no-unused-expression718 expect(whiteListedBefore).to.be.false;719 // tslint:disable-next-line: no-unused-expression720 expect(whiteListedAfter).to.be.true;721 });722}723724export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {725 await usingApi(async (api) => {726 // Run the transaction727 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);728 const events = await submitTransactionAsync(sender, tx);729 const result = getGenericResult(events);730731 // What to expect732 // tslint:disable-next-line:no-unused-expression733 expect(result.success).to.be.true;734 });735}736737export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {738 await usingApi(async (api) => {739 // Run the transaction740 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);741 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;742 const result = getGenericResult(events);743744 // What to expect745 // tslint:disable-next-line:no-unused-expression746 expect(result.success).to.be.false;747 });748}749750export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)751 : Promise<ICollectionInterface | null> => {752 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;753};754755export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {756 // set global object - collectionsCount757 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();758};