difftreelog
Merge branch 'develop' into release/v2.0.0
in: master
4 files changed
doc/application_development.mddiffbeforeafterboth--- a/doc/application_development.md
+++ b/doc/application_development.md
@@ -101,10 +101,9 @@
- Owner: Address, initial owner of the NFT
##### Events
-
-- ItemCreated
- - ItemId: Identifier of newly created NFT, which is unique within the Collection, so the NFT is uniquely
- identified with a pair of values: CollectionId and ItemId.
+ItemCreated
+ItemId: Identifier of newly created NFT, which is unique within the Collection, so the NFT is uniquely identified with a pair of values: CollectionId and ItemId.
+Recipient: Address, owner of newly created item
#### BurnItem
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -495,7 +495,9 @@
/// * collection_id: Id of the collection where item was created.
///
/// * item_id: Id of an item. Unique within the collection.
- ItemCreated(CollectionId, TokenId),
+ ///
+ /// * recipient: Owner of newly created item
+ ItemCreated(CollectionId, TokenId, AccountId),
/// Collection item was burned.
///
@@ -505,6 +507,19 @@
///
/// item_id: Identifier of burned NFT.
ItemDestroyed(CollectionId, TokenId),
+
+ /// Item was transferred
+ ///
+ /// * collection_id: Id of collection to which item is belong
+ ///
+ /// * item_id: Id of an item
+ ///
+ /// * sender: Original owner of item
+ ///
+ /// * recipient: New owner of item
+ ///
+ /// * amount: Always 1 for NFT
+ Transfer(CollectionId, TokenId, AccountId, AccountId, u128),
}
);
@@ -1556,12 +1571,14 @@
match target_collection.mode
{
- CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,
+ CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient.clone())?,
CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, value, &sender, &recipient)?,
- CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,
+ CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient.clone())?,
_ => ()
};
+ Self::deposit_event(RawEvent::Transfer(collection_id, item_id, sender, recipient, value));
+
Ok(())
}
@@ -1635,7 +1652,7 @@
{
CreateItemData::NFT(data) => {
let item = NftItemType {
- owner,
+ owner: owner.clone(),
const_data: data.const_data,
variable_data: data.variable_data
};
@@ -1660,7 +1677,7 @@
};
// call event
- Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));
Ok(())
}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -29,6 +29,7 @@
"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",
+ "testCreateItem": "mocha --timeout 9999999 -r ts-node/register ./**/createItem.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",
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;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39}4041interface IReFungibleOwner {42 Fraction: BN;43 Owner: number[];44}4546interface ITokenDataType {47 Owner: number[];48 ConstData: number[];49 VariableData: number[];50}5152interface IFungibleTokenDataType {53 Value: BN;54}5556export interface IReFungibleTokenDataType {57 Owner: IReFungibleOwner[];58 ConstData: number[];59 VariableData: number[];60}6162export function getGenericResult(events: EventRecord[]): GenericResult {63 const result: GenericResult = {64 success: false,65 };66 events.forEach(({ phase, event: { data, method, section } }) => {67 // console.log(` ${phase}: ${section}.${method}:: ${data}`);68 if (method === 'ExtrinsicSuccess') {69 result.success = true;70 }71 });72 return result;73}7475export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {76 let success = false;77 let collectionId: number = 0;78 events.forEach(({ phase, event: { data, method, section } }) => {79 // console.log(` ${phase}: ${section}.${method}:: ${data}`);80 if (method == 'ExtrinsicSuccess') {81 success = true;82 } else if ((section == 'nft') && (method == 'Created')) {83 collectionId = parseInt(data[0].toString());84 }85 });86 const result: CreateCollectionResult = {87 success,88 collectionId,89 };90 return result;91}9293export function getCreateItemResult(events: EventRecord[]): CreateItemResult {94 let success = false;95 let collectionId: number = 0;96 let itemId: number = 0;97 events.forEach(({ phase, event: { data, method, section } }) => {98 // console.log(` ${phase}: ${section}.${method}:: ${data}`);99 if (method == 'ExtrinsicSuccess') {100 success = true;101 } else if ((section == 'nft') && (method == 'ItemCreated')) {102 collectionId = parseInt(data[0].toString());103 itemId = parseInt(data[1].toString());104 }105 });106 const result: CreateItemResult = {107 success,108 collectionId,109 itemId,110 };111 return result;112}113114interface Invalid {115 type: 'Invalid';116}117118interface Nft {119 type: 'NFT';120}121122interface Fungible {123 type: 'Fungible';124 decimalPoints: number;125}126127interface ReFungible {128 type: 'ReFungible';129}130131type CollectionMode = Nft | Fungible | ReFungible | Invalid;132133export type CreateCollectionParams = {134 mode: CollectionMode,135 name: string,136 description: string,137 tokenPrefix: string,138};139140const defaultCreateCollectionParams: CreateCollectionParams = {141 description: 'description',142 mode: { type: 'NFT' },143 name: 'name',144 tokenPrefix: 'prefix',145}146147export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {148 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};149150 let collectionId: number = 0;151 await usingApi(async (api) => {152 // Get number of collections before the transaction153 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);154155 // Run the CreateCollection transaction156 const alicePrivateKey = privateKey('//Alice');157158 let modeprm = {};159 if (mode.type === 'NFT') {160 modeprm = {nft: null};161 } else if (mode.type === 'Fungible') {162 modeprm = {fungible: mode.decimalPoints};163 } else if (mode.type === 'ReFungible') {164 modeprm = {refungible: null};165 } else if (mode.type === 'Invalid') {166 modeprm = {invalid: null};167 }168169 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);170 const events = await submitTransactionAsync(alicePrivateKey, tx);171 const result = getCreateCollectionResult(events);172173 // Get number of collections after the transaction174 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);175176 // Get the collection177 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();178179 // What to expect180 // tslint:disable-next-line:no-unused-expression181 expect(result.success).to.be.true;182 expect(result.collectionId).to.be.equal(BcollectionCount);183 // tslint:disable-next-line:no-unused-expression184 expect(collection).to.be.not.null;185 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');186 expect(collection.Owner).to.be.equal(alicesPublicKey);187 expect(utf16ToStr(collection.Name)).to.be.equal(name);188 expect(utf16ToStr(collection.Description)).to.be.equal(description);189 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);190191 collectionId = result.collectionId;192 });193194 return collectionId;195}196197export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {198 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};199200 let modeprm = {};201 if (mode.type === 'NFT') {202 modeprm = {nft: null};203 } else if (mode.type === 'Fungible') {204 modeprm = {fungible: mode.decimalPoints};205 } else if (mode.type === 'ReFungible') {206 modeprm = {refungible: null};207 } else if (mode.type === 'Invalid') {208 modeprm = {invalid: null};209 }210211 await usingApi(async (api) => {212 // Get number of collections before the transaction213 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());214215 // Run the CreateCollection transaction216 const alicePrivateKey = privateKey('//Alice');217 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);218 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;219 const result = getCreateCollectionResult(events);220221 // Get number of collections after the transaction222 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());223224 // What to expect225 // tslint:disable-next-line:no-unused-expression226 expect(result.success).to.be.false;227 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');228 });229}230231export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {232 let bal = new BigNumber(0);233 let unused;234 do {235 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;236 const keyring = new Keyring({ type: 'sr25519' });237 unused = keyring.addFromUri(`//${randomSeed}`);238 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());239 } while (bal.toFixed() != '0');240 return unused;241}242243export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {244 return await usingApi(async (api) => {245 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;246 return BigInt(bn.toString());247 });248}249250export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {251 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));252}253254export async function findNotExistingCollection(api: ApiPromise): Promise<number> {255 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;256 const newCollection: number = totalNumber + 1;257 return newCollection;258}259260function getDestroyResult(events: EventRecord[]): boolean {261 let success: boolean = false;262 events.forEach(({ phase, event: { data, method, section } }) => {263 // console.log(` ${phase}: ${section}.${method}:: ${data}`);264 if (method == 'ExtrinsicSuccess') {265 success = true;266 }267 });268 return success;269}270271export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {272 await usingApi(async (api) => {273 // Run the DestroyCollection transaction274 const alicePrivateKey = privateKey(senderSeed);275 const tx = api.tx.nft.destroyCollection(collectionId);276 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;277 });278}279280export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {281 await usingApi(async (api) => {282 // Run the DestroyCollection transaction283 const alicePrivateKey = privateKey(senderSeed);284 const tx = api.tx.nft.destroyCollection(collectionId);285 const events = await submitTransactionAsync(alicePrivateKey, tx);286 const result = getDestroyResult(events);287288 // Get the collection289 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291 // What to expect292 expect(result).to.be.true;293 expect(collection).to.be.not.null;294 expect(collection.Owner).to.be.equal(nullPublicKey);295 });296}297298export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {299 await usingApi(async (api) => {300301 // Run the transaction302 const alicePrivateKey = privateKey('//Alice');303 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);304 const events = await submitTransactionAsync(alicePrivateKey, tx);305 const result = getGenericResult(events);306307 // Get the collection308 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();309310 // What to expect311 expect(result.success).to.be.true;312 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());313 expect(collection.SponsorConfirmed).to.be.false;314 });315}316317export async function removeCollectionSponsorExpectSuccess(collectionId: number) {318 await usingApi(async (api) => {319320 // Run the transaction321 const alicePrivateKey = privateKey('//Alice');322 const tx = api.tx.nft.removeCollectionSponsor(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getGenericResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result.success).to.be.true;331 expect(collection.Sponsor).to.be.equal(nullPublicKey);332 expect(collection.SponsorConfirmed).to.be.false;333 });334}335336export async function removeCollectionSponsorExpectFailure(collectionId: number) {337 await usingApi(async (api) => {338339 // Run the transaction340 const alicePrivateKey = privateKey('//Alice');341 const tx = api.tx.nft.removeCollectionSponsor(collectionId);342 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;343 });344}345346export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {347 await usingApi(async (api) => {348349 // Run the transaction350 const alicePrivateKey = privateKey(senderSeed);351 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);352 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353 });354}355356export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {357 await usingApi(async (api) => {358359 // Run the transaction360 const sender = privateKey(senderSeed);361 const tx = api.tx.nft.confirmSponsorship(collectionId);362 const events = await submitTransactionAsync(sender, tx);363 const result = getGenericResult(events);364365 // Get the collection366 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();367368 // What to expect369 expect(result.success).to.be.true;370 expect(collection.Sponsor).to.be.equal(sender.address);371 expect(collection.SponsorConfirmed).to.be.true;372 });373}374375376export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {377 await usingApi(async (api) => {378379 // Run the transaction380 const sender = privateKey(senderSeed);381 const tx = api.tx.nft.confirmSponsorship(collectionId);382 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;383 });384}385386export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {387 await usingApi(async (api) => {388 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);389 const events = await submitTransactionAsync(sender, tx);390 const result = getGenericResult(events);391392 expect(result.success).to.be.true;393 });394}395396export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {397 await usingApi(async (api) => {398 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);399 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;400 const result = getGenericResult(events);401402 expect(result.success).to.be.false;403 });404}405406export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {407 await usingApi(async (api) => {408 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);409 const events = await submitTransactionAsync(sender, tx);410 const result = getGenericResult(events);411412 expect(result.success).to.be.true;413 });414}415416export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {417 await usingApi(async (api) => {418 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);419 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;420 const result = getGenericResult(events);421422 expect(result.success).to.be.false;423 });424}425426export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {427 await usingApi(async (api) => {428 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 expect(result.success).to.be.true;433 });434}435436export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {437 let whitelisted: boolean = false;438 await usingApi(async (api) => {439 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;440 });441 return whitelisted;442}443444export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {445 await usingApi(async (api) => {446 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);447 const events = await submitTransactionAsync(sender, tx);448 const result = getGenericResult(events);449450 expect(result.success).to.be.true;451 });452}453454export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);457 const events = await submitTransactionAsync(sender, tx);458 const result = getGenericResult(events);459460 expect(result.success).to.be.true;461 });462}463464export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);467 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468 const result = getGenericResult(events);469470 expect(result.success).to.be.false;471 });472}473474export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {475 await usingApi(async (api) => {476 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));477 const events = await submitTransactionAsync(sender, tx);478 const result = getGenericResult(events);479480 expect(result.success).to.be.true;481 });482}483484export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {485 await usingApi(async (api) => {486 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));487 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488 });489}490491export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {492 await usingApi(async (api) => {493 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));494 const events = await submitTransactionAsync(sender, tx);495 const result = getGenericResult(events);496497 expect(result.success).to.be.true;498 });499}500501export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {502 await usingApi(async (api) => {503 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));504 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;505 });506}507508export interface CreateFungibleData {509 readonly Value: bigint;510}511512export interface CreateReFungibleData { }513export interface CreateNftData { }514515export type CreateItemData = {516 NFT: CreateNftData;517} | {518 Fungible: CreateFungibleData;519} | {520 ReFungible: CreateReFungibleData;521};522523export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {524 await usingApi(async (api) => {525 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);526 const events = await submitTransactionAsync(owner, tx);527 const result = getGenericResult(events);528 // Get the item529 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();530 // What to expect531 // tslint:disable-next-line:no-unused-expression532 expect(result.success).to.be.true;533 // tslint:disable-next-line:no-unused-expression534 expect(item).to.be.not.null;535 expect(item.Owner).to.be.equal(nullPublicKey);536 });537}538539export async function540approveExpectSuccess(collectionId: number,541 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {542 await usingApi(async (api: ApiPromise) => {543 const allowanceBefore =544 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;545 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);546 const events = await submitTransactionAsync(owner, approveNftTx);547 const result = getCreateItemResult(events);548 // tslint:disable-next-line:no-unused-expression549 expect(result.success).to.be.true;550 const allowanceAfter =551 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;552 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());553 });554}555556export async function557transferFromExpectSuccess(collectionId: number,558 tokenId: number,559 accountApproved: IKeyringPair,560 accountFrom: IKeyringPair,561 accountTo: IKeyringPair,562 value: number | bigint = 1,563 type: string = 'NFT') {564 await usingApi(async (api: ApiPromise) => {565 let balanceBefore = new BN(0);566 if (type === 'Fungible') {567 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;568 }569 const transferFromTx = await api.tx.nft.transferFrom(570 accountFrom.address, accountTo.address, collectionId, tokenId, value);571 const events = await submitTransactionAsync(accountApproved, transferFromTx);572 const result = getCreateItemResult(events);573 // tslint:disable-next-line:no-unused-expression574 expect(result.success).to.be.true;575 if (type === 'NFT') {576 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;577 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);578 }579 if (type === 'Fungible') {580 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;581 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());582 }583 if (type === 'ReFungible') {584 const nftItemData =585 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;586 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);587 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);588 }589 });590}591592export async function593transferFromExpectFail(collectionId: number,594 tokenId: number,595 accountApproved: IKeyringPair,596 accountFrom: IKeyringPair,597 accountTo: IKeyringPair,598 value: number | bigint = 1) {599 await usingApi(async (api: ApiPromise) => {600 const transferFromTx = await api.tx.nft.transferFrom(601 accountFrom.address, accountTo.address, collectionId, tokenId, value);602 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;603 const result = getCreateCollectionResult(events);604 // tslint:disable-next-line:no-unused-expression605 expect(result.success).to.be.false;606 });607}608609export async function610transferExpectSuccess(collectionId: number,611 tokenId: number,612 sender: IKeyringPair,613 recipient: IKeyringPair,614 value: number | bigint = 1,615 type: string = 'NFT') {616 await usingApi(async (api: ApiPromise) => {617 let balanceBefore = new BN(0);618 if (type === 'Fungible') {619 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;620 }621 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);622 const events = await submitTransactionAsync(sender, transferTx);623 const result = getCreateItemResult(events);624 // tslint:disable-next-line:no-unused-expression625 expect(result.success).to.be.true;626 if (type === 'NFT') {627 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;628 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);629 }630 if (type === 'Fungible') {631 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;632 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());633 }634 if (type === 'ReFungible') {635 const nftItemData =636 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;637 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);638 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);639 }640 });641}642643export async function644transferExpectFail(collectionId: number,645 tokenId: number,646 sender: IKeyringPair,647 recipient: IKeyringPair,648 value: number | bigint = 1,649 type: string = 'NFT') {650 await usingApi(async (api: ApiPromise) => {651 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);652 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;653 if (events && Array.isArray(events)) {654 const result = getCreateCollectionResult(events);655 // tslint:disable-next-line:no-unused-expression656 expect(result.success).to.be.false;657 }658 });659}660661export async function662approveExpectFail(collectionId: number,663 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {664 await usingApi(async (api: ApiPromise) => {665 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);666 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;667 const result = getCreateCollectionResult(events);668 // tslint:disable-next-line:no-unused-expression669 expect(result.success).to.be.false;670 });671}672673export async function getFungibleBalance(674 collectionId: number,675 owner: string,676) {677 return await usingApi(async (api) => {678 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};679 return BigInt(response.Value);680 });681}682683export async function createFungibleItemExpectSuccess(684 sender: IKeyringPair,685 collectionId: number,686 data: CreateFungibleData,687 owner: string = sender.address,688) {689 return await usingApi(async (api) => {690 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });691692 const events = await submitTransactionAsync(sender, tx);693 const result = getCreateItemResult(events);694695 expect(result.success).to.be.true;696 return result.itemId;697 });698}699700export async function createItemExpectSuccess(701 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {702 let newItemId: number = 0;703 await usingApi(async (api) => {704 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);705 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();706 const AItemBalance = new BigNumber(Aitem.Value);707708 if (owner === '') {709 owner = sender.address;710 }711712 let tx;713 if (createMode === 'Fungible') {714 const createData = {fungible: {value: 10}};715 tx = api.tx.nft.createItem(collectionId, owner, createData);716 } else if (createMode === 'ReFungible') {717 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};718 tx = api.tx.nft.createItem(collectionId, owner, createData);719 } else {720 tx = api.tx.nft.createItem(collectionId, owner, createMode);721 }722 const events = await submitTransactionAsync(sender, tx);723 const result = getCreateItemResult(events);724725 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);726 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();727 const BItemBalance = new BigNumber(Bitem.Value);728729 // What to expect730 // tslint:disable-next-line:no-unused-expression731 expect(result.success).to.be.true;732 if (createMode === 'Fungible') {733 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);734 } else {735 expect(BItemCount).to.be.equal(AItemCount + 1);736 }737 expect(collectionId).to.be.equal(result.collectionId);738 expect(BItemCount).to.be.equal(result.itemId);739 newItemId = result.itemId;740 });741 return newItemId;742}743744export async function createItemExpectFailure(745 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {746 await usingApi(async (api) => {747 const tx = api.tx.nft.createItem(collectionId, owner, createMode);748 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;749 const result = getCreateItemResult(events);750751 expect(result.success).to.be.false;752 });753}754755export async function setPublicAccessModeExpectSuccess(756 sender: IKeyringPair, collectionId: number,757 accessMode: 'Normal' | 'WhiteList',758) {759 await usingApi(async (api) => {760761 // Run the transaction762 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);763 const events = await submitTransactionAsync(sender, tx);764 const result = getGenericResult(events);765766 // Get the collection767 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();768769 // What to expect770 // tslint:disable-next-line:no-unused-expression771 expect(result.success).to.be.true;772 expect(collection.Access).to.be.equal(accessMode);773 });774}775776export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {777 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');778}779780export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {781 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');782}783784export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {785 await usingApi(async (api) => {786787 // Run the transaction788 const tx = api.tx.nft.setMintPermission(collectionId, enabled);789 const events = await submitTransactionAsync(sender, tx);790 const result = getGenericResult(events);791792 // Get the collection793 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();794795 // What to expect796 // tslint:disable-next-line:no-unused-expression797 expect(result.success).to.be.true;798 expect(collection.MintMode).to.be.equal(enabled);799 });800}801802export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {803 await setMintPermissionExpectSuccess(sender, collectionId, true);804}805806export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {807 await usingApi(async (api) => {808 // Run the transaction809 const tx = api.tx.nft.setMintPermission(collectionId, enabled);810 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;811 const result = getCreateCollectionResult(events);812 // tslint:disable-next-line:no-unused-expression813 expect(result.success).to.be.false;814 });815}816817export async function isWhitelisted(collectionId: number, address: string) {818 let whitelisted: boolean = false;819 await usingApi(async (api) => {820 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;821 });822 return whitelisted;823}824825export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {826 await usingApi(async (api) => {827828 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();829830 // Run the transaction831 const tx = api.tx.nft.addToWhiteList(collectionId, address);832 const events = await submitTransactionAsync(sender, tx);833 const result = getGenericResult(events);834835 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();836837 // What to expect838 // tslint:disable-next-line:no-unused-expression839 expect(result.success).to.be.true;840 // tslint:disable-next-line: no-unused-expression841 expect(whiteListedBefore).to.be.false;842 // tslint:disable-next-line: no-unused-expression843 expect(whiteListedAfter).to.be.true;844 });845}846847export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {848 await usingApi(async (api) => {849 // Run the transaction850 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);851 const events = await submitTransactionAsync(sender, tx);852 const result = getGenericResult(events);853854 // What to expect855 // tslint:disable-next-line:no-unused-expression856 expect(result.success).to.be.true;857 });858}859860export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {861 await usingApi(async (api) => {862 // Run the transaction863 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);864 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;865 const result = getGenericResult(events);866867 // What to expect868 // tslint:disable-next-line:no-unused-expression869 expect(result.success).to.be.false;870 });871}872873export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)874 : Promise<ICollectionInterface | null> => {875 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;876};877878export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {879 // set global object - collectionsCount880 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();881};882883export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {884 return await usingApi(async (api) => {885 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;886 });887}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;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566export interface IReFungibleTokenDataType {67 Owner: IReFungibleOwner[];68 ConstData: number[];69 VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73 const result: GenericResult = {74 success: false,75 };76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method === 'ExtrinsicSuccess') {79 result.success = true;80 }81 });82 return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86 let success = false;87 let collectionId: number = 0;88 events.forEach(({ phase, event: { data, method, section } }) => {89 // console.log(` ${phase}: ${section}.${method}:: ${data}`);90 if (method == 'ExtrinsicSuccess') {91 success = true;92 } else if ((section == 'nft') && (method == 'Created')) {93 collectionId = parseInt(data[0].toString());94 }95 });96 const result: CreateCollectionResult = {97 success,98 collectionId,99 };100 return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104 let success = false;105 let collectionId: number = 0;106 let itemId: number = 0;107 let recipient: string = '';108 events.forEach(({ phase, event: { data, method, section } }) => {109 // console.log(` ${phase}: ${section}.${method}:: ${data}`);110 if (method == 'ExtrinsicSuccess') {111 success = true;112 } else if ((section == 'nft') && (method == 'ItemCreated')) {113 collectionId = parseInt(data[0].toString());114 itemId = parseInt(data[1].toString());115 recipient = data[2].toString();116 }117 });118 const result: CreateItemResult = {119 success,120 collectionId,121 itemId,122 recipient,123 };124 return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128 const result: TransferResult = {129 success: false,130 collectionId: 0,131 itemId: 0,132 sender: '',133 recipient: '',134 value: 0n,135 };136137 events.forEach(({event: {data, method, section}}) => {138 if (method === 'ExtrinsicSuccess') {139 result.success = true;140 } else if (section === 'nft' && method === 'Transfer') {141 result.collectionId = +data[0].toString();142 result.itemId = +data[1].toString();143 result.sender = data[2].toString();144 result.recipient = data[3].toString();145 result.value = BigInt(data[4].toString());146 }147 });148149 return result;150}151152interface Invalid {153 type: 'Invalid';154}155156interface Nft {157 type: 'NFT';158}159160interface Fungible {161 type: 'Fungible';162 decimalPoints: number;163}164165interface ReFungible {166 type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172 mode: CollectionMode,173 name: string,174 description: string,175 tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179 description: 'description',180 mode: { type: 'NFT' },181 name: 'name',182 tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188 let collectionId: number = 0;189 await usingApi(async (api) => {190 // Get number of collections before the transaction191 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193 // Run the CreateCollection transaction194 const alicePrivateKey = privateKey('//Alice');195196 let modeprm = {};197 if (mode.type === 'NFT') {198 modeprm = {nft: null};199 } else if (mode.type === 'Fungible') {200 modeprm = {fungible: mode.decimalPoints};201 } else if (mode.type === 'ReFungible') {202 modeprm = {refungible: null};203 } else if (mode.type === 'Invalid') {204 modeprm = {invalid: null};205 }206207 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208 const events = await submitTransactionAsync(alicePrivateKey, tx);209 const result = getCreateCollectionResult(events);210211 // Get number of collections after the transaction212 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214 // Get the collection215 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217 // What to expect218 // tslint:disable-next-line:no-unused-expression219 expect(result.success).to.be.true;220 expect(result.collectionId).to.be.equal(BcollectionCount);221 // tslint:disable-next-line:no-unused-expression222 expect(collection).to.be.not.null;223 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224 expect(collection.Owner).to.be.equal(alicesPublicKey);225 expect(utf16ToStr(collection.Name)).to.be.equal(name);226 expect(utf16ToStr(collection.Description)).to.be.equal(description);227 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229 collectionId = result.collectionId;230 });231232 return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238 let modeprm = {};239 if (mode.type === 'NFT') {240 modeprm = {nft: null};241 } else if (mode.type === 'Fungible') {242 modeprm = {fungible: mode.decimalPoints};243 } else if (mode.type === 'ReFungible') {244 modeprm = {refungible: null};245 } else if (mode.type === 'Invalid') {246 modeprm = {invalid: null};247 }248249 await usingApi(async (api) => {250 // Get number of collections before the transaction251 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253 // Run the CreateCollection transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 const result = getCreateCollectionResult(events);258259 // Get number of collections after the transaction260 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262 // What to expect263 // tslint:disable-next-line:no-unused-expression264 expect(result.success).to.be.false;265 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266 });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270 let bal = new BigNumber(0);271 let unused;272 do {273 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274 const keyring = new Keyring({ type: 'sr25519' });275 unused = keyring.addFromUri(`//${randomSeed}`);276 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277 } while (bal.toFixed() != '0');278 return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282 return await usingApi(async (api) => {283 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284 return BigInt(bn.toString());285 });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294 const newCollection: number = totalNumber + 1;295 return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299 let success: boolean = false;300 events.forEach(({ phase, event: { data, method, section } }) => {301 // console.log(` ${phase}: ${section}.${method}:: ${data}`);302 if (method == 'ExtrinsicSuccess') {303 success = true;304 }305 });306 return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310 await usingApi(async (api) => {311 // Run the DestroyCollection transaction312 const alicePrivateKey = privateKey(senderSeed);313 const tx = api.tx.nft.destroyCollection(collectionId);314 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315 });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319 await usingApi(async (api) => {320 // Run the DestroyCollection transaction321 const alicePrivateKey = privateKey(senderSeed);322 const tx = api.tx.nft.destroyCollection(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getDestroyResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.not.null;332 expect(collection.Owner).to.be.equal(nullPublicKey);333 });334}335336export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {337 await usingApi(async (api) => {338339 // Run the transaction340 const alicePrivateKey = privateKey('//Alice');341 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);342 const events = await submitTransactionAsync(alicePrivateKey, tx);343 const result = getGenericResult(events);344345 // Get the collection346 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();347348 // What to expect349 expect(result.success).to.be.true;350 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());351 expect(collection.SponsorConfirmed).to.be.false;352 });353}354355export async function removeCollectionSponsorExpectSuccess(collectionId: number) {356 await usingApi(async (api) => {357358 // Run the transaction359 const alicePrivateKey = privateKey('//Alice');360 const tx = api.tx.nft.removeCollectionSponsor(collectionId);361 const events = await submitTransactionAsync(alicePrivateKey, tx);362 const result = getGenericResult(events);363364 // Get the collection365 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();366367 // What to expect368 expect(result.success).to.be.true;369 expect(collection.Sponsor).to.be.equal(nullPublicKey);370 expect(collection.SponsorConfirmed).to.be.false;371 });372}373374export async function removeCollectionSponsorExpectFailure(collectionId: number) {375 await usingApi(async (api) => {376377 // Run the transaction378 const alicePrivateKey = privateKey('//Alice');379 const tx = api.tx.nft.removeCollectionSponsor(collectionId);380 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;381 });382}383384export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {385 await usingApi(async (api) => {386387 // Run the transaction388 const alicePrivateKey = privateKey(senderSeed);389 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);390 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;391 });392}393394export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {395 await usingApi(async (api) => {396397 // Run the transaction398 const sender = privateKey(senderSeed);399 const tx = api.tx.nft.confirmSponsorship(collectionId);400 const events = await submitTransactionAsync(sender, tx);401 const result = getGenericResult(events);402403 // Get the collection404 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();405406 // What to expect407 expect(result.success).to.be.true;408 expect(collection.Sponsor).to.be.equal(sender.address);409 expect(collection.SponsorConfirmed).to.be.true;410 });411}412413414export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {415 await usingApi(async (api) => {416417 // Run the transaction418 const sender = privateKey(senderSeed);419 const tx = api.tx.nft.confirmSponsorship(collectionId);420 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;421 });422}423424export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {425 await usingApi(async (api) => {426 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);427 const events = await submitTransactionAsync(sender, tx);428 const result = getGenericResult(events);429430 expect(result.success).to.be.true;431 });432}433434export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {435 await usingApi(async (api) => {436 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);437 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438 const result = getGenericResult(events);439440 expect(result.success).to.be.false;441 });442}443444export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {445 await usingApi(async (api) => {446 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);447 const events = await submitTransactionAsync(sender, tx);448 const result = getGenericResult(events);449450 expect(result.success).to.be.true;451 });452}453454export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);457 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;458 const result = getGenericResult(events);459460 expect(result.success).to.be.false;461 });462}463464export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);467 const events = await submitTransactionAsync(sender, tx);468 const result = getGenericResult(events);469470 expect(result.success).to.be.true;471 });472}473474export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {475 let whitelisted: boolean = false;476 await usingApi(async (api) => {477 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;478 });479 return whitelisted;480}481482export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {483 await usingApi(async (api) => {484 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);485 const events = await submitTransactionAsync(sender, tx);486 const result = getGenericResult(events);487488 expect(result.success).to.be.true;489 });490}491492export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {493 await usingApi(async (api) => {494 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);495 const events = await submitTransactionAsync(sender, tx);496 const result = getGenericResult(events);497498 expect(result.success).to.be.true;499 });500}501502export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {503 await usingApi(async (api) => {504 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);505 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;506 const result = getGenericResult(events);507508 expect(result.success).to.be.false;509 });510}511512export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {513 await usingApi(async (api) => {514 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));515 const events = await submitTransactionAsync(sender, tx);516 const result = getGenericResult(events);517518 expect(result.success).to.be.true;519 });520}521522export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {523 await usingApi(async (api) => {524 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));525 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;526 });527}528529export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {530 await usingApi(async (api) => {531 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));532 const events = await submitTransactionAsync(sender, tx);533 const result = getGenericResult(events);534535 expect(result.success).to.be.true;536 });537}538539export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {540 await usingApi(async (api) => {541 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));542 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;543 });544}545546export interface CreateFungibleData {547 readonly Value: bigint;548}549550export interface CreateReFungibleData { }551export interface CreateNftData { }552553export type CreateItemData = {554 NFT: CreateNftData;555} | {556 Fungible: CreateFungibleData;557} | {558 ReFungible: CreateReFungibleData;559};560561export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {562 await usingApi(async (api) => {563 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);564 const events = await submitTransactionAsync(owner, tx);565 const result = getGenericResult(events);566 // Get the item567 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();568 // What to expect569 // tslint:disable-next-line:no-unused-expression570 expect(result.success).to.be.true;571 // tslint:disable-next-line:no-unused-expression572 expect(item).to.be.not.null;573 expect(item.Owner).to.be.equal(nullPublicKey);574 });575}576577export async function578approveExpectSuccess(collectionId: number,579 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {580 await usingApi(async (api: ApiPromise) => {581 const allowanceBefore =582 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;583 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);584 const events = await submitTransactionAsync(owner, approveNftTx);585 const result = getCreateItemResult(events);586 // tslint:disable-next-line:no-unused-expression587 expect(result.success).to.be.true;588 const allowanceAfter =589 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;590 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());591 });592}593594export async function595transferFromExpectSuccess(collectionId: number,596 tokenId: number,597 accountApproved: IKeyringPair,598 accountFrom: IKeyringPair,599 accountTo: IKeyringPair,600 value: number | bigint = 1,601 type: string = 'NFT') {602 await usingApi(async (api: ApiPromise) => {603 let balanceBefore = new BN(0);604 if (type === 'Fungible') {605 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;606 }607 const transferFromTx = await api.tx.nft.transferFrom(608 accountFrom.address, accountTo.address, collectionId, tokenId, value);609 const events = await submitTransactionAsync(accountApproved, transferFromTx);610 const result = getCreateItemResult(events);611 // tslint:disable-next-line:no-unused-expression612 expect(result.success).to.be.true;613 if (type === 'NFT') {614 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;615 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);616 }617 if (type === 'Fungible') {618 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;619 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());620 }621 if (type === 'ReFungible') {622 const nftItemData =623 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;624 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);625 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);626 }627 });628}629630export async function631transferFromExpectFail(collectionId: number,632 tokenId: number,633 accountApproved: IKeyringPair,634 accountFrom: IKeyringPair,635 accountTo: IKeyringPair,636 value: number | bigint = 1) {637 await usingApi(async (api: ApiPromise) => {638 const transferFromTx = await api.tx.nft.transferFrom(639 accountFrom.address, accountTo.address, collectionId, tokenId, value);640 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;641 const result = getCreateCollectionResult(events);642 // tslint:disable-next-line:no-unused-expression643 expect(result.success).to.be.false;644 });645}646647export async function648transferExpectSuccess(collectionId: number,649 tokenId: number,650 sender: IKeyringPair,651 recipient: IKeyringPair,652 value: number | bigint = 1,653 type: string = 'NFT') {654 await usingApi(async (api: ApiPromise) => {655 let balanceBefore = new BN(0);656 if (type === 'Fungible') {657 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;658 }659 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);660 const events = await submitTransactionAsync(sender, transferTx);661 const result = getTransferResult(events);662 // tslint:disable-next-line:no-unused-expression663 expect(result.success).to.be.true;664 expect(result.collectionId).to.be.equal(collectionId);665 expect(result.itemId).to.be.equal(tokenId);666 expect(result.sender).to.be.equal(sender.address);667 expect(result.recipient).to.be.equal(recipient.address);668 expect(result.value.toString()).to.be.equal(value.toString());669 if (type === 'NFT') {670 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;671 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);672 }673 if (type === 'Fungible') {674 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;675 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());676 }677 if (type === 'ReFungible') {678 const nftItemData =679 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;680 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);681 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);682 }683 });684}685686export async function687transferExpectFail(collectionId: number,688 tokenId: number,689 sender: IKeyringPair,690 recipient: IKeyringPair,691 value: number | bigint = 1,692 type: string = 'NFT') {693 await usingApi(async (api: ApiPromise) => {694 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);695 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;696 if (events && Array.isArray(events)) {697 const result = getCreateCollectionResult(events);698 // tslint:disable-next-line:no-unused-expression699 expect(result.success).to.be.false;700 }701 });702}703704export async function705approveExpectFail(collectionId: number,706 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {707 await usingApi(async (api: ApiPromise) => {708 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);709 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;710 const result = getCreateCollectionResult(events);711 // tslint:disable-next-line:no-unused-expression712 expect(result.success).to.be.false;713 });714}715716export async function getFungibleBalance(717 collectionId: number,718 owner: string,719) {720 return await usingApi(async (api) => {721 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};722 return BigInt(response.Value);723 });724}725726export async function createFungibleItemExpectSuccess(727 sender: IKeyringPair,728 collectionId: number,729 data: CreateFungibleData,730 owner: string = sender.address,731) {732 return await usingApi(async (api) => {733 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });734735 const events = await submitTransactionAsync(sender, tx);736 const result = getCreateItemResult(events);737738 expect(result.success).to.be.true;739 return result.itemId;740 });741}742743export async function createItemExpectSuccess(744 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {745 let newItemId: number = 0;746 await usingApi(async (api) => {747 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);748 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();749 const AItemBalance = new BigNumber(Aitem.Value);750751 if (owner === '') {752 owner = sender.address;753 }754755 let tx;756 if (createMode === 'Fungible') {757 const createData = {fungible: {value: 10}};758 tx = api.tx.nft.createItem(collectionId, owner, createData);759 } else if (createMode === 'ReFungible') {760 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};761 tx = api.tx.nft.createItem(collectionId, owner, createData);762 } else {763 tx = api.tx.nft.createItem(collectionId, owner, createMode);764 }765 const events = await submitTransactionAsync(sender, tx);766 const result = getCreateItemResult(events);767768 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);769 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();770 const BItemBalance = new BigNumber(Bitem.Value);771772 // What to expect773 // tslint:disable-next-line:no-unused-expression774 expect(result.success).to.be.true;775 if (createMode === 'Fungible') {776 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);777 } else {778 expect(BItemCount).to.be.equal(AItemCount + 1);779 }780 expect(collectionId).to.be.equal(result.collectionId);781 expect(BItemCount).to.be.equal(result.itemId);782 expect(owner).to.be.equal(result.recipient);783 newItemId = result.itemId;784 });785 return newItemId;786}787788export async function createItemExpectFailure(789 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {790 await usingApi(async (api) => {791 const tx = api.tx.nft.createItem(collectionId, owner, createMode);792 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793 const result = getCreateItemResult(events);794795 expect(result.success).to.be.false;796 });797}798799export async function setPublicAccessModeExpectSuccess(800 sender: IKeyringPair, collectionId: number,801 accessMode: 'Normal' | 'WhiteList',802) {803 await usingApi(async (api) => {804805 // Run the transaction806 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);807 const events = await submitTransactionAsync(sender, tx);808 const result = getGenericResult(events);809810 // Get the collection811 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();812813 // What to expect814 // tslint:disable-next-line:no-unused-expression815 expect(result.success).to.be.true;816 expect(collection.Access).to.be.equal(accessMode);817 });818}819820export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {821 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');822}823824export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {825 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');826}827828export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {829 await usingApi(async (api) => {830831 // Run the transaction832 const tx = api.tx.nft.setMintPermission(collectionId, enabled);833 const events = await submitTransactionAsync(sender, tx);834 const result = getGenericResult(events);835836 // Get the collection837 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();838839 // What to expect840 // tslint:disable-next-line:no-unused-expression841 expect(result.success).to.be.true;842 expect(collection.MintMode).to.be.equal(enabled);843 });844}845846export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {847 await setMintPermissionExpectSuccess(sender, collectionId, true);848}849850export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {851 await usingApi(async (api) => {852 // Run the transaction853 const tx = api.tx.nft.setMintPermission(collectionId, enabled);854 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;855 const result = getCreateCollectionResult(events);856 // tslint:disable-next-line:no-unused-expression857 expect(result.success).to.be.false;858 });859}860861export async function isWhitelisted(collectionId: number, address: string) {862 let whitelisted: boolean = false;863 await usingApi(async (api) => {864 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;865 });866 return whitelisted;867}868869export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {870 await usingApi(async (api) => {871872 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();873874 // Run the transaction875 const tx = api.tx.nft.addToWhiteList(collectionId, address);876 const events = await submitTransactionAsync(sender, tx);877 const result = getGenericResult(events);878879 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();880881 // What to expect882 // tslint:disable-next-line:no-unused-expression883 expect(result.success).to.be.true;884 // tslint:disable-next-line: no-unused-expression885 expect(whiteListedBefore).to.be.false;886 // tslint:disable-next-line: no-unused-expression887 expect(whiteListedAfter).to.be.true;888 });889}890891export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {892 await usingApi(async (api) => {893 // Run the transaction894 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);895 const events = await submitTransactionAsync(sender, tx);896 const result = getGenericResult(events);897898 // What to expect899 // tslint:disable-next-line:no-unused-expression900 expect(result.success).to.be.true;901 });902}903904export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {905 await usingApi(async (api) => {906 // Run the transaction907 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);908 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;909 const result = getGenericResult(events);910911 // What to expect912 // tslint:disable-next-line:no-unused-expression913 expect(result.success).to.be.false;914 });915}916917export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)918 : Promise<ICollectionInterface | null> => {919 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;920};921922export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {923 // set global object - collectionsCount924 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();925};926927export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {928 return await usingApi(async (api) => {929 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;930 });931}