difftreelog
CORE-325 Make test to check supprot ERC721Metadata
in: master
2 files changed
tests/src/eth/metadata.test.tsdiffbeforeafterboth--- a/tests/src/eth/metadata.test.ts
+++ b/tests/src/eth/metadata.test.ts
@@ -16,8 +16,11 @@
import {expect} from 'chai';
import {createCollectionExpectSuccess} from '../util/helpers';
-import {collectionIdToAddress, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from './util/helpers';
import fungibleMetadataAbi from './fungibleMetadataAbi.json';
+import privateKey from '../substrate/privateKey';
+import {submitTransactionAsync} from '../substrate/substrate-api';
+import nonFungibleAbi from './nonFungibleAbi.json';
describe('Common metadata', () => {
itWeb3('Returns collection name', async ({api, web3}) => {
@@ -62,4 +65,94 @@
expect(+decimals).to.equal(6);
});
-});
\ No newline at end of file
+});
+
+describe.only('Support ERC721Metadata', () => {
+ itWeb3('Check unsupport ERC721Metadata ShemaVersion::Unique', async ({web3, api}) => {
+ const collectionId = await createCollectionExpectSuccess({
+ mode: {type: 'NFT'},
+ shemaVersion: 'Unique',
+ });
+ const collection = await api.rpc.unique.collectionById(collectionId);
+ expect(collection.isSome).to.be.true;
+ expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('Unique');
+
+ const alice = privateKey('//Alice');
+
+ const caller = await createEthAccountWithBalance(api, web3);
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ const address = collectionIdToAddress(collectionId);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ await expect(contract.methods.name().call()).to.be.rejectedWith('Unsupported shema version! Support only ImageURL');
+ await expect(contract.methods.symbol().call()).to.be.rejectedWith('Unsupported shema version! Support only ImageURL');
+
+ const receiver = createEthAccount(web3);
+ const nextTokenId = await contract.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+ await expect(contract.methods.mintWithTokenURI(
+ receiver,
+ nextTokenId,
+ 'Test URI',
+ ).send({from: caller})).to.be.rejected;
+
+ await expect(contract.methods.mintBulkWithTokenURI(
+ receiver,
+ [
+ [nextTokenId, 'Test URI 0'],
+ [+nextTokenId + 1, 'Test URI 1'],
+ [+nextTokenId + 2, 'Test URI 2'],
+ ],
+ ).send({from: caller})).to.be.rejected;
+ });
+
+ itWeb3('Check support ERC721Metadata for ShemaVersion::ImageURL', async ({web3, api}) => {
+ const collectionId = await createCollectionExpectSuccess({
+ mode: {type: 'NFT'},
+ name: 'some_name',
+ tokenPrefix: 'some_prefix',
+ });
+ const collection = await api.rpc.unique.collectionById(collectionId);
+ expect(collection.isSome).to.be.true;
+ expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('ImageURL');
+
+ const alice = privateKey('//Alice');
+
+ const caller = await createEthAccountWithBalance(api, web3);
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ const address = collectionIdToAddress(collectionId);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ expect(await contract.methods.name().call()).to.be.eq('some_name');
+ expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
+
+ const receiver = createEthAccount(web3);
+ const nextTokenId = await contract.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+ const result = await contract.methods.mintWithTokenURI(
+ receiver,
+ nextTokenId,
+ 'Test URI',
+ ).send({from: caller});
+ const events = normalizeEvents(result.events);
+
+ expect(events).to.be.deep.equal([
+ {
+ address,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: receiver,
+ tokenId: nextTokenId,
+ },
+ },
+ ]);
+
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ });
+});
+
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 // console.log(` ${phase}: ${section}.${method}:: ${data}`);191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209 events.forEach(({event: {data, method, section}}) => {210 // console.log(` ${phase}: ${section}.${method}:: ${data}`);211 if (method == 'ExtrinsicSuccess') {212 success = true;213 } else if ((section == 'common') && (method == 'ItemCreated')) {214 collectionId = parseInt(data[0].toString(), 10);215 itemId = parseInt(data[1].toString(), 10);216 recipient = normalizeAccountId(data[2].toJSON() as any);217 }218 });219 const result: CreateItemResult = {220 success,221 collectionId,222 itemId,223 recipient,224 };225 return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229 const result: TransferResult = {230 success: false,231 collectionId: 0,232 itemId: 0,233 value: 0n,234 };235236 events.forEach(({event: {data, method, section}}) => {237 if (method === 'ExtrinsicSuccess') {238 result.success = true;239 } else if (section === 'common' && method === 'Transfer') {240 result.collectionId = +data[0].toString();241 result.itemId = +data[1].toString();242 result.sender = normalizeAccountId(data[2].toJSON() as any);243 result.recipient = normalizeAccountId(data[3].toJSON() as any);244 result.value = BigInt(data[4].toString());245 }246 });247248 return result;249}250251interface Nft {252 type: 'NFT';253}254255interface Fungible {256 type: 'Fungible';257 decimalPoints: number;258}259260interface ReFungible {261 type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267 mode: CollectionMode,268 name: string,269 description: string,270 tokenPrefix: string,271};272273const defaultCreateCollectionParams: CreateCollectionParams = {274 description: 'description',275 mode: {type: 'NFT'},276 name: 'name',277 tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};282283 let collectionId = 0;284 await usingApi(async (api) => {285 // Get number of collections before the transaction286 const collectionCountBefore = await getCreatedCollectionCount(api);287288 // Run the CreateCollection transaction289 const alicePrivateKey = privateKey('//Alice');290291 let modeprm = {};292 if (mode.type === 'NFT') {293 modeprm = {nft: null};294 } else if (mode.type === 'Fungible') {295 modeprm = {fungible: mode.decimalPoints};296 } else if (mode.type === 'ReFungible') {297 modeprm = {refungible: null};298 }299300 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301 const events = await submitTransactionAsync(alicePrivateKey, tx);302 const result = getCreateCollectionResult(events);303304 // Get number of collections after the transaction305 const collectionCountAfter = await getCreatedCollectionCount(api);306307 // Get the collection308 const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310 // What to expect311 // tslint:disable-next-line:no-unused-expression312 expect(result.success).to.be.true;313 expect(result.collectionId).to.be.equal(collectionCountAfter);314 // tslint:disable-next-line:no-unused-expression315 expect(collection).to.be.not.null;316 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322 collectionId = result.collectionId;323 });324325 return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331 let modeprm = {};332 if (mode.type === 'NFT') {333 modeprm = {nft: null};334 } else if (mode.type === 'Fungible') {335 modeprm = {fungible: mode.decimalPoints};336 } else if (mode.type === 'ReFungible') {337 modeprm = {refungible: null};338 }339340 await usingApi(async (api) => {341 // Get number of collections before the transaction342 const collectionCountBefore = await getCreatedCollectionCount(api);343344 // Run the CreateCollection transaction345 const alicePrivateKey = privateKey('//Alice');346 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348 const result = getCreateCollectionResult(events);349350 // Get number of collections after the transaction351 const collectionCountAfter = await getCreatedCollectionCount(api);352353 // What to expect354 // tslint:disable-next-line:no-unused-expression355 expect(result.success).to.be.false;356 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');357 });358}359360export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {361 let bal = 0n;362 let unused;363 do {364 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;365 const keyring = new Keyring({type: 'sr25519'});366 unused = keyring.addFromUri(`//${randomSeed}`);367 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();368 } while (bal !== 0n);369 return unused;370}371372export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {373 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();374}375376export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {377 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));378}379380export async function findNotExistingCollection(api: ApiPromise): Promise<number> {381 const totalNumber = await getCreatedCollectionCount(api);382 const newCollection: number = totalNumber + 1;383 return newCollection;384}385386function getDestroyResult(events: EventRecord[]): boolean {387 let success = false;388 events.forEach(({event: {method}}) => {389 if (method == 'ExtrinsicSuccess') {390 success = true;391 }392 });393 return success;394}395396export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {397 await usingApi(async (api) => {398 // Run the DestroyCollection transaction399 const alicePrivateKey = privateKey(senderSeed);400 const tx = api.tx.unique.destroyCollection(collectionId);401 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;402 });403}404405export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {406 await usingApi(async (api) => {407 // Run the DestroyCollection transaction408 const alicePrivateKey = privateKey(senderSeed);409 const tx = api.tx.unique.destroyCollection(collectionId);410 const events = await submitTransactionAsync(alicePrivateKey, tx);411 const result = getDestroyResult(events);412 expect(result).to.be.true;413414 // What to expect415 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;416 });417}418419export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {420 await usingApi(async (api) => {421 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);422 const events = await submitTransactionAsync(sender, tx);423 const result = getGenericResult(events);424425 expect(result.success).to.be.true;426 });427}428429export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {430 await usingApi(async (api) => {431 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433 const result = getGenericResult(events);434435 expect(result.success).to.be.false;436 });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440 await usingApi(async (api) => {441442 // Run the transaction443 const senderPrivateKey = privateKey(sender);444 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);445 const events = await submitTransactionAsync(senderPrivateKey, tx);446 const result = getGenericResult(events);447448 // Get the collection449 const collection = await queryCollectionExpectSuccess(api, collectionId);450451 // What to expect452 expect(result.success).to.be.true;453 expect(collection.sponsorship.toJSON()).to.deep.equal({454 unconfirmed: sponsor,455 });456 });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460 await usingApi(async (api) => {461462 // Run the transaction463 const alicePrivateKey = privateKey(sender);464 const tx = api.tx.unique.removeCollectionSponsor(collectionId);465 const events = await submitTransactionAsync(alicePrivateKey, tx);466 const result = getGenericResult(events);467468 // Get the collection469 const collection = await queryCollectionExpectSuccess(api, collectionId);470471 // What to expect472 expect(result.success).to.be.true;473 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});474 });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478 await usingApi(async (api) => {479480 // Run the transaction481 const alicePrivateKey = privateKey(senderSeed);482 const tx = api.tx.unique.removeCollectionSponsor(collectionId);483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484 });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488 await usingApi(async (api) => {489490 // Run the transaction491 const alicePrivateKey = privateKey(senderSeed);492 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);493 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494 });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498 await usingApi(async (api) => {499500 // Run the transaction501 const sender = privateKey(senderSeed);502 const tx = api.tx.unique.confirmSponsorship(collectionId);503 const events = await submitTransactionAsync(sender, tx);504 const result = getGenericResult(events);505506 // Get the collection507 const collection = await queryCollectionExpectSuccess(api, collectionId);508509 // What to expect510 expect(result.success).to.be.true;511 expect(collection.sponsorship.toJSON()).to.be.deep.equal({512 confirmed: sender.address,513 });514 });515}516517518export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {519 await usingApi(async (api) => {520521 // Run the transaction522 const sender = privateKey(senderSeed);523 const tx = api.tx.unique.confirmSponsorship(collectionId);524 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525 });526}527528export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {529530 await usingApi(async (api) => {531 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);532 const events = await submitTransactionAsync(sender, tx);533 const result = getGenericResult(events);534535 expect(result.success).to.be.true;536 });537}538539export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {540541 await usingApi(async (api) => {542 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);543 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;544 const result = getGenericResult(events);545546 expect(result.success).to.be.false;547 });548}549550export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {551 await usingApi(async (api) => {552 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);553 const events = await submitTransactionAsync(sender, tx);554 const result = getGenericResult(events);555556 expect(result.success).to.be.true;557 });558}559560export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {561 await usingApi(async (api) => {562 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);563 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;564 const result = getGenericResult(events);565566 expect(result.success).to.be.false;567 });568}569570export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {571572 await usingApi(async (api) => {573574 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);575 const events = await submitTransactionAsync(sender, tx);576 const result = getGenericResult(events);577578 expect(result.success).to.be.true;579 });580}581582export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {583584 await usingApi(async (api) => {585586 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);587 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588 const result = getGenericResult(events);589590 expect(result.success).to.be.false;591 });592}593594export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {595 await usingApi(async (api) => {596 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);597 const events = await submitTransactionAsync(sender, tx);598 const result = getGenericResult(events);599600 expect(result.success).to.be.true;601 });602}603604export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {605 await usingApi(async (api) => {606 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);607 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608 const result = getGenericResult(events);609610 expect(result.success).to.be.false;611 });612}613614export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {615 await usingApi(async (api) => {616 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);617 const events = await submitTransactionAsync(sender, tx);618 const result = getGenericResult(events);619620 expect(result.success).to.be.true;621 });622}623624export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {625 let allowlisted = false;626 await usingApi(async (api) => {627 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;628 });629 return allowlisted;630}631632export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {633 await usingApi(async (api) => {634 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());635 const events = await submitTransactionAsync(sender, tx);636 const result = getGenericResult(events);637638 expect(result.success).to.be.true;639 });640}641642export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {643 await usingApi(async (api) => {644 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());645 const events = await submitTransactionAsync(sender, tx);646 const result = getGenericResult(events);647648 expect(result.success).to.be.true;649 });650}651652export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {653 await usingApi(async (api) => {654 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656 const result = getGenericResult(events);657658 expect(result.success).to.be.false;659 });660}661662export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {663 await usingApi(async (api) => {664 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));665 const events = await submitTransactionAsync(sender, tx);666 const result = getGenericResult(events);667668 expect(result.success).to.be.true;669 });670}671672export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {673 await usingApi(async (api) => {674 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));675 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;676 });677}678679export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {680 await usingApi(async (api) => {681 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));682 const events = await submitTransactionAsync(sender, tx);683 const result = getGenericResult(events);684685 expect(result.success).to.be.true;686 });687}688689export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {690 await usingApi(async (api) => {691 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));692 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;693 });694}695696export interface CreateFungibleData {697 readonly Value: bigint;698}699700export interface CreateReFungibleData { }701export interface CreateNftData { }702703export type CreateItemData = {704 NFT: CreateNftData;705} | {706 Fungible: CreateFungibleData;707} | {708 ReFungible: CreateReFungibleData;709};710711export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {712 await usingApi(async (api) => {713 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);714 // if burning token by admin - use adminButnItemExpectSuccess715 expect(balanceBefore >= BigInt(value)).to.be.true;716717 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);718 const events = await submitTransactionAsync(sender, tx);719 const result = getGenericResult(events);720 expect(result.success).to.be.true;721722 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);723 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);724 });725}726727export async function728approveExpectSuccess(729 collectionId: number,730 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732 await usingApi(async (api: ApiPromise) => {733 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734 const events = await submitTransactionAsync(owner, approveUniqueTx);735 const result = getGenericResult(events);736 expect(result.success).to.be.true;737738 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));739 });740}741742export async function adminApproveFromExpectSuccess(743 collectionId: number,744 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,745) {746 await usingApi(async (api: ApiPromise) => {747 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);748 const events = await submitTransactionAsync(admin, approveUniqueTx);749 const result = getGenericResult(events);750 expect(result.success).to.be.true;751752 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));753 });754}755756export async function757transferFromExpectSuccess(758 collectionId: number,759 tokenId: number,760 accountApproved: IKeyringPair,761 accountFrom: IKeyringPair | CrossAccountId,762 accountTo: IKeyringPair | CrossAccountId,763 value: number | bigint = 1,764 type = 'NFT',765) {766 await usingApi(async (api: ApiPromise) => {767 const from = normalizeAccountId(accountFrom);768 const to = normalizeAccountId(accountTo);769 let balanceBefore = 0n;770 if (type === 'Fungible') {771 balanceBefore = await getBalance(api, collectionId, to, tokenId);772 }773 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);774 const events = await submitTransactionAsync(accountApproved, transferFromTx);775 const result = getCreateItemResult(events);776 // tslint:disable-next-line:no-unused-expression777 expect(result.success).to.be.true;778 if (type === 'NFT') {779 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);780 }781 if (type === 'Fungible') {782 const balanceAfter = await getBalance(api, collectionId, to, tokenId);783 if (JSON.stringify(to) !== JSON.stringify(from)) {784 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));785 } else {786 expect(balanceAfter).to.be.equal(balanceBefore);787 }788 }789 if (type === 'ReFungible') {790 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));791 }792 });793}794795export async function796transferFromExpectFail(797 collectionId: number,798 tokenId: number,799 accountApproved: IKeyringPair,800 accountFrom: IKeyringPair,801 accountTo: IKeyringPair,802 value: number | bigint = 1,803) {804 await usingApi(async (api: ApiPromise) => {805 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);806 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;807 const result = getCreateCollectionResult(events);808 // tslint:disable-next-line:no-unused-expression809 expect(result.success).to.be.false;810 });811}812813/* eslint no-async-promise-executor: "off" */814async function getBlockNumber(api: ApiPromise): Promise<number> {815 return new Promise<number>(async (resolve) => {816 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {817 unsubscribe();818 resolve(head.number.toNumber());819 });820 });821}822823export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {824 await usingApi(async (api) => {825 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));826 const events = await submitTransactionAsync(sender, changeAdminTx);827 const result = getCreateCollectionResult(events);828 expect(result.success).to.be.true;829 });830}831832export async function833getFreeBalance(account: IKeyringPair): Promise<bigint> {834 let balance = 0n;835 await usingApi(async (api) => {836 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());837 });838839 return balance;840}841842export async function843scheduleTransferExpectSuccess(844 collectionId: number,845 tokenId: number,846 sender: IKeyringPair,847 recipient: IKeyringPair,848 value: number | bigint = 1,849 blockSchedule: number,850) {851 await usingApi(async (api: ApiPromise) => {852 const blockNumber: number | undefined = await getBlockNumber(api);853 const expectedBlockNumber = blockNumber + blockSchedule;854855 expect(blockNumber).to.be.greaterThan(0);856 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);857 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);858859 await submitTransactionAsync(sender, scheduleTx);860861 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();862863 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));864865 // sleep for 4 blocks866 await waitNewBlocks(blockSchedule + 1);867868 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();869870 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));871 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);872 });873}874875876export async function877transferExpectSuccess(878 collectionId: number,879 tokenId: number,880 sender: IKeyringPair,881 recipient: IKeyringPair | CrossAccountId,882 value: number | bigint = 1,883 type = 'NFT',884) {885 await usingApi(async (api: ApiPromise) => {886 const from = normalizeAccountId(sender);887 const to = normalizeAccountId(recipient);888889 let balanceBefore = 0n;890 if (type === 'Fungible') {891 balanceBefore = await getBalance(api, collectionId, to, tokenId);892 }893 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);894 const events = await submitTransactionAsync(sender, transferTx);895 const result = getTransferResult(events);896 // tslint:disable-next-line:no-unused-expression897 expect(result.success).to.be.true;898 expect(result.collectionId).to.be.equal(collectionId);899 expect(result.itemId).to.be.equal(tokenId);900 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));901 expect(result.recipient).to.be.deep.equal(to);902 expect(result.value).to.be.equal(BigInt(value));903 if (type === 'NFT') {904 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);905 }906 if (type === 'Fungible') {907 const balanceAfter = await getBalance(api, collectionId, to, tokenId);908 if (JSON.stringify(to) !== JSON.stringify(from)) {909 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));910 } else {911 expect(balanceAfter).to.be.equal(balanceBefore);912 }913 }914 if (type === 'ReFungible') {915 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;916 }917 });918}919920export async function921transferExpectFailure(922 collectionId: number,923 tokenId: number,924 sender: IKeyringPair,925 recipient: IKeyringPair,926 value: number | bigint = 1,927) {928 await usingApi(async (api: ApiPromise) => {929 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);930 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;931 const result = getGenericResult(events);932 // if (events && Array.isArray(events)) {933 // const result = getCreateCollectionResult(events);934 // tslint:disable-next-line:no-unused-expression935 expect(result.success).to.be.false;936 //}937 });938}939940export async function941approveExpectFail(942 collectionId: number,943 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,944) {945 await usingApi(async (api: ApiPromise) => {946 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);947 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;948 const result = getCreateCollectionResult(events);949 // tslint:disable-next-line:no-unused-expression950 expect(result.success).to.be.false;951 });952}953954export async function getBalance(955 api: ApiPromise,956 collectionId: number,957 owner: string | CrossAccountId,958 token: number,959): Promise<bigint> {960 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();961}962export async function getTokenOwner(963 api: ApiPromise,964 collectionId: number,965 token: number,966): Promise<CrossAccountId> {967 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);968}969export async function isTokenExists(970 api: ApiPromise,971 collectionId: number,972 token: number,973): Promise<boolean> {974 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();975}976export async function getLastTokenId(977 api: ApiPromise,978 collectionId: number,979): Promise<number> {980 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();981}982export async function getAdminList(983 api: ApiPromise,984 collectionId: number,985): Promise<string[]> {986 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;987}988export async function getVariableMetadata(989 api: ApiPromise,990 collectionId: number,991 tokenId: number,992): Promise<number[]> {993 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];994}995export async function getConstMetadata(996 api: ApiPromise,997 collectionId: number,998 tokenId: number,999): Promise<number[]> {1000 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1001}10021003export async function createFungibleItemExpectSuccess(1004 sender: IKeyringPair,1005 collectionId: number,1006 data: CreateFungibleData,1007 owner: CrossAccountId | string = sender.address,1008) {1009 return await usingApi(async (api) => {1010 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10111012 const events = await submitTransactionAsync(sender, tx);1013 const result = getCreateItemResult(events);10141015 expect(result.success).to.be.true;1016 return result.itemId;1017 });1018}10191020export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1021 let newItemId = 0;1022 await usingApi(async (api) => {1023 const to = normalizeAccountId(owner);1024 const itemCountBefore = await getLastTokenId(api, collectionId);1025 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10261027 let tx;1028 if (createMode === 'Fungible') {1029 const createData = {fungible: {value: 10}};1030 tx = api.tx.unique.createItem(collectionId, to, createData as any);1031 } else if (createMode === 'ReFungible') {1032 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1033 tx = api.tx.unique.createItem(collectionId, to, createData as any);1034 } else {1035 const createData = {nft: {const_data: [], variable_data: []}};1036 tx = api.tx.unique.createItem(collectionId, to, createData as any);1037 }10381039 const events = await submitTransactionAsync(sender, tx);1040 const result = getCreateItemResult(events);10411042 const itemCountAfter = await getLastTokenId(api, collectionId);1043 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10441045 // What to expect1046 // tslint:disable-next-line:no-unused-expression1047 expect(result.success).to.be.true;1048 if (createMode === 'Fungible') {1049 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1050 } else {1051 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1052 }1053 expect(collectionId).to.be.equal(result.collectionId);1054 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1055 expect(to).to.be.deep.equal(result.recipient);1056 newItemId = result.itemId;1057 });1058 return newItemId;1059}10601061export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1062 await usingApi(async (api) => {1063 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10641065 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1066 const result = getCreateItemResult(events);10671068 expect(result.success).to.be.false;1069 });1070}10711072export async function setPublicAccessModeExpectSuccess(1073 sender: IKeyringPair, collectionId: number,1074 accessMode: 'Normal' | 'AllowList',1075) {1076 await usingApi(async (api) => {10771078 // Run the transaction1079 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1080 const events = await submitTransactionAsync(sender, tx);1081 const result = getGenericResult(events);10821083 // Get the collection1084 const collection = await queryCollectionExpectSuccess(api, collectionId);10851086 // What to expect1087 // tslint:disable-next-line:no-unused-expression1088 expect(result.success).to.be.true;1089 expect(collection.access.toHuman()).to.be.equal(accessMode);1090 });1091}10921093export async function setPublicAccessModeExpectFail(1094 sender: IKeyringPair, collectionId: number,1095 accessMode: 'Normal' | 'AllowList',1096) {1097 await usingApi(async (api) => {10981099 // Run the transaction1100 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1101 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1102 const result = getGenericResult(events);11031104 // What to expect1105 // tslint:disable-next-line:no-unused-expression1106 expect(result.success).to.be.false;1107 });1108}11091110export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1111 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1112}11131114export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1115 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1116}11171118export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1119 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1120}11211122export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1123 await usingApi(async (api) => {11241125 // Run the transaction1126 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1127 const events = await submitTransactionAsync(sender, tx);1128 const result = getGenericResult(events);1129 expect(result.success).to.be.true;11301131 // Get the collection1132 const collection = await queryCollectionExpectSuccess(api, collectionId);11331134 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1135 });1136}11371138export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1139 await setMintPermissionExpectSuccess(sender, collectionId, true);1140}11411142export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1143 await usingApi(async (api) => {1144 // Run the transaction1145 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1146 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1147 const result = getCreateCollectionResult(events);1148 // tslint:disable-next-line:no-unused-expression1149 expect(result.success).to.be.false;1150 });1151}11521153export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1154 await usingApi(async (api) => {1155 // Run the transaction1156 const tx = api.tx.unique.setChainLimits(limits);1157 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1158 const result = getCreateCollectionResult(events);1159 // tslint:disable-next-line:no-unused-expression1160 expect(result.success).to.be.false;1161 });1162}11631164export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1165 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1166}11671168export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1169 await usingApi(async (api) => {1170 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11711172 // Run the transaction1173 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1174 const events = await submitTransactionAsync(sender, tx);1175 const result = getGenericResult(events);1176 expect(result.success).to.be.true;11771178 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1179 });1180}11811182export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1183 await usingApi(async (api) => {11841185 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11861187 // Run the transaction1188 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1189 const events = await submitTransactionAsync(sender, tx);1190 const result = getGenericResult(events);1191 expect(result.success).to.be.true;11921193 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1194 });1195}11961197export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1198 await usingApi(async (api) => {11991200 // Run the transaction1201 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1202 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1203 const result = getGenericResult(events);12041205 // What to expect1206 // tslint:disable-next-line:no-unused-expression1207 expect(result.success).to.be.false;1208 });1209}12101211export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1212 await usingApi(async (api) => {1213 // Run the transaction1214 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1215 const events = await submitTransactionAsync(sender, tx);1216 const result = getGenericResult(events);12171218 // What to expect1219 // tslint:disable-next-line:no-unused-expression1220 expect(result.success).to.be.true;1221 });1222}12231224export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1225 await usingApi(async (api) => {1226 // Run the transaction1227 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1228 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1229 const result = getGenericResult(events);12301231 // What to expect1232 // tslint:disable-next-line:no-unused-expression1233 expect(result.success).to.be.false;1234 });1235}12361237export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1238 : Promise<UpDataStructsCollection | null> => {1239 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1240};12411242export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1243 // set global object - collectionsCount1244 return (await api.rpc.unique.collectionStats()).created.toNumber();1245};12461247export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1248 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1249}12501251export async function waitNewBlocks(blocksCount = 1): Promise<void> {1252 await usingApi(async (api) => {1253 const promise = new Promise<void>(async (resolve) => {1254 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1255 if (blocksCount > 0) {1256 blocksCount--;1257 } else {1258 unsubscribe();1259 resolve();1260 }1261 });1262 });1263 return promise;1264 });1265}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 // console.log(` ${phase}: ${section}.${method}:: ${data}`);191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209 events.forEach(({event: {data, method, section}}) => {210 // console.log(` ${phase}: ${section}.${method}:: ${data}`);211 if (method == 'ExtrinsicSuccess') {212 success = true;213 } else if ((section == 'common') && (method == 'ItemCreated')) {214 collectionId = parseInt(data[0].toString(), 10);215 itemId = parseInt(data[1].toString(), 10);216 recipient = normalizeAccountId(data[2].toJSON() as any);217 }218 });219 const result: CreateItemResult = {220 success,221 collectionId,222 itemId,223 recipient,224 };225 return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229 const result: TransferResult = {230 success: false,231 collectionId: 0,232 itemId: 0,233 value: 0n,234 };235236 events.forEach(({event: {data, method, section}}) => {237 if (method === 'ExtrinsicSuccess') {238 result.success = true;239 } else if (section === 'common' && method === 'Transfer') {240 result.collectionId = +data[0].toString();241 result.itemId = +data[1].toString();242 result.sender = normalizeAccountId(data[2].toJSON() as any);243 result.recipient = normalizeAccountId(data[3].toJSON() as any);244 result.value = BigInt(data[4].toString());245 }246 });247248 return result;249}250251interface Nft {252 type: 'NFT';253}254255interface Fungible {256 type: 'Fungible';257 decimalPoints: number;258}259260interface ReFungible {261 type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267 mode: CollectionMode,268 name: string,269 description: string,270 tokenPrefix: string,271 shemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275 description: 'description',276 mode: {type: 'NFT'},277 name: 'name',278 tokenPrefix: 'prefix',279 shemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283 const {name, description, mode, tokenPrefix, shemaVersion} = {...defaultCreateCollectionParams, ...params};284285 let collectionId = 0;286 await usingApi(async (api) => {287 // Get number of collections before the transaction288 const collectionCountBefore = await getCreatedCollectionCount(api);289290 // Run the CreateCollection transaction291 const alicePrivateKey = privateKey('//Alice');292293 let modeprm = {};294 if (mode.type === 'NFT') {295 modeprm = {nft: null};296 } else if (mode.type === 'Fungible') {297 modeprm = {fungible: mode.decimalPoints};298 } else if (mode.type === 'ReFungible') {299 modeprm = {refungible: null};300 }301302 const tx = api.tx.unique.createCollectionEx({303 name: strToUTF16(name), 304 description: strToUTF16(description), 305 tokenPrefix: strToUTF16(tokenPrefix), 306 mode: modeprm as any,307 schemaVersion: shemaVersion,308 });309 const events = await submitTransactionAsync(alicePrivateKey, tx);310 const result = getCreateCollectionResult(events);311312 // Get number of collections after the transaction313 const collectionCountAfter = await getCreatedCollectionCount(api);314315 // Get the collection316 const collection = await queryCollectionExpectSuccess(api, result.collectionId);317318 // What to expect319 // tslint:disable-next-line:no-unused-expression320 expect(result.success).to.be.true;321 expect(result.collectionId).to.be.equal(collectionCountAfter);322 // tslint:disable-next-line:no-unused-expression323 expect(collection).to.be.not.null;324 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');325 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));326 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);327 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);328 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);329330 collectionId = result.collectionId;331 });332333 return collectionId;334}335336export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {337 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};338339 let modeprm = {};340 if (mode.type === 'NFT') {341 modeprm = {nft: null};342 } else if (mode.type === 'Fungible') {343 modeprm = {fungible: mode.decimalPoints};344 } else if (mode.type === 'ReFungible') {345 modeprm = {refungible: null};346 }347348 await usingApi(async (api) => {349 // Get number of collections before the transaction350 const collectionCountBefore = await getCreatedCollectionCount(api);351352 // Run the CreateCollection transaction353 const alicePrivateKey = privateKey('//Alice');354 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});355 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356 const result = getCreateCollectionResult(events);357358 // Get number of collections after the transaction359 const collectionCountAfter = await getCreatedCollectionCount(api);360361 // What to expect362 // tslint:disable-next-line:no-unused-expression363 expect(result.success).to.be.false;364 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');365 });366}367368export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {369 let bal = 0n;370 let unused;371 do {372 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;373 const keyring = new Keyring({type: 'sr25519'});374 unused = keyring.addFromUri(`//${randomSeed}`);375 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();376 } while (bal !== 0n);377 return unused;378}379380export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {381 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();382}383384export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {385 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));386}387388export async function findNotExistingCollection(api: ApiPromise): Promise<number> {389 const totalNumber = await getCreatedCollectionCount(api);390 const newCollection: number = totalNumber + 1;391 return newCollection;392}393394function getDestroyResult(events: EventRecord[]): boolean {395 let success = false;396 events.forEach(({event: {method}}) => {397 if (method == 'ExtrinsicSuccess') {398 success = true;399 }400 });401 return success;402}403404export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {405 await usingApi(async (api) => {406 // Run the DestroyCollection transaction407 const alicePrivateKey = privateKey(senderSeed);408 const tx = api.tx.unique.destroyCollection(collectionId);409 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410 });411}412413export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {414 await usingApi(async (api) => {415 // Run the DestroyCollection transaction416 const alicePrivateKey = privateKey(senderSeed);417 const tx = api.tx.unique.destroyCollection(collectionId);418 const events = await submitTransactionAsync(alicePrivateKey, tx);419 const result = getDestroyResult(events);420 expect(result).to.be.true;421422 // What to expect423 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;424 });425}426427export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {428 await usingApi(async (api) => {429 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);430 const events = await submitTransactionAsync(sender, tx);431 const result = getGenericResult(events);432433 expect(result.success).to.be.true;434 });435}436437export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {438 await usingApi(async (api) => {439 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);440 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;441 const result = getGenericResult(events);442443 expect(result.success).to.be.false;444 });445}446447export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {448 await usingApi(async (api) => {449450 // Run the transaction451 const senderPrivateKey = privateKey(sender);452 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);453 const events = await submitTransactionAsync(senderPrivateKey, tx);454 const result = getGenericResult(events);455456 // Get the collection457 const collection = await queryCollectionExpectSuccess(api, collectionId);458459 // What to expect460 expect(result.success).to.be.true;461 expect(collection.sponsorship.toJSON()).to.deep.equal({462 unconfirmed: sponsor,463 });464 });465}466467export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {468 await usingApi(async (api) => {469470 // Run the transaction471 const alicePrivateKey = privateKey(sender);472 const tx = api.tx.unique.removeCollectionSponsor(collectionId);473 const events = await submitTransactionAsync(alicePrivateKey, tx);474 const result = getGenericResult(events);475476 // Get the collection477 const collection = await queryCollectionExpectSuccess(api, collectionId);478479 // What to expect480 expect(result.success).to.be.true;481 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});482 });483}484485export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {486 await usingApi(async (api) => {487488 // Run the transaction489 const alicePrivateKey = privateKey(senderSeed);490 const tx = api.tx.unique.removeCollectionSponsor(collectionId);491 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;492 });493}494495export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {496 await usingApi(async (api) => {497498 // Run the transaction499 const alicePrivateKey = privateKey(senderSeed);500 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);501 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;502 });503}504505export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {506 await usingApi(async (api) => {507508 // Run the transaction509 const sender = privateKey(senderSeed);510 const tx = api.tx.unique.confirmSponsorship(collectionId);511 const events = await submitTransactionAsync(sender, tx);512 const result = getGenericResult(events);513514 // Get the collection515 const collection = await queryCollectionExpectSuccess(api, collectionId);516517 // What to expect518 expect(result.success).to.be.true;519 expect(collection.sponsorship.toJSON()).to.be.deep.equal({520 confirmed: sender.address,521 });522 });523}524525526export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {527 await usingApi(async (api) => {528529 // Run the transaction530 const sender = privateKey(senderSeed);531 const tx = api.tx.unique.confirmSponsorship(collectionId);532 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;533 });534}535536export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {537538 await usingApi(async (api) => {539 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);540 const events = await submitTransactionAsync(sender, tx);541 const result = getGenericResult(events);542543 expect(result.success).to.be.true;544 });545}546547export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {548549 await usingApi(async (api) => {550 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);551 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;552 const result = getGenericResult(events);553554 expect(result.success).to.be.false;555 });556}557558export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {559 await usingApi(async (api) => {560 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {569 await usingApi(async (api) => {570 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);571 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;572 const result = getGenericResult(events);573574 expect(result.success).to.be.false;575 });576}577578export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {579580 await usingApi(async (api) => {581582 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);583 const events = await submitTransactionAsync(sender, tx);584 const result = getGenericResult(events);585586 expect(result.success).to.be.true;587 });588}589590export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {591592 await usingApi(async (api) => {593594 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;596 const result = getGenericResult(events);597598 expect(result.success).to.be.false;599 });600}601602export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {603 await usingApi(async (api) => {604 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);605 const events = await submitTransactionAsync(sender, tx);606 const result = getGenericResult(events);607608 expect(result.success).to.be.true;609 });610}611612export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {613 await usingApi(async (api) => {614 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);615 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;616 const result = getGenericResult(events);617618 expect(result.success).to.be.false;619 });620}621622export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {623 await usingApi(async (api) => {624 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);625 const events = await submitTransactionAsync(sender, tx);626 const result = getGenericResult(events);627628 expect(result.success).to.be.true;629 });630}631632export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {633 let allowlisted = false;634 await usingApi(async (api) => {635 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;636 });637 return allowlisted;638}639640export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {641 await usingApi(async (api) => {642 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());643 const events = await submitTransactionAsync(sender, tx);644 const result = getGenericResult(events);645646 expect(result.success).to.be.true;647 });648}649650export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {651 await usingApi(async (api) => {652 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());653 const events = await submitTransactionAsync(sender, tx);654 const result = getGenericResult(events);655656 expect(result.success).to.be.true;657 });658}659660export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {661 await usingApi(async (api) => {662 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());663 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;664 const result = getGenericResult(events);665666 expect(result.success).to.be.false;667 });668}669670export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {671 await usingApi(async (api) => {672 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));673 const events = await submitTransactionAsync(sender, tx);674 const result = getGenericResult(events);675676 expect(result.success).to.be.true;677 });678}679680export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));683 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;684 });685}686687export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {688 await usingApi(async (api) => {689 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));690 const events = await submitTransactionAsync(sender, tx);691 const result = getGenericResult(events);692693 expect(result.success).to.be.true;694 });695}696697export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {698 await usingApi(async (api) => {699 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));700 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;701 });702}703704export interface CreateFungibleData {705 readonly Value: bigint;706}707708export interface CreateReFungibleData { }709export interface CreateNftData { }710711export type CreateItemData = {712 NFT: CreateNftData;713} | {714 Fungible: CreateFungibleData;715} | {716 ReFungible: CreateReFungibleData;717};718719export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {720 await usingApi(async (api) => {721 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);722 // if burning token by admin - use adminButnItemExpectSuccess723 expect(balanceBefore >= BigInt(value)).to.be.true;724725 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);726 const events = await submitTransactionAsync(sender, tx);727 const result = getGenericResult(events);728 expect(result.success).to.be.true;729730 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);731 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);732 });733}734735export async function736approveExpectSuccess(737 collectionId: number,738 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,739) {740 await usingApi(async (api: ApiPromise) => {741 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);742 const events = await submitTransactionAsync(owner, approveUniqueTx);743 const result = getGenericResult(events);744 expect(result.success).to.be.true;745746 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));747 });748}749750export async function adminApproveFromExpectSuccess(751 collectionId: number,752 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,753) {754 await usingApi(async (api: ApiPromise) => {755 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);756 const events = await submitTransactionAsync(admin, approveUniqueTx);757 const result = getGenericResult(events);758 expect(result.success).to.be.true;759760 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));761 });762}763764export async function765transferFromExpectSuccess(766 collectionId: number,767 tokenId: number,768 accountApproved: IKeyringPair,769 accountFrom: IKeyringPair | CrossAccountId,770 accountTo: IKeyringPair | CrossAccountId,771 value: number | bigint = 1,772 type = 'NFT',773) {774 await usingApi(async (api: ApiPromise) => {775 const from = normalizeAccountId(accountFrom);776 const to = normalizeAccountId(accountTo);777 let balanceBefore = 0n;778 if (type === 'Fungible') {779 balanceBefore = await getBalance(api, collectionId, to, tokenId);780 }781 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);782 const events = await submitTransactionAsync(accountApproved, transferFromTx);783 const result = getCreateItemResult(events);784 // tslint:disable-next-line:no-unused-expression785 expect(result.success).to.be.true;786 if (type === 'NFT') {787 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);788 }789 if (type === 'Fungible') {790 const balanceAfter = await getBalance(api, collectionId, to, tokenId);791 if (JSON.stringify(to) !== JSON.stringify(from)) {792 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));793 } else {794 expect(balanceAfter).to.be.equal(balanceBefore);795 }796 }797 if (type === 'ReFungible') {798 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));799 }800 });801}802803export async function804transferFromExpectFail(805 collectionId: number,806 tokenId: number,807 accountApproved: IKeyringPair,808 accountFrom: IKeyringPair,809 accountTo: IKeyringPair,810 value: number | bigint = 1,811) {812 await usingApi(async (api: ApiPromise) => {813 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);814 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;815 const result = getCreateCollectionResult(events);816 // tslint:disable-next-line:no-unused-expression817 expect(result.success).to.be.false;818 });819}820821/* eslint no-async-promise-executor: "off" */822async function getBlockNumber(api: ApiPromise): Promise<number> {823 return new Promise<number>(async (resolve) => {824 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {825 unsubscribe();826 resolve(head.number.toNumber());827 });828 });829}830831export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {832 await usingApi(async (api) => {833 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));834 const events = await submitTransactionAsync(sender, changeAdminTx);835 const result = getCreateCollectionResult(events);836 expect(result.success).to.be.true;837 });838}839840export async function841getFreeBalance(account: IKeyringPair): Promise<bigint> {842 let balance = 0n;843 await usingApi(async (api) => {844 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());845 });846847 return balance;848}849850export async function851scheduleTransferExpectSuccess(852 collectionId: number,853 tokenId: number,854 sender: IKeyringPair,855 recipient: IKeyringPair,856 value: number | bigint = 1,857 blockSchedule: number,858) {859 await usingApi(async (api: ApiPromise) => {860 const blockNumber: number | undefined = await getBlockNumber(api);861 const expectedBlockNumber = blockNumber + blockSchedule;862863 expect(blockNumber).to.be.greaterThan(0);864 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);865 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);866867 await submitTransactionAsync(sender, scheduleTx);868869 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();870871 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));872873 // sleep for 4 blocks874 await waitNewBlocks(blockSchedule + 1);875876 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();877878 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));879 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);880 });881}882883884export async function885transferExpectSuccess(886 collectionId: number,887 tokenId: number,888 sender: IKeyringPair,889 recipient: IKeyringPair | CrossAccountId,890 value: number | bigint = 1,891 type = 'NFT',892) {893 await usingApi(async (api: ApiPromise) => {894 const from = normalizeAccountId(sender);895 const to = normalizeAccountId(recipient);896897 let balanceBefore = 0n;898 if (type === 'Fungible') {899 balanceBefore = await getBalance(api, collectionId, to, tokenId);900 }901 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);902 const events = await submitTransactionAsync(sender, transferTx);903 const result = getTransferResult(events);904 // tslint:disable-next-line:no-unused-expression905 expect(result.success).to.be.true;906 expect(result.collectionId).to.be.equal(collectionId);907 expect(result.itemId).to.be.equal(tokenId);908 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));909 expect(result.recipient).to.be.deep.equal(to);910 expect(result.value).to.be.equal(BigInt(value));911 if (type === 'NFT') {912 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);913 }914 if (type === 'Fungible') {915 const balanceAfter = await getBalance(api, collectionId, to, tokenId);916 if (JSON.stringify(to) !== JSON.stringify(from)) {917 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));918 } else {919 expect(balanceAfter).to.be.equal(balanceBefore);920 }921 }922 if (type === 'ReFungible') {923 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;924 }925 });926}927928export async function929transferExpectFailure(930 collectionId: number,931 tokenId: number,932 sender: IKeyringPair,933 recipient: IKeyringPair,934 value: number | bigint = 1,935) {936 await usingApi(async (api: ApiPromise) => {937 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);938 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;939 const result = getGenericResult(events);940 // if (events && Array.isArray(events)) {941 // const result = getCreateCollectionResult(events);942 // tslint:disable-next-line:no-unused-expression943 expect(result.success).to.be.false;944 //}945 });946}947948export async function949approveExpectFail(950 collectionId: number,951 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,952) {953 await usingApi(async (api: ApiPromise) => {954 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);955 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;956 const result = getCreateCollectionResult(events);957 // tslint:disable-next-line:no-unused-expression958 expect(result.success).to.be.false;959 });960}961962export async function getBalance(963 api: ApiPromise,964 collectionId: number,965 owner: string | CrossAccountId,966 token: number,967): Promise<bigint> {968 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();969}970export async function getTokenOwner(971 api: ApiPromise,972 collectionId: number,973 token: number,974): Promise<CrossAccountId> {975 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);976}977export async function isTokenExists(978 api: ApiPromise,979 collectionId: number,980 token: number,981): Promise<boolean> {982 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();983}984export async function getLastTokenId(985 api: ApiPromise,986 collectionId: number,987): Promise<number> {988 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();989}990export async function getAdminList(991 api: ApiPromise,992 collectionId: number,993): Promise<string[]> {994 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;995}996export async function getVariableMetadata(997 api: ApiPromise,998 collectionId: number,999 tokenId: number,1000): Promise<number[]> {1001 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1002}1003export async function getConstMetadata(1004 api: ApiPromise,1005 collectionId: number,1006 tokenId: number,1007): Promise<number[]> {1008 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1009}10101011export async function createFungibleItemExpectSuccess(1012 sender: IKeyringPair,1013 collectionId: number,1014 data: CreateFungibleData,1015 owner: CrossAccountId | string = sender.address,1016) {1017 return await usingApi(async (api) => {1018 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10191020 const events = await submitTransactionAsync(sender, tx);1021 const result = getCreateItemResult(events);10221023 expect(result.success).to.be.true;1024 return result.itemId;1025 });1026}10271028export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1029 let newItemId = 0;1030 await usingApi(async (api) => {1031 const to = normalizeAccountId(owner);1032 const itemCountBefore = await getLastTokenId(api, collectionId);1033 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10341035 let tx;1036 if (createMode === 'Fungible') {1037 const createData = {fungible: {value: 10}};1038 tx = api.tx.unique.createItem(collectionId, to, createData as any);1039 } else if (createMode === 'ReFungible') {1040 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1041 tx = api.tx.unique.createItem(collectionId, to, createData as any);1042 } else {1043 const createData = {nft: {const_data: [], variable_data: []}};1044 tx = api.tx.unique.createItem(collectionId, to, createData as any);1045 }10461047 const events = await submitTransactionAsync(sender, tx);1048 const result = getCreateItemResult(events);10491050 const itemCountAfter = await getLastTokenId(api, collectionId);1051 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10521053 // What to expect1054 // tslint:disable-next-line:no-unused-expression1055 expect(result.success).to.be.true;1056 if (createMode === 'Fungible') {1057 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1058 } else {1059 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1060 }1061 expect(collectionId).to.be.equal(result.collectionId);1062 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1063 expect(to).to.be.deep.equal(result.recipient);1064 newItemId = result.itemId;1065 });1066 return newItemId;1067}10681069export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1070 await usingApi(async (api) => {1071 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10721073 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1074 const result = getCreateItemResult(events);10751076 expect(result.success).to.be.false;1077 });1078}10791080export async function setPublicAccessModeExpectSuccess(1081 sender: IKeyringPair, collectionId: number,1082 accessMode: 'Normal' | 'AllowList',1083) {1084 await usingApi(async (api) => {10851086 // Run the transaction1087 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1088 const events = await submitTransactionAsync(sender, tx);1089 const result = getGenericResult(events);10901091 // Get the collection1092 const collection = await queryCollectionExpectSuccess(api, collectionId);10931094 // What to expect1095 // tslint:disable-next-line:no-unused-expression1096 expect(result.success).to.be.true;1097 expect(collection.access.toHuman()).to.be.equal(accessMode);1098 });1099}11001101export async function setPublicAccessModeExpectFail(1102 sender: IKeyringPair, collectionId: number,1103 accessMode: 'Normal' | 'AllowList',1104) {1105 await usingApi(async (api) => {11061107 // Run the transaction1108 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1109 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1110 const result = getGenericResult(events);11111112 // What to expect1113 // tslint:disable-next-line:no-unused-expression1114 expect(result.success).to.be.false;1115 });1116}11171118export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1119 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1120}11211122export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1123 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1124}11251126export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1127 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1128}11291130export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1131 await usingApi(async (api) => {11321133 // Run the transaction1134 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1135 const events = await submitTransactionAsync(sender, tx);1136 const result = getGenericResult(events);1137 expect(result.success).to.be.true;11381139 // Get the collection1140 const collection = await queryCollectionExpectSuccess(api, collectionId);11411142 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1143 });1144}11451146export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1147 await setMintPermissionExpectSuccess(sender, collectionId, true);1148}11491150export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1151 await usingApi(async (api) => {1152 // Run the transaction1153 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1154 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1155 const result = getCreateCollectionResult(events);1156 // tslint:disable-next-line:no-unused-expression1157 expect(result.success).to.be.false;1158 });1159}11601161export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1162 await usingApi(async (api) => {1163 // Run the transaction1164 const tx = api.tx.unique.setChainLimits(limits);1165 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1166 const result = getCreateCollectionResult(events);1167 // tslint:disable-next-line:no-unused-expression1168 expect(result.success).to.be.false;1169 });1170}11711172export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1173 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1174}11751176export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1177 await usingApi(async (api) => {1178 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11791180 // Run the transaction1181 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1182 const events = await submitTransactionAsync(sender, tx);1183 const result = getGenericResult(events);1184 expect(result.success).to.be.true;11851186 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1187 });1188}11891190export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1191 await usingApi(async (api) => {11921193 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11941195 // Run the transaction1196 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1197 const events = await submitTransactionAsync(sender, tx);1198 const result = getGenericResult(events);1199 expect(result.success).to.be.true;12001201 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1202 });1203}12041205export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1206 await usingApi(async (api) => {12071208 // Run the transaction1209 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1210 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1211 const result = getGenericResult(events);12121213 // What to expect1214 // tslint:disable-next-line:no-unused-expression1215 expect(result.success).to.be.false;1216 });1217}12181219export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1220 await usingApi(async (api) => {1221 // Run the transaction1222 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1223 const events = await submitTransactionAsync(sender, tx);1224 const result = getGenericResult(events);12251226 // What to expect1227 // tslint:disable-next-line:no-unused-expression1228 expect(result.success).to.be.true;1229 });1230}12311232export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1233 await usingApi(async (api) => {1234 // Run the transaction1235 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1236 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1237 const result = getGenericResult(events);12381239 // What to expect1240 // tslint:disable-next-line:no-unused-expression1241 expect(result.success).to.be.false;1242 });1243}12441245export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1246 : Promise<UpDataStructsCollection | null> => {1247 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1248};12491250export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1251 // set global object - collectionsCount1252 return (await api.rpc.unique.collectionStats()).created.toNumber();1253};12541255export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1256 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1257}12581259export async function waitNewBlocks(blocksCount = 1): Promise<void> {1260 await usingApi(async (api) => {1261 const promise = new Promise<void>(async (resolve) => {1262 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1263 if (blocksCount > 0) {1264 blocksCount--;1265 } else {1266 unsubscribe();1267 resolve();1268 }1269 });1270 });1271 return promise;1272 });1273}