git.delta.rocks / unique-network / refs/commits / f16723a5aa89

difftreelog

source

tests/src/util/helpers.ts13.8 KiBsourcehistory
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 chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122type GenericResult = {23  success: boolean,24};2526type CreateCollectionResult = {27  success: boolean,28  collectionId: number29};3031type CreateItemResult = {32  success: boolean,33  collectionId: number,34  itemId: number35};3637export function getGenericResult(events: EventRecord[]): GenericResult {38  let result: GenericResult = {39    success: false40  }41  events.forEach(({ phase, event: { data, method, section } }) => {42    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);43    if (method == 'ExtrinsicSuccess') {44      result.success = true;45    }46  });47  return result;48}4950function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {51  let success = false;52  let collectionId: number = 0;53  events.forEach(({ phase, event: { data, method, section } }) => {54    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);55    if (method == 'ExtrinsicSuccess') {56      success = true;57    } else if ((section == 'nft') && (method == 'Created')) {58      collectionId = parseInt(data[0].toString());59    }60  });61  let result: CreateCollectionResult = {62    success,63    collectionId64  }65  return result;66}6768function getCreateItemResult(events: EventRecord[]): CreateItemResult {69  let success = false;70  let collectionId: number = 0;71  let itemId: number = 0;72  events.forEach(({ phase, event: { data, method, section } }) => {73    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);74    if (method == 'ExtrinsicSuccess') {75      success = true;76    } else if ((section == 'nft') && (method == 'ItemCreated')) {77      collectionId = parseInt(data[0].toString());78      itemId = parseInt(data[1].toString());79    }80  });81  let result: CreateItemResult = {82    success,83    collectionId,84    itemId85  }86  return result;87}8889export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {90  let collectionId: number = 0;91  await usingApi(async (api) => {92    // Get number of collections before the transaction93    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());9495    // Run the CreateCollection transaction96    const alicePrivateKey = privateKey('//Alice');97    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);98    const events = await submitTransactionAsync(alicePrivateKey, tx);99    const result = getCreateCollectionResult(events);100101    // Get number of collections after the transaction102    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());103104    // Get the collection 105    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();106107    // What to expect108    expect(result.success).to.be.true;109    expect(result.collectionId).to.be.equal(BcollectionCount);110    expect(collection).to.be.not.null;111    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');112    expect(collection.Owner).to.be.equal(alicesPublicKey);113    expect(utf16ToStr(collection.Name)).to.be.equal(name);114    expect(utf16ToStr(collection.Description)).to.be.equal(description);115    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);116117    collectionId = result.collectionId;118  });119120  return collectionId;121}122  123export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {124  await usingApi(async (api) => {125    // Get number of collections before the transaction126    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());127128    // Run the CreateCollection transaction129    const alicePrivateKey = privateKey('//Alice');130    const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);131    const events = await submitTransactionAsync(alicePrivateKey, tx);132    const result = getCreateCollectionResult(events);133134    // Get number of collections after the transaction135    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());136137    // What to expect138    expect(result.success).to.be.false;139    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');140  });141}142  143export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {144  let bal = new BigNumber(0);145  let unused;146  do {147    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));148    const keyring = new Keyring({ type: 'sr25519' });149    unused = keyring.addFromUri(`//${randomSeed}`);150    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());151  } while (bal.toFixed() != '0');152  return unused; 153}154155function getDestroyResult(events: EventRecord[]): boolean {156  let success: boolean = false;157  events.forEach(({ phase, event: { data, method, section } }) => {158    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);159    if (method == 'ExtrinsicSuccess') {160      success = true;161    }162  });163  return success;164}165166export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {167  await usingApi(async (api) => {168    // Run the DestroyCollection transaction169    const alicePrivateKey = privateKey(senderSeed);170    const tx = api.tx.nft.destroyCollection(collectionId);171    const events = await submitTransactionAsync(alicePrivateKey, tx);172    const result = getDestroyResult(events);173174    // What to expect175    expect(result).to.be.false;176  });177}178179export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {180  await usingApi(async (api) => {181    // Run the DestroyCollection transaction182    const alicePrivateKey = privateKey(senderSeed);183    const tx = api.tx.nft.destroyCollection(collectionId);184    const events = await submitTransactionAsync(alicePrivateKey, tx);185    const result = getDestroyResult(events);186187    // Get the collection 188    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();189190    // What to expect191    expect(result).to.be.true;192    expect(collection).to.be.not.null;193    expect(collection.Owner).to.be.equal(nullPublicKey);194  });195}196197export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {198  await usingApi(async (api) => {199200    // Run the transaction201    const alicePrivateKey = privateKey('//Alice');202    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);203    const events = await submitTransactionAsync(alicePrivateKey, tx);204    const result = getGenericResult(events);205206    // Get the collection 207    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();208209    // What to expect210    expect(result.success).to.be.true;211    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());212    expect(collection.SponsorConfirmed).to.be.false;213  });214}215216export async function removeCollectionSponsorExpectSuccess(collectionId: number) {217  await usingApi(async (api) => {218219    // Run the transaction220    const alicePrivateKey = privateKey('//Alice');221    const tx = api.tx.nft.removeCollectionSponsor(collectionId);222    const events = await submitTransactionAsync(alicePrivateKey, tx);223    const result = getGenericResult(events);224225    // Get the collection 226    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();227228    // What to expect229    expect(result.success).to.be.true;230    expect(collection.Sponsor).to.be.equal(nullPublicKey);231    expect(collection.SponsorConfirmed).to.be.false;232  });233}234235export async function removeCollectionSponsorExpectFailure(collectionId: number) {236  await usingApi(async (api) => {237238    // Run the transaction239    const alicePrivateKey = privateKey('//Alice');240    const tx = api.tx.nft.removeCollectionSponsor(collectionId);241    const events = await submitTransactionAsync(alicePrivateKey, tx);242    const result = getGenericResult(events);243244    // What to expect245    expect(result.success).to.be.false;246  });247}248249export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {250  await usingApi(async (api) => {251252    // Run the transaction253    const alicePrivateKey = privateKey(senderSeed);254    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);255    const events = await submitTransactionAsync(alicePrivateKey, tx);256    const result = getGenericResult(events);257258    // What to expect259    expect(result.success).to.be.false;260  });261}262263export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {264  await usingApi(async (api) => {265266    // Run the transaction267    const sender = privateKey(senderSeed);268    const tx = api.tx.nft.confirmSponsorship(collectionId);269    const events = await submitTransactionAsync(sender, tx);270    const result = getGenericResult(events);271272    // Get the collection 273    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();274275    // What to expect276    expect(result.success).to.be.true;277    expect(collection.Sponsor).to.be.equal(sender.address);278    expect(collection.SponsorConfirmed).to.be.true;279  });280}281282export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {283  await usingApi(async (api) => {284285    // Run the transaction286    const sender = privateKey(senderSeed);287    const tx = api.tx.nft.confirmSponsorship(collectionId);288    const events = await submitTransactionAsync(sender, tx);289    const result = getGenericResult(events);290291    // What to expect292    expect(result.success).to.be.false;293  });294}295296export interface CreateFungibleData extends Struct {297  readonly value: u128;298};299300export interface CreateReFungibleData extends Struct {};301export interface CreateNftData extends Struct {};302303export interface CreateItemData extends Enum {304  NFT: CreateNftData,305  Fungible: CreateFungibleData,306  ReFungible: CreateReFungibleData307};308309export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {310  let newItemId: number = 0;311  await usingApi(async (api) => {312    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());313    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    314    const AItemBalance = new BigNumber(Aitem.Value);315316    if (owner === '') owner = sender.address;317318    let tx;319    if (createMode == 'Fungible') {320      let createData = {fungible: {value: 10}};321      tx = api.tx.nft.createItem(collectionId, owner, createData);322    }323    else {324      tx = api.tx.nft.createItem(collectionId, owner, createMode);325    }326    const events = await submitTransactionAsync(sender, tx);327    const result = getCreateItemResult(events);328329    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());330    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    331    const BItemBalance = new BigNumber(Bitem.Value);332333    // What to expect334    expect(result.success).to.be.true;335    if (createMode == 'Fungible') {336      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);337    }338    else {339      expect(BItemCount).to.be.equal(AItemCount+1);340    }341    expect(collectionId).to.be.equal(result.collectionId);342    expect(BItemCount).to.be.equal(result.itemId);343    newItemId = result.itemId;344  });345  return newItemId;346}347348export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {349  await usingApi(async (api) => {350351    // Run the transaction352    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');353    const events = await submitTransactionAsync(sender, tx);354    const result = getGenericResult(events);355356    // Get the collection 357    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();358359    // What to expect360    expect(result.success).to.be.true;361    expect(collection.Access).to.be.equal('WhiteList');362  });363}364365export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {366  await usingApi(async (api) => {367368    // Run the transaction369    const tx = api.tx.nft.setMintPermission(collectionId, true);370    const events = await submitTransactionAsync(sender, tx);371    const result = getGenericResult(events);372373    // Get the collection 374    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();375376    // What to expect377    expect(result.success).to.be.true;378    expect(collection.MintMode).to.be.equal(true);379  });380}381382export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {383  await usingApi(async (api) => {384385    // Run the transaction386    const tx = api.tx.nft.addToWhiteList(collectionId, address);387    const events = await submitTransactionAsync(sender, tx);388    const result = getGenericResult(events);389390    // Get the collection 391    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();392393    // What to expect394    expect(result.success).to.be.true;395    expect(collection.MintMode).to.be.equal(true);396  });397}398