difftreelog
Merge pull request #54 from usetech-llc/feature/NFTPAR-237
in: master
Feature/NFTPAR-237
13 files changed
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/change-collection-owner.test.ts
@@ -0,0 +1,59 @@
+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, createCollectionExpectFailure } from "./util/helpers";
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
+ it('Changing owner changes owner.', async () => {
+ await usingApi(async api => {
+ const collectionId = await createCollectionExpectSuccess();
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const collection: any = (await api.query.nft.collection(collectionId));
+ expect(collection.Owner.toString()).to.be.eq(alice.address);
+
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+ await submitTransactionAsync(alice, changeOwnerTx);
+
+ const collectionAfterOwnerChange: any = (await api.query.nft.collection(collectionId));
+ expect(collectionAfterOwnerChange.Owner.toString()).to.be.eq(bob.address);
+ });
+ });
+});
+
+describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
+ it(`Not owner can't change owner.`, async () => {
+ await usingApi(async api => {
+ const collectionId = await createCollectionExpectSuccess();
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+ await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
+
+ const collectionAfterOwnerChange: any = (await api.query.nft.collection(collectionId));
+ expect(collectionAfterOwnerChange.Owner.toString()).to.be.eq(alice.address);
+
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await createCollectionExpectSuccess();
+ });
+ });
+ it(`Can't change owner of not existing collection.`, async () => {
+ await usingApi(async api => {
+ const collectionId = (1<<32) - 1;
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+ await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
+
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await createCollectionExpectSuccess();
+ });
+ });
+});
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -5,7 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
import {
createCollectionExpectSuccess,
setCollectionSponsorExpectSuccess,
@@ -44,25 +44,25 @@
});
it('Confirm collection sponsorship', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
});
it('Add sponsor to a collection after the same sponsor was already added and confirmed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
});
it('Add new sponsor to a collection after another sponsor was already added and confirmed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
await setCollectionSponsorExpectSuccess(collectionId, charlie.address);
});
it('NFT: Transfer fees are paid by the sponsor after confirmation', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -89,7 +89,7 @@
});
it('Fungible: Transfer fees are paid by the sponsor after confirmation', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+ const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -115,7 +115,7 @@
});
it('ReFungible: Transfer fees are paid by the sponsor after confirmation', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+ const collectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -141,7 +141,7 @@
});
it('CreateItem fees are paid by the sponsor after confirmation', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -171,7 +171,7 @@
});
it('NFT: Sponsoring is rate limited', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -192,11 +192,7 @@
const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 0);
const badTransaction = async function () {
- console.log = function () {};
- console.error = function () {};
- await submitTransactionAsync(zeroBalance, zeroToAlice);
- delete console.log;
- delete console.error;
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
};
await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -214,7 +210,7 @@
});
it('Fungible: Sponsoring is rate limited', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+ const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -233,11 +229,7 @@
const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
const badTransaction = async function () {
- console.log = function () {};
- console.error = function () {};
- await submitTransactionAsync(zeroBalance, zeroToAlice);
- delete console.log;
- delete console.error;
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
};
const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -255,7 +247,7 @@
});
it('ReFungible: Sponsoring is rate limited', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+ const collectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
@@ -276,11 +268,7 @@
const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 1);
const badTransaction = async function () {
- console.log = function () {};
- console.error = function () {};
- await submitTransactionAsync(zeroBalance, zeroToAlice);
- delete console.log;
- delete console.error;
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
};
await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -320,7 +308,7 @@
});
it('(!negative test!) Confirm sponsorship using a non-sponsor address', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await usingApi(async (api) => {
@@ -332,18 +320,18 @@
});
it('(!negative test!) Confirm sponsorship using owner address', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectFailure(collectionId, '//Alice');
});
it('(!negative test!) Confirm sponsorship without sponsor being set with setCollectionSponsor', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
});
it('(!negative test!) Confirm sponsorship in a collection that was destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectSuccess(collectionId);
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
});
tests/src/connection.test.tsdiffbeforeafterboth--- a/tests/src/connection.test.ts
+++ b/tests/src/connection.test.ts
@@ -21,6 +21,8 @@
});
it('Cannot connect to 255.255.255.255', async () => {
+ const log = console.log;
+ const error = console.error;
console.log = function () {};
console.error = function () {};
@@ -31,7 +33,7 @@
}, { provider: neverConnectProvider });
})()).to.be.eventually.rejected;
- delete console.log;
- delete console.error;
+ console.log = log;
+ console.error = error;
});
});
\ No newline at end of file
tests/src/contracts.test.tsdiffbeforeafterboth1import chai from "chai";2import chaiAsPromised from 'chai-as-promised';3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";4import fs from "fs";5import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";6import { IKeyringPair } from "@polkadot/types/types";7import { ApiPromise, Keyring } from "@polkadot/api";8import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";9import privateKey from "./substrate/privateKey";1011chai.use(chaiAsPromised);12const expect = chai.expect;13import { BigNumber } from 'bignumber.js';14import { findUnusedAddress } from './util/helpers'1516const value = 0;17const gasLimit = 3000n * 1000000n;18const endowment = `1000000000000000`;1920function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {21 return new Promise<Blueprint>(async (resolve, reject) => {22 const unsub = await code23 .createBlueprint()24 .signAndSend(alice, (result) => {25 if (result.status.isInBlock || result.status.isFinalized) {26 // here we have an additional field in the result, containing the blueprint27 resolve(result.blueprint);28 unsub();29 }30 })31 });32}3334function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {35 return new Promise<any>(async (resolve, reject) => {36 const initValue = true;3738 const unsub = await blueprint.tx39 .new(endowment, gasLimit, initValue)40 .signAndSend(alice, (result) => {41 if (result.status.isInBlock || result.status.isFinalized) {42 unsub();43 resolve(result);44 }45 }); 46 });47}4849async function prepareDeployer(api: ApiPromise) {50 // Find unused address51 const deployer = await findUnusedAddress(api);5253 // Transfer balance to it54 const keyring = new Keyring({ type: 'sr25519' });55 const alice = keyring.addFromUri(`//Alice`);56 let amount = new BigNumber(endowment);57 amount = amount.plus(1e15);58 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());59 await submitTransactionAsync(alice, tx);6061 return deployer;62}6364async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {65 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));66 const abi = new Abi(metadata);6768 const deployer = await prepareDeployer(api);6970 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');7172 const code = new CodePromise(api, abi, wasm);7374 const blueprint = await deployBlueprint(deployer, code);75 const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7677 const initialGetResponse = await getFlipValue(contract, deployer);78 expect(initialGetResponse).to.be.true;7980 return [contract, deployer];81}8283async function getFlipValue(contract: Contract, deployer: IKeyringPair) {84 const result = await contract.query.get(deployer.address, value, gasLimit);8586 if(!result.result.isSuccess) {87 throw `Failed to get flipper value`;88 }89 return (result.result.asSuccess.data[0] == 0x00) ? false : true;90}9192describe('Contracts', () => {93 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {94 await usingApi(async api => {95 const [contract, deployer] = await deployFlipper(api);96 const initialGetResponse = await getFlipValue(contract, deployer);9798 const bob = privateKey("//Bob");99 const flip = contract.exec('flip', value, gasLimit);100 await submitTransactionAsync(bob, flip);101102 const afterFlipGetResponse = await getFlipValue(contract, deployer);103 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');104 });105 });106107 it(`Whitelisted account can call contract.`, async () => {108 await usingApi(async api => {109 const bob = privateKey("//Bob");110 111 const [contract, deployer] = await deployFlipper(api);112 const consoleError = console.error;113 console.error = (...data: any[]) => {114 };115116 let expectedFlipValue = await getFlipValue(contract, deployer);117118 const flip = contract.exec('flip', value, gasLimit);119 await submitTransactionAsync(bob, flip);120 expectedFlipValue = !expectedFlipValue;121 const afterFlip = await getFlipValue(contract,deployer);122 expect(afterFlip).to.be.eq(expectedFlipValue, `Anyone can call new contract.`);123124 const deployerCanFlip = async () => {125 expectedFlipValue = !expectedFlipValue;126 const deployerFlip = contract.exec('flip', value, gasLimit);127 await submitTransactionAsync(deployer, deployerFlip);128 const aliceFlip1Response = await getFlipValue(contract, deployer);129 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);130 };131 await deployerCanFlip();132133 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);134 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);135 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);136 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;137 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);138 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);139140 await deployerCanFlip();141142 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);143 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);144 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);145 await submitTransactionAsync(bob, flipWithWhitelistedBob);146 expectedFlipValue = !expectedFlipValue;147 const flipAfterWhiteListed = await getFlipValue(contract,deployer);148 expect(flipAfterWhiteListed).to.be.eq(expectedFlipValue, `Bob was whitelisted, now he can flip.`);149150 await deployerCanFlip();151152 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);153 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);154 const bobRemoved = contract.exec('flip', value, gasLimit);155 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;156 const afterBobRemoved = await getFlipValue(contract, deployer);157 expect(afterBobRemoved).to.be.eq(expectedFlipValue, `Bob can't call contract, now when he is removeed from white list.`);158159 await deployerCanFlip();160161 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);162 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);163 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);164 await submitTransactionAsync(bob, whiteListDisabledFlip);165 expectedFlipValue = !expectedFlipValue;166 const afterWhiteListDisabled = await getFlipValue(contract,deployer);167 expect(afterWhiteListDisabled).to.be.eq(expectedFlipValue, `Anyone can call contract with disabled whitelist.`);168169 console.error = consoleError;170 });171 });172173 it.skip('Can transfer balance using smart contract.', async () => {174 await usingApi(async api => {175 // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);176 // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');177 // const contract = compactAddLength(u8aToU8a(wasm));178179 // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));180 // const abi = new Abi(api.registry as any, metadata);181182 // const alicesPrivateKey = privateKey('//Alice');183184 // const contractHash = await deployContract(api, contract, alicesPrivateKey);185186 // // const args = abi.constructors[0]();187 // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);188 // const contractInstance = new ContractPromise(api, abi, instanceAccountId);189 // const bob = new GenericAccountId(api.registry, bobsPublicKey);190191 // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);192 // await submitTransactionAsync(alicesPrivateKey, transfer);193194 // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);195196 // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;197 // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;198 });199 })200});1import chai from "chai";2import chaiAsPromised from 'chai-as-promised';3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";4import fs from "fs";5import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";6import { IKeyringPair } from "@polkadot/types/types";7import { ApiPromise, Keyring } from "@polkadot/api";8import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";9import privateKey from "./substrate/privateKey";1011chai.use(chaiAsPromised);12const expect = chai.expect;13import { BigNumber } from 'bignumber.js';14import { findUnusedAddress } from './util/helpers'1516const value = 0;17const gasLimit = 3000n * 1000000n;18const endowment = `1000000000000000`;1920function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {21 return new Promise<Blueprint>(async (resolve, reject) => {22 const unsub = await code23 .createBlueprint()24 .signAndSend(alice, (result) => {25 if (result.status.isInBlock || result.status.isFinalized) {26 // here we have an additional field in the result, containing the blueprint27 resolve(result.blueprint);28 unsub();29 }30 })31 });32}3334function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {35 return new Promise<any>(async (resolve, reject) => {36 const initValue = true;3738 const unsub = await blueprint.tx39 .new(endowment, gasLimit, initValue)40 .signAndSend(alice, (result) => {41 if (result.status.isInBlock || result.status.isFinalized) {42 unsub();43 resolve(result);44 }45 }); 46 });47}4849async function prepareDeployer(api: ApiPromise) {50 // Find unused address51 const deployer = await findUnusedAddress(api);5253 // Transfer balance to it54 const keyring = new Keyring({ type: 'sr25519' });55 const alice = keyring.addFromUri(`//Alice`);56 let amount = new BigNumber(endowment);57 amount = amount.plus(1e15);58 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());59 await submitTransactionAsync(alice, tx);6061 return deployer;62}6364async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {65 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));66 const abi = new Abi(metadata);6768 const deployer = await prepareDeployer(api);6970 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');7172 const code = new CodePromise(api, abi, wasm);7374 const blueprint = await deployBlueprint(deployer, code);75 const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7677 const initialGetResponse = await getFlipValue(contract, deployer);78 expect(initialGetResponse).to.be.true;7980 return [contract, deployer];81}8283async function getFlipValue(contract: Contract, deployer: IKeyringPair) {84 const result = await contract.query.get(deployer.address, value, gasLimit);8586 if(!result.result.isSuccess) {87 throw `Failed to get flipper value`;88 }89 return (result.result.asSuccess.data[0] == 0x00) ? false : true;90}9192describe('Contracts', () => {93 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {94 await usingApi(async api => {95 const [contract, deployer] = await deployFlipper(api);96 const initialGetResponse = await getFlipValue(contract, deployer);9798 const bob = privateKey("//Bob");99 const flip = contract.exec('flip', value, gasLimit);100 await submitTransactionAsync(bob, flip);101102 const afterFlipGetResponse = await getFlipValue(contract, deployer);103 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');104 });105 });106107 it(`Whitelisted account can call contract.`, async () => {108 await usingApi(async api => {109 const bob = privateKey("//Bob");110 111 const [contract, deployer] = await deployFlipper(api);112113 let expectedFlipValue = await getFlipValue(contract, deployer);114115 const flip = contract.exec('flip', value, gasLimit);116 await submitTransactionAsync(bob, flip);117 expectedFlipValue = !expectedFlipValue;118 const afterFlip = await getFlipValue(contract,deployer);119 expect(afterFlip).to.be.eq(expectedFlipValue, `Anyone can call new contract.`);120121 const deployerCanFlip = async () => {122 expectedFlipValue = !expectedFlipValue;123 const deployerFlip = contract.exec('flip', value, gasLimit);124 await submitTransactionAsync(deployer, deployerFlip);125 const aliceFlip1Response = await getFlipValue(contract, deployer);126 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);127 };128 await deployerCanFlip();129130 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);131 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);132 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);133 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;134 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);135 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);136137 await deployerCanFlip();138139 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);140 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);141 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);142 await submitTransactionAsync(bob, flipWithWhitelistedBob);143 expectedFlipValue = !expectedFlipValue;144 const flipAfterWhiteListed = await getFlipValue(contract,deployer);145 expect(flipAfterWhiteListed).to.be.eq(expectedFlipValue, `Bob was whitelisted, now he can flip.`);146147 await deployerCanFlip();148149 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);150 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);151 const bobRemoved = contract.exec('flip', value, gasLimit);152 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;153 const afterBobRemoved = await getFlipValue(contract, deployer);154 expect(afterBobRemoved).to.be.eq(expectedFlipValue, `Bob can't call contract, now when he is removeed from white list.`);155156 await deployerCanFlip();157158 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);159 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);160 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);161 await submitTransactionAsync(bob, whiteListDisabledFlip);162 expectedFlipValue = !expectedFlipValue;163 const afterWhiteListDisabled = await getFlipValue(contract,deployer);164 expect(afterWhiteListDisabled).to.be.eq(expectedFlipValue, `Anyone can call contract with disabled whitelist.`);165166 });167 });168169 it.skip('Can transfer balance using smart contract.', async () => {170 await usingApi(async api => {171 // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);172 // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');173 // const contract = compactAddLength(u8aToU8a(wasm));174175 // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));176 // const abi = new Abi(api.registry as any, metadata);177178 // const alicesPrivateKey = privateKey('//Alice');179180 // const contractHash = await deployContract(api, contract, alicesPrivateKey);181182 // // const args = abi.constructors[0]();183 // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);184 // const contractInstance = new ContractPromise(api, abi, instanceAccountId);185 // const bob = new GenericAccountId(api.registry, bobsPublicKey);186187 // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);188 // await submitTransactionAsync(alicesPrivateKey, transfer);189190 // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);191192 // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;193 // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;194 });195 })196});tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -6,37 +6,29 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { default as usingApi } from "./substrate/substrate-api";
-import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
+import { createCollectionExpectSuccess, createCollectionExpectFailure, CollectionMode } from "./util/helpers";
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('integration test: ext. createCollection():', () => {
it('Create new NFT collection', async () => {
- await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
});
it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
- await createCollectionExpectSuccess(
- 'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCD',
- '1', '1', 'NFT');
+ await createCollectionExpectSuccess({name: 'A'.repeat(64)});
});
it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
- await createCollectionExpectSuccess(
- 'A',
- 'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdef',
- '1', 'NFT');
+ await createCollectionExpectSuccess({description: 'A'.repeat(256)});
});
it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
- await createCollectionExpectSuccess(
- '1',
- '1',
- 'ABCDEFGHIJABCDEF', 'NFT');
+ await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
});
it('Create new Fungible collection', async () => {
- await createCollectionExpectSuccess('1', '1', '1', 'Fungible');
+ await createCollectionExpectSuccess({mode: 'Fungible'});
});
it('Create new ReFungible collection', async () => {
- await createCollectionExpectSuccess('1', '1', '1', 'ReFungible');
+ await createCollectionExpectSuccess({mode: 'ReFungible'});
});
});
@@ -46,7 +38,7 @@
const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
const badTransaction = async function () {
- await createCollectionExpectSuccess('1', '1', '1', 'BadMode');
+ await createCollectionExpectSuccess({mode: 'BadMode' as CollectionMode});
};
expect(badTransaction()).to.be.rejected;
@@ -55,18 +47,12 @@
});
});
it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
- await createCollectionExpectFailure(
- 'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDE',
- '1', '1', 'NFT');
+ await createCollectionExpectFailure({name: 'A'.repeat(65)});
});
it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
- await createCollectionExpectFailure('1',
- 'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdefg',
- '1', 'NFT');
+ await createCollectionExpectFailure({description: 'A'.repeat(257)});
});
it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
- await createCollectionExpectFailure('1', '1',
- 'ABCDEFGHIJABCDEFG',
- 'NFT');
+ await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17)});
});
});
tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -18,17 +18,17 @@
it('Create new item in NFT collection', async () => {
const createMode = 'NFT';
- const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+ const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
await createItemExpectSuccess(alice, newCollectionID, createMode);
});
it('Create new item in Fungible collection', async () => {
const createMode = 'Fungible';
- const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+ const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
await createItemExpectSuccess(alice, newCollectionID, createMode);
});
it('Create new item in ReFungible collection', async () => {
const createMode = 'ReFungible';
- const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+ const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
await createItemExpectSuccess(alice, newCollectionID, createMode);
});
});
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -5,7 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
import { alicesPublicKey, bobsPublicKey } from "./accounts";
import privateKey from "./substrate/privateKey";
import { BigNumber } from 'bignumber.js';
@@ -63,14 +63,13 @@
const bobBalanceBefore = new BigNumber((await api.query.system.account(bobsPublicKey)).data.free.toString());
const badTx = api.tx.balances.setBalance(alicesPublicKey, 0, 0);
- const result = getGenericResult(await submitTransactionAsync(bobPrivateKey, badTx));
+ await expect(submitTransactionExpectFailAsync(bobPrivateKey, badTx)).to.be.rejected;
const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
const bobBalanceAfter = new BigNumber((await api.query.system.account(bobsPublicKey)).data.free.toString());
const fee = bobBalanceBefore.minus(bobBalanceAfter);
const treasuryIncrease = treasuryBalanceAfter.minus(treasuryBalanceBefore);
- expect(result.success).to.be.false;
expect(treasuryIncrease.toFixed()).to.be.equal(fee.toFixed());
});
});
@@ -80,7 +79,7 @@
const treasuryBalanceBefore = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
const aliceBalanceBefore = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
- await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await createCollectionExpectSuccess();
const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
@@ -96,7 +95,7 @@
const treasuryBalanceBefore = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
const aliceBalanceBefore = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
- await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await createCollectionExpectSuccess();
const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -10,15 +10,15 @@
describe('integration test: ext. destroyCollection():', () => {
it('NFT collection can be destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectSuccess(collectionId);
});
it('Fungible collection can be destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+ const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
await destroyCollectionExpectSuccess(collectionId);
});
it('ReFungible collection can be destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+ const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
await destroyCollectionExpectSuccess(collectionId);
});
});
@@ -32,12 +32,12 @@
});
});
it('(!negative test!) Destroy a collection that has already been destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectSuccess(collectionId);
await destroyCollectionExpectFailure(collectionId);
});
it('(!negative test!) Destroy a collection using non-owner account', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectFailure(collectionId, '//Bob');
await destroyCollectionExpectSuccess(collectionId, '//Alice');
});
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -5,7 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
import {
createCollectionExpectSuccess,
setCollectionSponsorExpectSuccess,
@@ -46,7 +46,7 @@
});
it('Remove NFT collection sponsor stops sponsorship', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
await removeCollectionSponsorExpectSuccess(collectionId);
@@ -62,11 +62,7 @@
const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 0);
const badTransaction = async function () {
- console.log = function () {};
- console.error = function () {};
- await submitTransactionAsync(zeroBalance, zeroToAlice);
- delete console.log;
- delete console.error;
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
};
await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -76,7 +72,7 @@
});
it('Remove a sponsor after it was already removed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
await removeCollectionSponsorExpectSuccess(collectionId);
@@ -84,12 +80,12 @@
});
it('Remove sponsor in a collection that never had the sponsor set', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await removeCollectionSponsorExpectSuccess(collectionId);
});
it('Remove sponsor for a collection that had the sponsor set, but not confirmed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await removeCollectionSponsorExpectSuccess(collectionId);
});
@@ -117,21 +113,21 @@
});
it('(!negative test!) Remove sponsor in a destroyed collection', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await destroyCollectionExpectSuccess(collectionId);
await removeCollectionSponsorExpectFailure(collectionId);
});
it('Set - remove - confirm: fails', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await removeCollectionSponsorExpectSuccess(collectionId);
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
});
it('Set - confirm - remove - confirm: Sponsor cannot come back', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
await removeCollectionSponsorExpectSuccess(collectionId);
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -26,25 +26,25 @@
});
it('Set NFT collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
});
it('Set Fungible collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+ const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
});
it('Set ReFungible collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+ const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
});
it('Set the same sponsor repeatedly', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
});
it('Replace collection sponsor', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
const keyring = new Keyring({ type: 'sr25519' });
const charlie = keyring.addFromUri(`//Charlie`);
@@ -62,7 +62,7 @@
});
it('(!negative test!) Add sponsor with a non-owner', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectFailure(collectionId, bob.address, '//Bob');
});
it('(!negative test!) Add sponsor to a collection that never existed', async () => {
@@ -75,7 +75,7 @@
await setCollectionSponsorExpectFailure(collectionId, bob.address);
});
it('(!negative test!) Add sponsor to a collection that was destroyed', async () => {
- const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectSuccess(collectionId);
await setCollectionSponsorExpectFailure(collectionId, bob.address);
});
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -33,21 +33,42 @@
}
}
+enum TransactionStatus {
+ Success,
+ Fail,
+ NotReady
+}
+
+function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {
+ if (status.isReady) {
+ return TransactionStatus.NotReady;
+ }
+ if (status.isBroadcast) {
+ return TransactionStatus.NotReady;
+ }
+ if (status.isInBlock || status.isFinalized) {
+ if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {
+ return TransactionStatus.Fail;
+ }
+ if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {
+ return TransactionStatus.Success;
+ }
+ }
+
+ return TransactionStatus.Fail;
+}
+
export function submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
return new Promise(async function(resolve, reject) {
try {
await transaction.signAndSend(sender, ({ events = [], status }) => {
- if (status.isReady) {
- // nothing to do
- // console.log(`Current tx status is Ready`);
- } else if (status.isBroadcast) {
- // nothing to do
- // console.log(`Current tx status is Broadcast`);
- } else if (status.isInBlock || status.isFinalized) {
+ const transactionStatus = getTransactionStatus(events, status);
+
+ if (transactionStatus == TransactionStatus.Success) {
resolve(events);
- } else {
+ } else if (transactionStatus == TransactionStatus.Fail) {
console.log(`Something went wrong with transaction. Status: ${status}`);
- reject("Transaction failed");
+ reject(events);
}
});
} catch (e) {
@@ -58,19 +79,35 @@
}
export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
- return new Promise(async function(resolve, reject) {
+ const consoleError = console.error;
+ const consoleLog = console.log;
+ console.error = () => {};
+ console.log = () => {};
+
+ return new Promise<EventRecord[]>(async function(res, rej) {
+ const resolve = (rec: EventRecord[]) => {
+ setTimeout(() => {
+ res(rec);
+ console.error = consoleError;
+ console.log = consoleLog;
+
+ });
+ };
+ const reject = (errror: any) => {
+ setTimeout(() => {
+ rej(errror);
+ console.error = consoleError;
+ console.log = consoleLog;
+ });
+ };
try {
await transaction.signAndSend(sender, ({ events = [], status }) => {
- if (status.isReady) {
- // nothing to do
- // console.log(`Current tx status is Ready`);
- } else if (status.isBroadcast) {
- // nothing to do
- // console.log(`Current tx status is Broadcast`);
- } else if (status.isInBlock || status.isFinalized) {
+ const transactionStatus = getTransactionStatus(events, status);
+
+ if (transactionStatus == TransactionStatus.Success) {
resolve(events);
- } else {
- reject("Transaction failed");
+ } else if (transactionStatus == TransactionStatus.Fail) {
+ reject(events);
}
});
} catch (e) {
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -33,6 +33,8 @@
// Find unused address
const pk = await findUnusedAddress(api);
+ const error = console.error;
+ const log = console.log;
console.log = function () {};
console.error = function () {};
@@ -42,8 +44,8 @@
};
await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
- delete console.log;
- delete console.error;
+ console.log = log;
+ console.error = error;
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -7,7 +7,7 @@
import chaiAsPromised from 'chai-as-promised';
import type { AccountId, EventRecord } from '@polkadot/types/interfaces';
import { ApiPromise, Keyring } from "@polkadot/api";
-import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";
import privateKey from '../substrate/privateKey';
import { alicesPublicKey, nullPublicKey } from "../accounts";
import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';
@@ -86,7 +86,24 @@
return result;
}
-export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {
+export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';
+export type CreateCollectionParams = {
+ mode: CollectionMode,
+ name: string,
+ description: string,
+ tokenPrefix: string
+};
+
+const defaultCreateCollectionParams: CreateCollectionParams = {
+ name: 'name',
+ description: 'description',
+ mode: 'NFT',
+ tokenPrefix: 'prefix'
+}
+
+export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
+ const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};
+
let collectionId: number = 0;
await usingApi(async (api) => {
// Get number of collections before the transaction
@@ -120,15 +137,17 @@
return collectionId;
}
-export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {
+export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
+ const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};
+
await usingApi(async (api) => {
// Get number of collections before the transaction
const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
- const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);
+ const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
const result = getCreateCollectionResult(events);
// Get number of collections after the transaction
@@ -168,11 +187,7 @@
// Run the DestroyCollection transaction
const alicePrivateKey = privateKey(senderSeed);
const tx = api.tx.nft.destroyCollection(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getDestroyResult(events);
-
- // What to expect
- expect(result).to.be.false;
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
});
}
@@ -238,11 +253,7 @@
// Run the transaction
const alicePrivateKey = privateKey('//Alice');
const tx = api.tx.nft.removeCollectionSponsor(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getGenericResult(events);
-
- // What to expect
- expect(result.success).to.be.false;
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
});
}
@@ -252,11 +263,7 @@
// Run the transaction
const alicePrivateKey = privateKey(senderSeed);
const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getGenericResult(events);
-
- // What to expect
- expect(result.success).to.be.false;
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
});
}
@@ -285,11 +292,7 @@
// Run the transaction
const sender = privateKey(senderSeed);
const tx = api.tx.nft.confirmSponsorship(collectionId);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // What to expect
- expect(result.success).to.be.false;
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
});
}