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

difftreelog

source

tests/src/util/helpers.ts18.4 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 { 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 ITokenDataType {40  Owner: number[];41  ConstData: number[];42  VariableData: number[];43}4445export function getGenericResult(events: EventRecord[]): GenericResult {46  const result: GenericResult = {47    success: false,48  };49  events.forEach(({ phase, event: { data, method, section } }) => {50    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);51    if (method === 'ExtrinsicSuccess') {52      result.success = true;53    }54  });55  return result;56}5758export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {59  let success = false;60  let collectionId: number = 0;61  events.forEach(({ phase, event: { data, method, section } }) => {62    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);63    if (method == 'ExtrinsicSuccess') {64      success = true;65    } else if ((section == 'nft') && (method == 'Created')) {66      collectionId = parseInt(data[0].toString());67    }68  });69  const result: CreateCollectionResult = {70    success,71    collectionId,72  };73  return result;74}7576export function getCreateItemResult(events: EventRecord[]): CreateItemResult {77  let success = false;78  let collectionId: number = 0;79  let itemId: number = 0;80  events.forEach(({ phase, event: { data, method, section } }) => {81    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);82    if (method == 'ExtrinsicSuccess') {83      success = true;84    } else if ((section == 'nft') && (method == 'ItemCreated')) {85      collectionId = parseInt(data[0].toString());86      itemId = parseInt(data[1].toString());87    }88  });89  const result: CreateItemResult = {90    success,91    collectionId,92    itemId,93  };94  return result;95}9697interface Invalid {98  type: 'Invalid';99}100101interface Nft {102  type: 'NFT';103}104105interface Fungible {106  type: 'Fungible';107  decimalPoints: number;108}109110interface ReFungible {111  type: 'ReFungible';112  decimalPoints: number;113}114115type CollectionMode = Nft | Fungible | ReFungible | Invalid;116117export type CreateCollectionParams = {118  mode: CollectionMode,119  name: string,120  description: string,121  tokenPrefix: string,122};123124const defaultCreateCollectionParams: CreateCollectionParams = {125  description: 'description',126  mode: { type: 'NFT' },127  name: 'name',128  tokenPrefix: 'prefix',129}130131export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {132  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};133134  let collectionId: number = 0;135  await usingApi(async (api) => {136    // Get number of collections before the transaction137    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);138139    // Run the CreateCollection transaction140    const alicePrivateKey = privateKey('//Alice');141142    let modeprm = {};143    if (mode.type === 'NFT') {144      modeprm = {nft: null};145    } else if (mode.type === 'Fungible') {146      modeprm = {fungible: mode.decimalPoints};147    } else if (mode.type === 'ReFungible') {148      modeprm = {refungible: mode.decimalPoints};149    } else if (mode.type === 'Invalid') {150      modeprm = {invalid: null};151    }152153    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);154    const events = await submitTransactionAsync(alicePrivateKey, tx);155    const result = getCreateCollectionResult(events);156157    // Get number of collections after the transaction158    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);159160    // Get the collection161    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();162163    // What to expect164    // tslint:disable-next-line:no-unused-expression165    expect(result.success).to.be.true;166    expect(result.collectionId).to.be.equal(BcollectionCount);167    // tslint:disable-next-line:no-unused-expression168    expect(collection).to.be.not.null;169    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');170    expect(collection.Owner).to.be.equal(alicesPublicKey);171    expect(utf16ToStr(collection.Name)).to.be.equal(name);172    expect(utf16ToStr(collection.Description)).to.be.equal(description);173    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);174175    collectionId = result.collectionId;176  });177178  return collectionId;179}180181export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {182  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};183184  let modeprm = {};185  if (mode.type === 'NFT') {186    modeprm = {nft: null};187  } else if (mode.type === 'Fungible') {188    modeprm = {fungible: mode.decimalPoints};189  } else if (mode.type === 'ReFungible') {190    modeprm = {refungible: mode.decimalPoints};191  } else if (mode.type === 'Invalid') {192    modeprm = {invalid: null};193  }194195  await usingApi(async (api) => {196    // Get number of collections before the transaction197    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());198199    // Run the CreateCollection transaction200    const alicePrivateKey = privateKey('//Alice');201    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);202    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;203    const result = getCreateCollectionResult(events);204205    // Get number of collections after the transaction206    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());207208    // What to expect209    // tslint:disable-next-line:no-unused-expression210    expect(result.success).to.be.false;211    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');212  });213}214215export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {216  let bal = new BigNumber(0);217  let unused;218  do {219    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));220    const keyring = new Keyring({ type: 'sr25519' });221    unused = keyring.addFromUri(`//${randomSeed}`);222    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());223  } while (bal.toFixed() != '0');224  return unused;225}226227function getDestroyResult(events: EventRecord[]): boolean {228  let success: boolean = false;229  events.forEach(({ phase, event: { data, method, section } }) => {230    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);231    if (method == 'ExtrinsicSuccess') {232      success = true;233    }234  });235  return success;236}237238export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {239  await usingApi(async (api) => {240    // Run the DestroyCollection transaction241    const alicePrivateKey = privateKey(senderSeed);242    const tx = api.tx.nft.destroyCollection(collectionId);243    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;244  });245}246247export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {248  await usingApi(async (api) => {249    // Run the DestroyCollection transaction250    const alicePrivateKey = privateKey(senderSeed);251    const tx = api.tx.nft.destroyCollection(collectionId);252    const events = await submitTransactionAsync(alicePrivateKey, tx);253    const result = getDestroyResult(events);254255    // Get the collection256    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();257258    // What to expect259    expect(result).to.be.true;260    expect(collection).to.be.not.null;261    expect(collection.Owner).to.be.equal(nullPublicKey);262  });263}264265export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {266  await usingApi(async (api) => {267268    // Run the transaction269    const alicePrivateKey = privateKey('//Alice');270    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);271    const events = await submitTransactionAsync(alicePrivateKey, tx);272    const result = getGenericResult(events);273274    // Get the collection275    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();276277    // What to expect278    expect(result.success).to.be.true;279    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());280    expect(collection.SponsorConfirmed).to.be.false;281  });282}283284export async function removeCollectionSponsorExpectSuccess(collectionId: number) {285  await usingApi(async (api) => {286287    // Run the transaction288    const alicePrivateKey = privateKey('//Alice');289    const tx = api.tx.nft.removeCollectionSponsor(collectionId);290    const events = await submitTransactionAsync(alicePrivateKey, tx);291    const result = getGenericResult(events);292293    // Get the collection294    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();295296    // What to expect297    expect(result.success).to.be.true;298    expect(collection.Sponsor).to.be.equal(nullPublicKey);299    expect(collection.SponsorConfirmed).to.be.false;300  });301}302303export async function removeCollectionSponsorExpectFailure(collectionId: number) {304  await usingApi(async (api) => {305306    // Run the transaction307    const alicePrivateKey = privateKey('//Alice');308    const tx = api.tx.nft.removeCollectionSponsor(collectionId);309    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;310  });311}312313export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {314  await usingApi(async (api) => {315316    // Run the transaction317    const alicePrivateKey = privateKey(senderSeed);318    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);319    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;320  });321}322323export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {324  await usingApi(async (api) => {325326    // Run the transaction327    const sender = privateKey(senderSeed);328    const tx = api.tx.nft.confirmSponsorship(collectionId);329    const events = await submitTransactionAsync(sender, tx);330    const result = getGenericResult(events);331332    // Get the collection333    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();334335    // What to expect336    expect(result.success).to.be.true;337    expect(collection.Sponsor).to.be.equal(sender.address);338    expect(collection.SponsorConfirmed).to.be.true;339  });340}341342export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {343  await usingApi(async (api) => {344345    // Run the transaction346    const sender = privateKey(senderSeed);347    const tx = api.tx.nft.confirmSponsorship(collectionId);348    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;349  });350}351352export interface CreateFungibleData extends Struct {353  readonly value: u128;354}355356export interface CreateReFungibleData extends Struct {}357export interface CreateNftData extends Struct {}358359export interface CreateItemData extends Enum {360  NFT: CreateNftData;361  Fungible: CreateFungibleData;362  ReFungible: CreateReFungibleData;363}364365export async function366approveExpectSuccess(collectionId: number,367                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {368  await usingApi(async (api: ApiPromise) => {369    const allowanceBefore =370      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;371    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);372    const events = await submitTransactionAsync(owner, approveNftTx);373    const result = getCreateItemResult(events);374    // tslint:disable-next-line:no-unused-expression375    expect(result.success).to.be.true;376    const allowanceAfter =377      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;378    expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);379  });380}381382export async function383transferFromExpectSuccess(collectionId: number, tokenId: number, accountFrom: IKeyringPair,384                          accountTo: IKeyringPair, value: number = 1, type: string = 'NFT') {385  await usingApi(async (api: ApiPromise) => {386    const transferFromTx = await api.tx.nft.transferFrom(387      accountFrom.address, accountTo.address, collectionId, tokenId, value);388    const events = await submitTransactionAsync(accountFrom, transferFromTx);389    const result = getCreateItemResult(events);390    // tslint:disable-next-line:no-unused-expression391    expect(result.success).to.be.true;392    if (type === 'NFT') {393      const nftItemData = api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;394      console.log('NFT data', nftItemData);395    }396    if (type === 'Fungible') {397      const nftItemData = api.query.nft.fungibleItemList(collectionId, tokenId) as unknown as ITokenDataType;398      console.log('Fungible data', nftItemData);399    }400    if (type === 'ReFungible') {401      const nftItemData = api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as ITokenDataType;402      console.log('reFungibleItemList data', nftItemData);403    }404  });405}406407export async function408approveExpectFail(collectionId: number,409                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {410  await usingApi(async (api: ApiPromise) => {411    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);412    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;413    const result = getCreateCollectionResult(events);414    // tslint:disable-next-line:no-unused-expression415    expect(result.success).to.be.false;416  });417}418419export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {420  let newItemId: number = 0;421  await usingApi(async (api) => {422    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);423    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();424    const AItemBalance = new BigNumber(Aitem.Value);425426    if (owner === '') {427      owner = sender.address;428    }429430    let tx;431    if (createMode === 'Fungible') {432      const createData = {fungible: {value: 10}};433      tx = api.tx.nft.createItem(collectionId, owner, createData);434    } else {435      tx = api.tx.nft.createItem(collectionId, owner, createMode);436    }437    const events = await submitTransactionAsync(sender, tx);438    const result = getCreateItemResult(events);439440    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);441    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();442    const BItemBalance = new BigNumber(Bitem.Value);443444    // What to expect445    // tslint:disable-next-line:no-unused-expression446    expect(result.success).to.be.true;447    if (createMode === 'Fungible') {448      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);449    } else {450      expect(BItemCount).to.be.equal(AItemCount + 1);451    }452    expect(collectionId).to.be.equal(result.collectionId);453    expect(BItemCount).to.be.equal(result.itemId);454    newItemId = result.itemId;455  });456  return newItemId;457}458459export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {460  await usingApi(async (api) => {461462    // Run the transaction463    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');464    const events = await submitTransactionAsync(sender, tx);465    const result = getGenericResult(events);466467    // Get the collection468    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();469470    // What to expect471    expect(result.success).to.be.true;472    expect(collection.Access).to.be.equal('WhiteList');473  });474}475476export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {477  await usingApi(async (api) => {478479    // Run the transaction480    const tx = api.tx.nft.setMintPermission(collectionId, true);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.MintMode).to.be.equal(true);490  });491}492493export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {494  await usingApi(async (api) => {495496    // Run the transaction497    const tx = api.tx.nft.addToWhiteList(collectionId, address);498    const events = await submitTransactionAsync(sender, tx);499    const result = getGenericResult(events);500501    // Get the collection502    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();503504    // What to expect505    expect(result.success).to.be.true;506    expect(collection.MintMode).to.be.equal(true);507  });508}509510export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)511  : Promise<ICollectionInterface | null> => {512  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;513};514515export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {516  // set global object - collectionsCount517  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();518};