git.delta.rocks / unique-network / refs/commits / 04a22c8dcea1

difftreelog

refactor remove meta update permission

Daniel Shiposha2022-05-15parent: #07f2d6c.patch.diff
in: master

11 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -22,7 +22,7 @@
 use pallet_evm::account::CrossAccountId;
 use frame_support::{
 	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
-	ensure, fail,
+	ensure,
 	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
 	BoundedVec,
 	weights::Pays,
@@ -30,7 +30,7 @@
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,
-	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,
+	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,
 	CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,
 	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
 	CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,
@@ -134,21 +134,6 @@
 			<Error<T>>::AddressNotInAllowlist
 		);
 		Ok(())
-	}
-
-	pub fn check_can_update_meta(
-		&self,
-		subject: &T::CrossAccountId,
-		item_owner: &T::CrossAccountId,
-	) -> DispatchResult {
-		match self.meta_update_permission {
-			MetaUpdatePermission::ItemOwner => {
-				ensure!(subject == item_owner, <Error<T>>::NoPermission);
-				Ok(())
-			}
-			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),
-			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),
-		}
 	}
 }
 
@@ -565,7 +550,6 @@
 			schema_version,
 			sponsorship,
 			limits,
-			meta_update_permission,
 		} = <CollectionById<T>>::get(collection)?;
 
 		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
@@ -595,7 +579,6 @@
 			schema_version,
 			sponsorship,
 			limits,
-			meta_update_permission,
 			offchain_schema: <CollectionData<T>>::get((
 				collection,
 				CollectionField::OffchainSchema,
@@ -656,7 +639,6 @@
 				.limits
 				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
 				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
-			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
 		};
 
 		let mut collection_properties = up_data_structs::CollectionProperties::get();
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -168,9 +168,4 @@
 			nesting_rule: None,
 		};
 	}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
-
-	set_meta_update_permission_flag {
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-	}: _(RawOrigin::Signed(caller.clone()), collection, MetaUpdatePermission::Admin)
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -38,12 +38,12 @@
 	CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
 	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
-	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData,
+	SchemaVersion, SponsorshipState, CreateCollectionData,
 	CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
-	CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo,
+	CollectionHandle, Pallet as PalletCommon, CommonWeightInfo,
 	dispatch::dispatch_call, dispatch::CollectionDispatch,
 };
 
@@ -925,34 +925,6 @@
 			let budget = budget::Value::new(2);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
-		}
-
-		/// Set meta_update_permission value for particular collection
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner.
-		///
-		/// # Arguments
-		///
-		/// * collection_id: ID of the collection.
-		///
-		/// * value: New flag value.
-		#[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]
-		#[transactional]
-		pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
-			ensure!(
-				target_collection.meta_update_permission != MetaUpdatePermission::None,
-				<CommonError<T>>::MetadataFlagFrozen,
-			);
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.meta_update_permission = value;
-
-			target_collection.save()
 		}
 
 		/// Set schema standard
modifiedpallets/unique/src/weights.rsdiffbeforeafterboth
--- a/pallets/unique/src/weights.rs
+++ b/pallets/unique/src/weights.rs
@@ -49,7 +49,6 @@
 	fn set_const_on_chain_schema(b: u32, ) -> Weight;
 	fn set_schema_version() -> Weight;
 	fn set_collection_limits() -> Weight;
-	fn set_meta_update_permission_flag() -> Weight;
 }
 
 /// Weights for pallet_unique using the Substrate node and recommended hardware.
@@ -167,12 +166,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_collection_limits() -> Weight {
 		(15_339_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Common CollectionById (r:1 w:1)
-	fn set_meta_update_permission_flag() -> Weight {
-		(7_214_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -292,12 +285,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_collection_limits() -> Weight {
 		(15_339_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Common CollectionById (r:1 w:1)
-	fn set_meta_update_permission_flag() -> Weight {
-		(7_214_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -308,6 +308,7 @@
 	#[version(..2)]
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
 
+	#[version(..2)]
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
@@ -327,7 +328,6 @@
 	pub sponsorship: SponsorshipState<AccountId>,
 	pub limits: CollectionLimits,
 	pub const_on_chain_schema: Vec<u8>,
-	pub meta_update_permission: MetaUpdatePermission,
 	pub token_property_permissions: Vec<PropertyKeyPermission>,
 	pub properties: Vec<Property>,
 }
@@ -353,7 +353,6 @@
 	pub pending_sponsor: Option<AccountId>,
 	pub limits: Option<CollectionLimits>,
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
-	pub meta_update_permission: Option<MetaUpdatePermission>,
 	pub token_property_permissions: CollectionPropertiesPermissionsVec,
 	pub properties: CollectionPropertiesVec,
 }
@@ -493,17 +492,10 @@
 }
 
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub enum MetaUpdatePermission {
 	ItemOwner,
 	Admin,
 	None,
-}
-
-impl Default for MetaUpdatePermission {
-	fn default() -> Self {
-		Self::ItemOwner
-	}
 }
 
 #[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -18,7 +18,7 @@
 use crate::{Test, TestCrossAccountId, CollectionCreationPrice, Origin, Unique, new_test_ext};
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
-	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
+	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT,
 	TokenId, MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionField, SchemaVersion,
 	CollectionMode, AccessMode,
 };
@@ -2467,32 +2467,6 @@
 		assert_eq!(
 			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
 			1
-		);
-	});
-}
-
-#[test]
-fn set_variable_meta_flag_after_freeze() {
-	new_test_ext().execute_with(|| {
-		// default_limits();
-
-		let collection_id =
-			create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
-		let origin2 = Origin::signed(2);
-
-		assert_ok!(Unique::set_meta_update_permission_flag(
-			origin2.clone(),
-			collection_id,
-			MetaUpdatePermission::None,
-		));
-		assert_noop!(
-			Unique::set_meta_update_permission_flag(
-				origin2.clone(),
-				collection_id,
-				MetaUpdatePermission::Admin
-			),
-			CommonError::<Test>::MetadataFlagFrozen
 		);
 	});
 }
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -74,7 +74,6 @@
           accountTokenOwnershipLimit: 3,
         },
         constOnChainSchema: '0x333333',
-        metaUpdatePermission: 'Admin',
       });
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateCollectionResult(events);
@@ -91,7 +90,6 @@
       expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
       expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
       expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
-      expect(collection.metaUpdatePermission.isAdmin).to.be.true;
     });
   });
 });
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import privateKey from '../substrate/privateKey';
-import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE, setMetadataUpdatePermissionFlagExpectSuccess} from '../util/helpers';
+import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {expect} from 'chai';
modifiedtests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth
--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import privateKey from '../../substrate/privateKey';
-import {createCollectionExpectSuccess, createItemExpectSuccess, setMetadataUpdatePermissionFlagExpectSuccess} from '../../util/helpers';
+import {createCollectionExpectSuccess, createItemExpectSuccess} from '../../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';
 import nonFungibleAbi from '../nonFungibleAbi.json';
 import {expect} from 'chai';
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -37,7 +37,6 @@
           accountTokenOwnershipLimit: 3,
         },
         constOnChainSchema: '0x333333',
-        metaUpdatePermission: 'Admin',
       });
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateCollectionResult(events);
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
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, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, 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, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} 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  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144  constData: number[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148  let checkMsgUnqMethod = '';149  let checkMsgTrsMethod = '';150  let checkMsgSysMethod = '';151  events.forEach(({event: {method, section}}) => {152    if (section === 'common') {153      checkMsgUnqMethod = method;154    } else if (section === 'treasury') {155      checkMsgTrsMethod = method;156    } else if (section === 'system') {157      checkMsgSysMethod = method;158    } else { return null; }159  });160  const result: IGetMessage = {161    checkMsgUnqMethod,162    checkMsgTrsMethod,163    checkMsgSysMethod,164  };165  return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169  const event = events.find(r => check(r.event));170  if (!event) return;171  return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175  const result: GenericResult = {176    success: false,177  };178  events.forEach(({event: {method}}) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method === 'ExtrinsicSuccess') {181      result.success = true;182    }183  });184  return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190  let success = false;191  let collectionId = 0;192  events.forEach(({event: {data, method, section}}) => {193    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);194    if (method == 'ExtrinsicSuccess') {195      success = true;196    } else if ((section == 'common') && (method == 'CollectionCreated')) {197      collectionId = parseInt(data[0].toString(), 10);198    }199  });200  const result: CreateCollectionResult = {201    success,202    collectionId,203  };204  return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208  let success = false;209  let collectionId = 0;210  let itemId = 0;211  let recipient;212213  const results : CreateItemResult[]  = [];214215  events.forEach(({event: {data, method, section}}) => {216    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);217    if (method == 'ExtrinsicSuccess') {218      success = true;219    } else if ((section == 'common') && (method == 'ItemCreated')) {220      collectionId = parseInt(data[0].toString(), 10);221      itemId = parseInt(data[1].toString(), 10);222      recipient = normalizeAccountId(data[2].toJSON() as any);223224      const itemRes: CreateItemResult = {225        success,226        collectionId,227        itemId,228        recipient,229      };230231      results.push(itemRes);232    }233  });234235  return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239  let success = false;240  let collectionId = 0;241  let itemId = 0;242  let recipient;243  events.forEach(({event: {data, method, section}}) => {244    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);245    if (method == 'ExtrinsicSuccess') {246      success = true;247    } else if ((section == 'common') && (method == 'ItemCreated')) {248      collectionId = parseInt(data[0].toString(), 10);249      itemId = parseInt(data[1].toString(), 10);250      recipient = normalizeAccountId(data[2].toJSON() as any);251    }252  });253  const result: CreateItemResult = {254    success,255    collectionId,256    itemId,257    recipient,258  };259  return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263  for (const {event} of events) {264    if (api.events.common.Transfer.is(event)) {265      const [collection, token, sender, recipient, value] = event.data;266      return {267        collectionId: collection.toNumber(),268        itemId: token.toNumber(),269        sender: normalizeAccountId(sender.toJSON() as any),270        recipient: normalizeAccountId(recipient.toJSON() as any),271        value: value.toBigInt(),272      };273    }274  }275  throw new Error('no transfer event');276}277278interface Nft {279  type: 'NFT';280}281282interface Fungible {283  type: 'Fungible';284  decimalPoints: number;285}286287interface ReFungible {288  type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294  key: any,295  value: any,296};297298type PropertyPermission = {299  key: any,300  mutable: boolean;301  collectionAdmin: boolean;302  tokenOwner: boolean;303}304305export type CreateCollectionParams = {306  mode: CollectionMode,307  name: string,308  description: string,309  tokenPrefix: string,310  schemaVersion: string,311  properties?: Array<Property>,312  propPerm?: Array<PropertyPermission>313};314315const defaultCreateCollectionParams: CreateCollectionParams = {316  description: 'description',317  mode: {type: 'NFT'},318  name: 'name',319  tokenPrefix: 'prefix',320  schemaVersion: 'ImageURL',321};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};325326  let collectionId = 0;327  await usingApi(async (api) => {328    // Get number of collections before the transaction329    const collectionCountBefore = await getCreatedCollectionCount(api);330331    // Run the CreateCollection transaction332    const alicePrivateKey = privateKey('//Alice');333334    let modeprm = {};335    if (mode.type === 'NFT') {336      modeprm = {nft: null};337    } else if (mode.type === 'Fungible') {338      modeprm = {fungible: mode.decimalPoints};339    } else if (mode.type === 'ReFungible') {340      modeprm = {refungible: null};341    }342343    const tx = api.tx.unique.createCollectionEx({344      name: strToUTF16(name),345      description: strToUTF16(description),346      tokenPrefix: strToUTF16(tokenPrefix),347      mode: modeprm as any,348      schemaVersion: schemaVersion,349    });350    const events = await submitTransactionAsync(alicePrivateKey, tx);351    const result = getCreateCollectionResult(events);352353    // Get number of collections after the transaction354    const collectionCountAfter = await getCreatedCollectionCount(api);355356    // Get the collection357    const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359    // What to expect360    // tslint:disable-next-line:no-unused-expression361    expect(result.success).to.be.true;362    expect(result.collectionId).to.be.equal(collectionCountAfter);363    // tslint:disable-next-line:no-unused-expression364    expect(collection).to.be.not.null;365    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371    collectionId = result.collectionId;372  });373374  return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380  let collectionId = 0;381  await usingApi(async (api) => {382    // Get number of collections before the transaction383    const collectionCountBefore = await getCreatedCollectionCount(api);384385    // Run the CreateCollection transaction386    const alicePrivateKey = privateKey('//Alice');387388    let modeprm = {};389    if (mode.type === 'NFT') {390      modeprm = {nft: null};391    } else if (mode.type === 'Fungible') {392      modeprm = {fungible: mode.decimalPoints};393    } else if (mode.type === 'ReFungible') {394      modeprm = {refungible: null};395    }396397    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getCreateCollectionResult(events);400401    // Get number of collections after the transaction402    const collectionCountAfter = await getCreatedCollectionCount(api);403404    // Get the collection405    const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407    // What to expect408    // tslint:disable-next-line:no-unused-expression409    expect(result.success).to.be.true;410    expect(result.collectionId).to.be.equal(collectionCountAfter);411    // tslint:disable-next-line:no-unused-expression412    expect(collection).to.be.not.null;413    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420    collectionId = result.collectionId;421  });422423  return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429  await usingApi(async (api) => {430    // Get number of collections before the transaction431    const collectionCountBefore = await getCreatedCollectionCount(api);432433    // Run the CreateCollection transaction434    const alicePrivateKey = privateKey('//Alice');435436    let modeprm = {};437    if (mode.type === 'NFT') {438      modeprm = {nft: null};439    } else if (mode.type === 'Fungible') {440      modeprm = {fungible: mode.decimalPoints};441    } else if (mode.type === 'ReFungible') {442      modeprm = {refungible: null};443    }444445    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});446    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449    // Get number of collections after the transaction450    const collectionCountAfter = await getCreatedCollectionCount(api);451452    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453  });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459  let modeprm = {};460  if (mode.type === 'NFT') {461    modeprm = {nft: null};462  } else if (mode.type === 'Fungible') {463    modeprm = {fungible: mode.decimalPoints};464  } else if (mode.type === 'ReFungible') {465    modeprm = {refungible: null};466  }467468  await usingApi(async (api) => {469    // Get number of collections before the transaction470    const collectionCountBefore = await getCreatedCollectionCount(api);471472    // Run the CreateCollection transaction473    const alicePrivateKey = privateKey('//Alice');474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477    // Get number of collections after the transaction478    const collectionCountAfter = await getCreatedCollectionCount(api);479480    // What to expect481    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482  });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486  let bal = 0n;487  let unused;488  do {489    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490    const keyring = new Keyring({type: 'sr25519'});491    unused = keyring.addFromUri(`//${randomSeed}`);492    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493  } while (bal !== 0n);494  return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506  const totalNumber = await getCreatedCollectionCount(api);507  const newCollection: number = totalNumber + 1;508  return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512  let success = false;513  events.forEach(({event: {method}}) => {514    if (method == 'ExtrinsicSuccess') {515      success = true;516    }517  });518  return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api) => {523    // Run the DestroyCollection transaction524    const alicePrivateKey = privateKey(senderSeed);525    const tx = api.tx.unique.destroyCollection(collectionId);526    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527  });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531  await usingApi(async (api) => {532    // Run the DestroyCollection transaction533    const alicePrivateKey = privateKey(senderSeed);534    const tx = api.tx.unique.destroyCollection(collectionId);535    const events = await submitTransactionAsync(alicePrivateKey, tx);536    const result = getDestroyResult(events);537    expect(result).to.be.true;538539    // What to expect540    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541  });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545  await usingApi(async (api) => {546    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547    const events = await submitTransactionAsync(sender, tx);548    const result = getGenericResult(events);549550    expect(result.success).to.be.true;551  });552}553554export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {555  await usingApi(async (api) => {556    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);557    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;558    const result = getGenericResult(events);559560    expect(result.success).to.be.false;561  });562}563564export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {565  await usingApi(async (api) => {566567    // Run the transaction568    const senderPrivateKey = privateKey(sender);569    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);570    const events = await submitTransactionAsync(senderPrivateKey, tx);571    const result = getGenericResult(events);572573    // Get the collection574    const collection = await queryCollectionExpectSuccess(api, collectionId);575576    // What to expect577    expect(result.success).to.be.true;578    expect(collection.sponsorship.toJSON()).to.deep.equal({579      unconfirmed: sponsor,580    });581  });582}583584export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {585  await usingApi(async (api) => {586587    // Run the transaction588    const alicePrivateKey = privateKey(sender);589    const tx = api.tx.unique.removeCollectionSponsor(collectionId);590    const events = await submitTransactionAsync(alicePrivateKey, tx);591    const result = getGenericResult(events);592593    // Get the collection594    const collection = await queryCollectionExpectSuccess(api, collectionId);595596    // What to expect597    expect(result.success).to.be.true;598    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});599  });600}601602export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {603  await usingApi(async (api) => {604605    // Run the transaction606    const alicePrivateKey = privateKey(senderSeed);607    const tx = api.tx.unique.removeCollectionSponsor(collectionId);608    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;609  });610}611612export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {613  await usingApi(async (api) => {614615    // Run the transaction616    const alicePrivateKey = privateKey(senderSeed);617    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);618    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619  });620}621622export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {623  await usingApi(async (api) => {624625    // Run the transaction626    const sender = privateKey(senderSeed);627    const tx = api.tx.unique.confirmSponsorship(collectionId);628    const events = await submitTransactionAsync(sender, tx);629    const result = getGenericResult(events);630631    // Get the collection632    const collection = await queryCollectionExpectSuccess(api, collectionId);633634    // What to expect635    expect(result.success).to.be.true;636    expect(collection.sponsorship.toJSON()).to.be.deep.equal({637      confirmed: sender.address,638    });639  });640}641642643export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {644  await usingApi(async (api) => {645646    // Run the transaction647    const sender = privateKey(senderSeed);648    const tx = api.tx.unique.confirmSponsorship(collectionId);649    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;650  });651}652653export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {654655  await usingApi(async (api) => {656    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {665666  await usingApi(async (api) => {667    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);668    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;669    const result = getGenericResult(events);670671    expect(result.success).to.be.false;672  });673}674675export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);678    const events = await submitTransactionAsync(sender, tx);679    const result = getGenericResult(events);680681    expect(result.success).to.be.true;682  });683}684685export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {686  await usingApi(async (api) => {687    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);688    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;689    const result = getGenericResult(events);690691    expect(result.success).to.be.false;692  });693}694695export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {696697  await usingApi(async (api) => {698699    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);700    const events = await submitTransactionAsync(sender, tx);701    const result = getGenericResult(events);702703    expect(result.success).to.be.true;704  });705}706707export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {708709  await usingApi(async (api) => {710711    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);712    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;713    const result = getGenericResult(events);714715    expect(result.success).to.be.false;716  });717}718719export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {720  await usingApi(async (api) => {721    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);722    const events = await submitTransactionAsync(sender, tx);723    const result = getGenericResult(events);724725    expect(result.success).to.be.true;726  });727}728729export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {730  await usingApi(async (api) => {731    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);732    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;733    const result = getGenericResult(events);734735    expect(result.success).to.be.false;736  });737}738739export async function getNextSponsored(740  api: ApiPromise,741  collectionId: number,742  account: string | CrossAccountId,743  tokenId: number,744): Promise<number> {745  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));746}747748export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {749  await usingApi(async (api) => {750    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);751    const events = await submitTransactionAsync(sender, tx);752    const result = getGenericResult(events);753754    expect(result.success).to.be.true;755  });756}757758export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {759  let allowlisted = false;760  await usingApi(async (api) => {761    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;762  });763  return allowlisted;764}765766export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {767  await usingApi(async (api) => {768    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());769    const events = await submitTransactionAsync(sender, tx);770    const result = getGenericResult(events);771772    expect(result.success).to.be.true;773  });774}775776export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {777  await usingApi(async (api) => {778    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());779    const events = await submitTransactionAsync(sender, tx);780    const result = getGenericResult(events);781782    expect(result.success).to.be.true;783  });784}785786export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {787  await usingApi(async (api) => {788    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());789    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790    const result = getGenericResult(events);791792    expect(result.success).to.be.false;793  });794}795796export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {797  await usingApi(async (api) => {798    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));799    const events = await submitTransactionAsync(sender, tx);800    const result = getGenericResult(events);801802    expect(result.success).to.be.true;803  });804}805806export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {807  await usingApi(async (api) => {808    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));809    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;810  });811}812813export interface CreateFungibleData {814  readonly Value: bigint;815}816817export interface CreateReFungibleData { }818export interface CreateNftData { }819820export type CreateItemData = {821  NFT: CreateNftData;822} | {823  Fungible: CreateFungibleData;824} | {825  ReFungible: CreateReFungibleData;826};827828export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {829  await usingApi(async (api) => {830    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);831    // if burning token by admin - use adminButnItemExpectSuccess832    expect(balanceBefore >= BigInt(value)).to.be.true;833834    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);835    const events = await submitTransactionAsync(sender, tx);836    const result = getGenericResult(events);837    expect(result.success).to.be.true;838839    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);840    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);841  });842}843844export async function845approveExpectSuccess(846  collectionId: number,847  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,848) {849  await usingApi(async (api: ApiPromise) => {850    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);851    const events = await submitTransactionAsync(owner, approveUniqueTx);852    const result = getGenericResult(events);853    expect(result.success).to.be.true;854855    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));856  });857}858859export async function adminApproveFromExpectSuccess(860  collectionId: number,861  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,862) {863  await usingApi(async (api: ApiPromise) => {864    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);865    const events = await submitTransactionAsync(admin, approveUniqueTx);866    const result = getGenericResult(events);867    expect(result.success).to.be.true;868869    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));870  });871}872873export async function874transferFromExpectSuccess(875  collectionId: number,876  tokenId: number,877  accountApproved: IKeyringPair,878  accountFrom: IKeyringPair | CrossAccountId,879  accountTo: IKeyringPair | CrossAccountId,880  value: number | bigint = 1,881  type = 'NFT',882) {883  await usingApi(async (api: ApiPromise) => {884    const from = normalizeAccountId(accountFrom);885    const to = normalizeAccountId(accountTo);886    let balanceBefore = 0n;887    if (type === 'Fungible' || type === 'ReFungible') {888      balanceBefore = await getBalance(api, collectionId, to, tokenId);889    }890    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);891    const events = await submitTransactionAsync(accountApproved, transferFromTx);892    const result = getCreateItemResult(events);893    // tslint:disable-next-line:no-unused-expression894    expect(result.success).to.be.true;895    if (type === 'NFT') {896      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);897    }898    if (type === 'Fungible') {899      const balanceAfter = await getBalance(api, collectionId, to, tokenId);900      if (JSON.stringify(to) !== JSON.stringify(from)) {901        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));902      } else {903        expect(balanceAfter).to.be.equal(balanceBefore);904      }905    }906    if (type === 'ReFungible') {907      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));908    }909  });910}911912export async function913transferFromExpectFail(914  collectionId: number,915  tokenId: number,916  accountApproved: IKeyringPair,917  accountFrom: IKeyringPair,918  accountTo: IKeyringPair,919  value: number | bigint = 1,920) {921  await usingApi(async (api: ApiPromise) => {922    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);923    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;924    const result = getCreateCollectionResult(events);925    // tslint:disable-next-line:no-unused-expression926    expect(result.success).to.be.false;927  });928}929930/* eslint no-async-promise-executor: "off" */931async function getBlockNumber(api: ApiPromise): Promise<number> {932  return new Promise<number>(async (resolve) => {933    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {934      unsubscribe();935      resolve(head.number.toNumber());936    });937  });938}939940export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {941  await usingApi(async (api) => {942    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));943    const events = await submitTransactionAsync(sender, changeAdminTx);944    const result = getCreateCollectionResult(events);945    expect(result.success).to.be.true;946  });947}948949export async function950getFreeBalance(account: IKeyringPair): Promise<bigint> {951  let balance = 0n;952  await usingApi(async (api) => {953    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());954  });955956  return balance;957}958959export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {960  const tx = api.tx.balances.transfer(target, amount);961  const events = await submitTransactionAsync(source, tx);962  const result = getGenericResult(events);963  expect(result.success).to.be.true;964}965966export async function967scheduleTransferExpectSuccess(968  collectionId: number,969  tokenId: number,970  sender: IKeyringPair,971  recipient: IKeyringPair,972  value: number | bigint = 1,973  blockSchedule: number,974) {975  await usingApi(async (api: ApiPromise) => {976    const blockNumber: number | undefined = await getBlockNumber(api);977    const expectedBlockNumber = blockNumber + blockSchedule;978979    expect(blockNumber).to.be.greaterThan(0);980    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);981    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);982983    await submitTransactionAsync(sender, scheduleTx);984985    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();986987    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));988989    // sleep for 4 blocks990    await waitNewBlocks(blockSchedule + 1);991992    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();993994    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));995    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);996  });997}9989991000export async function1001transferExpectSuccess(1002  collectionId: number,1003  tokenId: number,1004  sender: IKeyringPair,1005  recipient: IKeyringPair | CrossAccountId,1006  value: number | bigint = 1,1007  type = 'NFT',1008) {1009  await usingApi(async (api: ApiPromise) => {1010    const from = normalizeAccountId(sender);1011    const to = normalizeAccountId(recipient);10121013    let balanceBefore = 0n;1014    if (type === 'Fungible') {1015      balanceBefore = await getBalance(api, collectionId, to, tokenId);1016    }1017    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1018    const events = await executeTransaction(api, sender, transferTx);10191020    const result = getTransferResult(api, events);1021    expect(result.collectionId).to.be.equal(collectionId);1022    expect(result.itemId).to.be.equal(tokenId);1023    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1024    expect(result.recipient).to.be.deep.equal(to);1025    expect(result.value).to.be.equal(BigInt(value));10261027    if (type === 'NFT') {1028      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1029    }1030    if (type === 'Fungible') {1031      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1032      if (JSON.stringify(to) !== JSON.stringify(from)) {1033        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1034      } else {1035        expect(balanceAfter).to.be.equal(balanceBefore);1036      }1037    }1038    if (type === 'ReFungible') {1039      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1040    }1041  });1042}10431044export async function1045transferExpectFailure(1046  collectionId: number,1047  tokenId: number,1048  sender: IKeyringPair,1049  recipient: IKeyringPair | CrossAccountId,1050  value: number | bigint = 1,1051) {1052  await usingApi(async (api: ApiPromise) => {1053    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1054    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1055    const result = getGenericResult(events);1056    // if (events && Array.isArray(events)) {1057    //   const result = getCreateCollectionResult(events);1058    // tslint:disable-next-line:no-unused-expression1059    expect(result.success).to.be.false;1060    //}1061  });1062}10631064export async function1065approveExpectFail(1066  collectionId: number,1067  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1068) {1069  await usingApi(async (api: ApiPromise) => {1070    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1071    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1072    const result = getCreateCollectionResult(events);1073    // tslint:disable-next-line:no-unused-expression1074    expect(result.success).to.be.false;1075  });1076}10771078export async function getBalance(1079  api: ApiPromise,1080  collectionId: number,1081  owner: string | CrossAccountId,1082  token: number,1083): Promise<bigint> {1084  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1085}1086export async function getTokenOwner(1087  api: ApiPromise,1088  collectionId: number,1089  token: number,1090): Promise<CrossAccountId> {1091  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1092  if (owner == null) throw new Error('owner == null');1093  return normalizeAccountId(owner);1094}1095export async function getTopmostTokenOwner(1096  api: ApiPromise,1097  collectionId: number,1098  token: number,1099): Promise<CrossAccountId> {1100  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1101  if (owner == null) throw new Error('owner == null');1102  return normalizeAccountId(owner);1103}1104export async function isTokenExists(1105  api: ApiPromise,1106  collectionId: number,1107  token: number,1108): Promise<boolean> {1109  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1110}1111export async function getLastTokenId(1112  api: ApiPromise,1113  collectionId: number,1114): Promise<number> {1115  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1116}1117export async function getAdminList(1118  api: ApiPromise,1119  collectionId: number,1120): Promise<string[]> {1121  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1122}1123export async function getConstMetadata(1124  api: ApiPromise,1125  collectionId: number,1126  tokenId: number,1127): Promise<number[]> {1128  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1129}11301131export async function createFungibleItemExpectSuccess(1132  sender: IKeyringPair,1133  collectionId: number,1134  data: CreateFungibleData,1135  owner: CrossAccountId | string = sender.address,1136) {1137  return await usingApi(async (api) => {1138    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11391140    const events = await submitTransactionAsync(sender, tx);1141    const result = getCreateItemResult(events);11421143    expect(result.success).to.be.true;1144    return result.itemId;1145  });1146}11471148export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1149  let newItemId = 0;1150  await usingApi(async (api) => {1151    const to = normalizeAccountId(owner);1152    const itemCountBefore = await getLastTokenId(api, collectionId);1153    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11541155    let tx;1156    if (createMode === 'Fungible') {1157      const createData = {fungible: {value: 10}};1158      tx = api.tx.unique.createItem(collectionId, to, createData as any);1159    } else if (createMode === 'ReFungible') {1160      const createData = {refungible: {const_data: [], pieces: 100}};1161      tx = api.tx.unique.createItem(collectionId, to, createData as any);1162    } else {1163      const createData = {nft: {const_data: []}};1164      tx = api.tx.unique.createItem(collectionId, to, createData as any);1165    }11661167    const events = await submitTransactionAsync(sender, tx);1168    const result = getCreateItemResult(events);11691170    const itemCountAfter = await getLastTokenId(api, collectionId);1171    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11721173    // What to expect1174    // tslint:disable-next-line:no-unused-expression1175    expect(result.success).to.be.true;1176    if (createMode === 'Fungible') {1177      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1178    } else {1179      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1180    }1181    expect(collectionId).to.be.equal(result.collectionId);1182    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1183    expect(to).to.be.deep.equal(result.recipient);1184    newItemId = result.itemId;1185  });1186  return newItemId;1187}11881189export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1190  await usingApi(async (api) => {1191    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11921193    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1194    const result = getCreateItemResult(events);11951196    expect(result.success).to.be.false;1197  });1198}11991200export async function setPublicAccessModeExpectSuccess(1201  sender: IKeyringPair, collectionId: number,1202  accessMode: 'Normal' | 'AllowList',1203) {1204  await usingApi(async (api) => {12051206    // Run the transaction1207    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1208    const events = await submitTransactionAsync(sender, tx);1209    const result = getGenericResult(events);12101211    // Get the collection1212    const collection = await queryCollectionExpectSuccess(api, collectionId);12131214    // What to expect1215    // tslint:disable-next-line:no-unused-expression1216    expect(result.success).to.be.true;1217    expect(collection.access.toHuman()).to.be.equal(accessMode);1218  });1219}12201221export async function setPublicAccessModeExpectFail(1222  sender: IKeyringPair, collectionId: number,1223  accessMode: 'Normal' | 'AllowList',1224) {1225  await usingApi(async (api) => {12261227    // Run the transaction1228    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1229    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1230    const result = getGenericResult(events);12311232    // What to expect1233    // tslint:disable-next-line:no-unused-expression1234    expect(result.success).to.be.false;1235  });1236}12371238export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1239  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1240}12411242export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1243  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1244}12451246export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1247  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1248}12491250export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1251  await usingApi(async (api) => {12521253    // Run the transaction1254    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1255    const events = await submitTransactionAsync(sender, tx);1256    const result = getGenericResult(events);1257    expect(result.success).to.be.true;12581259    // Get the collection1260    const collection = await queryCollectionExpectSuccess(api, collectionId);12611262    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1263  });1264}12651266export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1267  await setMintPermissionExpectSuccess(sender, collectionId, true);1268}12691270export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1271  await usingApi(async (api) => {1272    // Run the transaction1273    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1274    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1275    const result = getCreateCollectionResult(events);1276    // tslint:disable-next-line:no-unused-expression1277    expect(result.success).to.be.false;1278  });1279}12801281export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1282  await usingApi(async (api) => {1283    // Run the transaction1284    const tx = api.tx.unique.setChainLimits(limits);1285    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1286    const result = getCreateCollectionResult(events);1287    // tslint:disable-next-line:no-unused-expression1288    expect(result.success).to.be.false;1289  });1290}12911292export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1293  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1294}12951296export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1297  await usingApi(async (api) => {1298    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12991300    // Run the transaction1301    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1302    const events = await submitTransactionAsync(sender, tx);1303    const result = getGenericResult(events);1304    expect(result.success).to.be.true;13051306    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1307  });1308}13091310export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1311  await usingApi(async (api) => {13121313    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13141315    // Run the transaction1316    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1317    const events = await submitTransactionAsync(sender, tx);1318    const result = getGenericResult(events);1319    expect(result.success).to.be.true;13201321    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1322  });1323}13241325export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1326  await usingApi(async (api) => {13271328    // Run the transaction1329    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1330    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1331    const result = getGenericResult(events);13321333    // What to expect1334    // tslint:disable-next-line:no-unused-expression1335    expect(result.success).to.be.false;1336  });1337}13381339export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1340  await usingApi(async (api) => {1341    // Run the transaction1342    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1343    const events = await submitTransactionAsync(sender, tx);1344    const result = getGenericResult(events);13451346    // What to expect1347    // tslint:disable-next-line:no-unused-expression1348    expect(result.success).to.be.true;1349  });1350}13511352export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1353  await usingApi(async (api) => {1354    // Run the transaction1355    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1356    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357    const result = getGenericResult(events);13581359    // What to expect1360    // tslint:disable-next-line:no-unused-expression1361    expect(result.success).to.be.false;1362  });1363}13641365export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1366  : Promise<UpDataStructsRpcCollection | null> => {1367  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1368};13691370export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1371  // set global object - collectionsCount1372  return (await api.rpc.unique.collectionStats()).created.toNumber();1373};13741375export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1376  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1377}13781379export async function waitNewBlocks(blocksCount = 1): Promise<void> {1380  await usingApi(async (api) => {1381    const promise = new Promise<void>(async (resolve) => {1382      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1383        if (blocksCount > 0) {1384          blocksCount--;1385        } else {1386          unsubscribe();1387          resolve();1388        }1389      });1390    });1391    return promise;1392  });1393}