git.delta.rocks / unique-network / refs/commits / 008a188c3ea9

difftreelog

Remove variableOnChainSchema

Daniel Shiposha2022-05-12parent: #edc04ac.patch.diff
in: master

12 files changed

modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
 use up_data_structs::{
 	CollectionMode, CreateCollectionData, CollectionId, MAX_COLLECTION_NAME_LENGTH,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, OFFCHAIN_SCHEMA_LIMIT,
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+	CONST_ON_CHAIN_SCHEMA_LIMIT,
 };
 use frame_support::{
 	traits::{Currency, Get},
@@ -67,7 +67,6 @@
 	let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
 	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
 	let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
-	let variable_on_chain_schema = create_data::<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>();
 	let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
 	handler(
 		owner,
@@ -77,7 +76,6 @@
 			description,
 			token_prefix,
 			offchain_schema,
-			variable_on_chain_schema,
 			const_on_chain_schema,
 			..Default::default()
 		},
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -482,12 +482,6 @@
 					.expect("data has lower bounds than field");
 					Self::set_field_raw(
 						id,
-						CollectionField::VariableOnChainSchema,
-						v.variable_on_chain_schema.clone().into_inner(),
-					)
-					.expect("data has lower bounds than field");
-					Self::set_field_raw(
-						id,
 						CollectionField::ConstOnChainSchema,
 						v.const_on_chain_schema.clone().into_inner(),
 					)
@@ -621,11 +615,6 @@
 				CollectionField::ConstOnChainSchema,
 			))
 			.into_inner(),
-			variable_on_chain_schema: <CollectionData<T>>::get((
-				collection,
-				CollectionField::VariableOnChainSchema,
-			))
-			.into_inner(),
 			token_property_permissions,
 			properties,
 		})
@@ -723,12 +712,6 @@
 			id,
 			CollectionField::OffchainSchema,
 			data.offchain_schema.into_inner(),
-		)
-		.expect("data has lower bounds than field");
-		Self::set_field_raw(
-			id,
-			CollectionField::VariableOnChainSchema,
-			data.variable_on_chain_schema.into_inner(),
 		)
 		.expect("data has lower bounds than field");
 		Self::set_field_raw(
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -146,14 +146,6 @@
 		let data = create_var_data(b);
 	}: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
 
-	set_variable_on_chain_schema {
-		let b in 0..VARIABLE_ON_CHAIN_SCHEMA_LIMIT;
-
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-		let data = create_var_data(b);
-	}: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
 	set_schema_version {
 		let caller: T::AccountId = account("caller", 0, SEED);
 		let collection = create_nft_collection::<T>(caller.clone())?;
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,7 +35,7 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
+	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, CustomDataLimit,
@@ -191,13 +191,6 @@
 		///
 		/// * collection_id: Globally unique collection identifier.
 		SchemaVersionSet(CollectionId),
-
-		/// Variable on chain schema was set
-		///
-		/// # Arguments
-		///
-		/// * collection_id: Globally unique collection identifier.
-		VariableOnChainSchemaSet(CollectionId),
 	}
 }
 
@@ -1083,38 +1076,6 @@
 			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
 
 			<Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(
-				collection_id
-			));
-			Ok(())
-		}
-
-		/// Set variable on-chain data schema.
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner
-		/// * Collection Admin
-		///
-		/// # Arguments
-		///
-		/// * collection_id.
-		///
-		/// * schema: String representing the variable on-chain data schema.
-		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]
-		#[transactional]
-		pub fn set_variable_on_chain_schema (
-			origin,
-			collection_id: CollectionId,
-			schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>
-		) -> DispatchResult {
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
-			// =========
-
-			<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::VariableOnChainSchema, schema.into_inner())?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::VariableOnChainSchemaSet(
 				collection_id
 			));
 			Ok(())
modifiedpallets/unique/src/weights.rsdiffbeforeafterboth
--- a/pallets/unique/src/weights.rs
+++ b/pallets/unique/src/weights.rs
@@ -47,7 +47,6 @@
 	fn set_transfers_enabled_flag() -> Weight;
 	fn set_offchain_schema(b: u32, ) -> Weight;
 	fn set_const_on_chain_schema(b: u32, ) -> Weight;
-	fn set_variable_on_chain_schema(b: u32, ) -> Weight;
 	fn set_schema_version() -> Weight;
 	fn set_collection_limits() -> Weight;
 	fn set_meta_update_permission_flag() -> Weight;
@@ -156,12 +155,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_const_on_chain_schema(_b: u32, ) -> Weight {
 		(14_984_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_variable_on_chain_schema(_b: u32, ) -> Weight {
-		(15_196_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -287,12 +280,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_const_on_chain_schema(_b: u32, ) -> Weight {
 		(14_984_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_variable_on_chain_schema(_b: u32, ) -> Weight {
-		(15_196_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
@@ -76,11 +76,9 @@
 
 // Schema limits
 pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;
-pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;
 pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;
 
 pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;
-// u32::max is not const: OFFCHAIN_SCHEMA_LIMIT.max(VARIABLE_ON_CHAIN_SCHEMA_LIMIT).max(CONST_ON_CHAIN_SCHEMA_LIMIT);
 
 pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;
 pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
@@ -303,8 +301,6 @@
 	#[version(2.., upper(limits.into()))]
 	pub limits: CollectionLimitsVersion2,
 
-	#[version(..2)]
-	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
 	#[version(..2)]
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
 
@@ -326,7 +322,6 @@
 	pub schema_version: SchemaVersion,
 	pub sponsorship: SponsorshipState<AccountId>,
 	pub limits: CollectionLimits,
-	pub variable_on_chain_schema: Vec<u8>,
 	pub const_on_chain_schema: Vec<u8>,
 	pub meta_update_permission: MetaUpdatePermission,
 	pub token_property_permissions: Vec<PropertyKeyPermission>,
@@ -336,7 +331,6 @@
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub enum CollectionField {
-	VariableOnChainSchema,
 	ConstOnChainSchema,
 	OffchainSchema,
 }
@@ -354,7 +348,6 @@
 	pub schema_version: Option<SchemaVersion>,
 	pub pending_sponsor: Option<AccountId>,
 	pub limits: Option<CollectionLimits>,
-	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
 	pub meta_update_permission: Option<MetaUpdatePermission>,
 	pub token_property_permissions: CollectionPropertiesPermissionsVec,
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -2423,45 +2423,6 @@
 			)),
 			b"test const on chain schema".to_vec()
 		);
-		assert_eq!(
-			<pallet_common::CollectionData<Test>>::get((
-				collection_id,
-				CollectionField::VariableOnChainSchema
-			)),
-			b"".to_vec()
-		);
-	});
-}
-
-#[test]
-fn set_variable_on_chain_schema() {
-	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
-		let origin1 = Origin::signed(1);
-		assert_ok!(Unique::set_variable_on_chain_schema(
-			origin1,
-			collection_id,
-			b"test variable on chain schema"
-				.to_vec()
-				.try_into()
-				.unwrap()
-		));
-
-		assert_eq!(
-			<pallet_common::CollectionData<Test>>::get((
-				collection_id,
-				CollectionField::ConstOnChainSchema
-			)),
-			b"".to_vec()
-		);
-		assert_eq!(
-			<pallet_common::CollectionData<Test>>::get((
-				collection_id,
-				CollectionField::VariableOnChainSchema
-			)),
-			b"test variable on chain schema".to_vec()
-		);
 	});
 }
 
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -40,20 +40,20 @@
   });
 
   it('create new collection with properties #1', async () => {
-    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}, 
-      properties: [{key: 'key1', value: 'val1'}], 
+    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+      properties: [{key: 'key1', value: 'val1'}],
       propPerm:   [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: true}]});
   });
 
   it('create new collection with properties #2', async () => {
-    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}, 
-      properties: [{key: 'key1', value: 'val1'}], 
+    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+      properties: [{key: 'key1', value: 'val1'}],
       propPerm:   [{key: 'key1', tokenOwner: false, mutable: true, collectionAdmin: false}]});
   });
 
   it('create new collection with properties #3', async () => {
-    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}, 
-      properties: [{key: 'key1', value: 'val1'}], 
+    await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+      properties: [{key: 'key1', value: 'val1'}],
       propPerm:   [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: false}]});
   });
 
@@ -73,7 +73,6 @@
         limits: {
           accountTokenOwnershipLimit: 3,
         },
-        variableOnChainSchema: '0x222222',
         constOnChainSchema: '0x333333',
         metaUpdatePermission: 'Admin',
       });
@@ -91,7 +90,6 @@
       expect(collection.schemaVersion.isUnique).to.be.true;
       expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
       expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
-      expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
       expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
       expect(collection.metaUpdatePermission.isAdmin).to.be.true;
     });
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -11,7 +11,7 @@
 // todo skip
 describe('Migration testing for pallet-common', () => {
   let alice: IKeyringPair;
-  
+
   before(async() => {
     await usingApi(async () => {
       alice = privateKey('//Alice');
@@ -36,7 +36,6 @@
         limits: {
           accountTokenOwnershipLimit: 3,
         },
-        variableOnChainSchema: '0x222222',
         constOnChainSchema: '0x333333',
         metaUpdatePermission: 'Admin',
       });
@@ -78,13 +77,11 @@
 
     await usingApi(async api => {
       const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;
-      
+
       // Make sure the extra fields are what they should be
-      const variableOnChainSchema = await api.query.common.collectionData(collectionId, 'VariableOnChainSchema');
       const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');
       const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');
 
-      expect(variableOnChainSchema.toHex()).to.be.deep.equal((collectionOld.variableOnChainSchema));
       expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);
       expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);
       expect(collectionNew).to.have.nested.property('limits.nestingRule');
@@ -93,10 +90,8 @@
       delete collectionNew.limits.nestingRule;
       delete collectionOld.constOnChainSchema;
       delete collectionOld.offchainSchema;
-      delete collectionOld.variableOnChainSchema;
 
       expect(collectionNew).to.be.deep.equal(collectionOld);
     });
   });
 });
-  
\ No newline at end of file
modifiedtests/src/setChainLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setChainLimits.test.ts
+++ b/tests/src/setChainLimits.test.ts
@@ -44,7 +44,6 @@
         fungibleSponsorTransferTimeout: 1,
         refungibleSponsorTransferTimeout: 1,
         offchainSchemaLimit: 1,
-        variableOnChainSchemaLimit: 1,
         constOnChainSchemaLimit: 1,
       };
     });
deletedtests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setVariableOnChainSchema.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {Keyring} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  destroyCollectionExpectSuccess,
-  addCollectionAdminExpectSuccess,
-  queryCollectionExpectSuccess,
-  getCreatedCollectionCount,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let schema: any;
-let largeSchema: any;
-
-before(async () => {
-  await usingApi(async () => {
-    const keyring = new Keyring({type: 'sr25519'});
-    alice = keyring.addFromUri('//Alice');
-    bob = keyring.addFromUri('//Bob');
-    schema = '0x31';
-    largeSchema = new Array(8 * 1024 + 10).fill(0xff);
-
-  });
-});
-describe('Integration Test ext. setVariableOnChainSchema()', () => {
-
-  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(alice, setSchema);
-    });
-  });
-
-  it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(alice, setSchema);
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
-
-    });
-  });
-});
-
-describe('Integration Test ext. collection admin setVariableOnChainSchema()', () => {
-
-  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(bob, setSchema);
-    });
-  });
-
-  it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(bob, setSchema);
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
-
-    });
-  });
-});
-
-describe('Negative Integration Test ext. setVariableOnChainSchema()', () => {
-
-  it('Set a non-existent collection', async () => {
-    await usingApi(async (api) => {
-      // tslint:disable-next-line: radix
-      const collectionId = await getCreatedCollectionCount(api) + 1;
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Set a previously deleted collection', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      await destroyCollectionExpectSuccess(collectionId);
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Set invalid data in schema (size too large:> 8kB)', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, largeSchema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Execute method not on behalf of the collection owner', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
-    });
-  });
-
-});
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  variableOnChainSchemaLimit: number;140  constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144  owner: IReFungibleOwner[];145  constData: number[];146  variableData: number[];147}148149export function uniqueEventMessage(events: EventRecord[]): IGetMessage {150  let checkMsgUnqMethod = '';151  let checkMsgTrsMethod = '';152  let checkMsgSysMethod = '';153  events.forEach(({event: {method, section}}) => {154    if (section === 'common') {155      checkMsgUnqMethod = method;156    } else if (section === 'treasury') {157      checkMsgTrsMethod = method;158    } else if (section === 'system') {159      checkMsgSysMethod = method;160    } else { return null; }161  });162  const result: IGetMessage = {163    checkMsgUnqMethod,164    checkMsgTrsMethod,165    checkMsgSysMethod,166  };167  return result;168}169170export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {171  const event = events.find(r => check(r.event));172  if (!event) return;173  return event.event as T;174}175176export function getGenericResult(events: EventRecord[]): GenericResult {177  const result: GenericResult = {178    success: false,179  };180  events.forEach(({event: {method}}) => {181    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);182    if (method === 'ExtrinsicSuccess') {183      result.success = true;184    }185  });186  return result;187}188189190191export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {192  let success = false;193  let collectionId = 0;194  events.forEach(({event: {data, method, section}}) => {195    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);196    if (method == 'ExtrinsicSuccess') {197      success = true;198    } else if ((section == 'common') && (method == 'CollectionCreated')) {199      collectionId = parseInt(data[0].toString(), 10);200    }201  });202  const result: CreateCollectionResult = {203    success,204    collectionId,205  };206  return result;207}208209export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {210  let success = false;211  let collectionId = 0;212  let itemId = 0;213  let recipient;214215  const results : CreateItemResult[]  = [];216217  events.forEach(({event: {data, method, section}}) => {218    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);219    if (method == 'ExtrinsicSuccess') {220      success = true;221    } else if ((section == 'common') && (method == 'ItemCreated')) {222      collectionId = parseInt(data[0].toString(), 10);223      itemId = parseInt(data[1].toString(), 10);224      recipient = normalizeAccountId(data[2].toJSON() as any);225226      const itemRes: CreateItemResult = {227        success,228        collectionId,229        itemId,230        recipient,231      };232233      results.push(itemRes);234    }235  });236237  return results;238}239240export function getCreateItemResult(events: EventRecord[]): CreateItemResult {241  let success = false;242  let collectionId = 0;243  let itemId = 0;244  let recipient;245  events.forEach(({event: {data, method, section}}) => {246    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);247    if (method == 'ExtrinsicSuccess') {248      success = true;249    } else if ((section == 'common') && (method == 'ItemCreated')) {250      collectionId = parseInt(data[0].toString(), 10);251      itemId = parseInt(data[1].toString(), 10);252      recipient = normalizeAccountId(data[2].toJSON() as any);253    }254  });255  const result: CreateItemResult = {256    success,257    collectionId,258    itemId,259    recipient,260  };261  return result;262}263264export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {265  for (const {event} of events) {266    if (api.events.common.Transfer.is(event)) {267      const [collection, token, sender, recipient, value] = event.data;268      return {269        collectionId: collection.toNumber(),270        itemId: token.toNumber(),271        sender: normalizeAccountId(sender.toJSON() as any),272        recipient: normalizeAccountId(recipient.toJSON() as any),273        value: value.toBigInt(),274      };275    }276  }277  throw new Error('no transfer event');278}279280interface Nft {281  type: 'NFT';282}283284interface Fungible {285  type: 'Fungible';286  decimalPoints: number;287}288289interface ReFungible {290  type: 'ReFungible';291}292293type CollectionMode = Nft | Fungible | ReFungible;294295export type Property = {296  key: any,297  value: any,298};299300type PropertyPermission = {301  key: any,302  mutable: boolean;303  collectionAdmin: boolean;304  tokenOwner: boolean;305}306307export type CreateCollectionParams = {308  mode: CollectionMode,309  name: string,310  description: string,311  tokenPrefix: string,312  schemaVersion: string,313  properties?: Array<Property>,314  propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318  description: 'description',319  mode: {type: 'NFT'},320  name: 'name',321  tokenPrefix: 'prefix',322  schemaVersion: 'ImageURL',323};324325export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {326  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};327328  let collectionId = 0;329  await usingApi(async (api) => {330    // Get number of collections before the transaction331    const collectionCountBefore = await getCreatedCollectionCount(api);332333    // Run the CreateCollection transaction334    const alicePrivateKey = privateKey('//Alice');335336    let modeprm = {};337    if (mode.type === 'NFT') {338      modeprm = {nft: null};339    } else if (mode.type === 'Fungible') {340      modeprm = {fungible: mode.decimalPoints};341    } else if (mode.type === 'ReFungible') {342      modeprm = {refungible: null};343    }344345    const tx = api.tx.unique.createCollectionEx({346      name: strToUTF16(name),347      description: strToUTF16(description),348      tokenPrefix: strToUTF16(tokenPrefix),349      mode: modeprm as any,350      schemaVersion: schemaVersion,351    });352    const events = await submitTransactionAsync(alicePrivateKey, tx);353    const result = getCreateCollectionResult(events);354355    // Get number of collections after the transaction356    const collectionCountAfter = await getCreatedCollectionCount(api);357358    // Get the collection359    const collection = await queryCollectionExpectSuccess(api, result.collectionId);360361    // What to expect362    // tslint:disable-next-line:no-unused-expression363    expect(result.success).to.be.true;364    expect(result.collectionId).to.be.equal(collectionCountAfter);365    // tslint:disable-next-line:no-unused-expression366    expect(collection).to.be.not.null;367    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');368    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));369    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);370    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);371    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);372373    collectionId = result.collectionId;374  });375376  return collectionId;377}378379export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {380  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};381382  let collectionId = 0;383  await usingApi(async (api) => {384    // Get number of collections before the transaction385    const collectionCountBefore = await getCreatedCollectionCount(api);386387    // Run the CreateCollection transaction388    const alicePrivateKey = privateKey('//Alice');389390    let modeprm = {};391    if (mode.type === 'NFT') {392      modeprm = {nft: null};393    } else if (mode.type === 'Fungible') {394      modeprm = {fungible: mode.decimalPoints};395    } else if (mode.type === 'ReFungible') {396      modeprm = {refungible: null};397    }398399    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});400    const events = await submitTransactionAsync(alicePrivateKey, tx);401    const result = getCreateCollectionResult(events);402403    // Get number of collections after the transaction404    const collectionCountAfter = await getCreatedCollectionCount(api);405406    // Get the collection407    const collection = await queryCollectionExpectSuccess(api, result.collectionId);408409    // What to expect410    // tslint:disable-next-line:no-unused-expression411    expect(result.success).to.be.true;412    expect(result.collectionId).to.be.equal(collectionCountAfter);413    // tslint:disable-next-line:no-unused-expression414    expect(collection).to.be.not.null;415    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');416    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));417    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);418    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);419    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);420421422    collectionId = result.collectionId;423  });424425  return collectionId;426}427428export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {429  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431  const collectionId = 0;432  await usingApi(async (api) => {433    // Get number of collections before the transaction434    const collectionCountBefore = await getCreatedCollectionCount(api);435436    // Run the CreateCollection transaction437    const alicePrivateKey = privateKey('//Alice');438439    let modeprm = {};440    if (mode.type === 'NFT') {441      modeprm = {nft: null};442    } else if (mode.type === 'Fungible') {443      modeprm = {fungible: mode.decimalPoints};444    } else if (mode.type === 'ReFungible') {445      modeprm = {refungible: null};446    }447448    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});449    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;450451452    // Get number of collections after the transaction453    const collectionCountAfter = await getCreatedCollectionCount(api);454455    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');456  });457}458459export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {460  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};461462  let modeprm = {};463  if (mode.type === 'NFT') {464    modeprm = {nft: null};465  } else if (mode.type === 'Fungible') {466    modeprm = {fungible: mode.decimalPoints};467  } else if (mode.type === 'ReFungible') {468    modeprm = {refungible: null};469  }470471  await usingApi(async (api) => {472    // Get number of collections before the transaction473    const collectionCountBefore = await getCreatedCollectionCount(api);474475    // Run the CreateCollection transaction476    const alicePrivateKey = privateKey('//Alice');477    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});478    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479480    // Get number of collections after the transaction481    const collectionCountAfter = await getCreatedCollectionCount(api);482483    // What to expect484    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');485  });486}487488export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {489  let bal = 0n;490  let unused;491  do {492    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;493    const keyring = new Keyring({type: 'sr25519'});494    unused = keyring.addFromUri(`//${randomSeed}`);495    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();496  } while (bal !== 0n);497  return unused;498}499500export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {501  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();502}503504export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {505  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));506}507508export async function findNotExistingCollection(api: ApiPromise): Promise<number> {509  const totalNumber = await getCreatedCollectionCount(api);510  const newCollection: number = totalNumber + 1;511  return newCollection;512}513514function getDestroyResult(events: EventRecord[]): boolean {515  let success = false;516  events.forEach(({event: {method}}) => {517    if (method == 'ExtrinsicSuccess') {518      success = true;519    }520  });521  return success;522}523524export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {525  await usingApi(async (api) => {526    // Run the DestroyCollection transaction527    const alicePrivateKey = privateKey(senderSeed);528    const tx = api.tx.unique.destroyCollection(collectionId);529    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;530  });531}532533export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {534  await usingApi(async (api) => {535    // Run the DestroyCollection transaction536    const alicePrivateKey = privateKey(senderSeed);537    const tx = api.tx.unique.destroyCollection(collectionId);538    const events = await submitTransactionAsync(alicePrivateKey, tx);539    const result = getDestroyResult(events);540    expect(result).to.be.true;541542    // What to expect543    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;544  });545}546547export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {548  await usingApi(async (api) => {549    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);550    const events = await submitTransactionAsync(sender, tx);551    const result = getGenericResult(events);552553    expect(result.success).to.be.true;554  });555}556557export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {558  await usingApi(async (api) => {559    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);560    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561    const result = getGenericResult(events);562563    expect(result.success).to.be.false;564  });565}566567export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {568  await usingApi(async (api) => {569570    // Run the transaction571    const senderPrivateKey = privateKey(sender);572    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);573    const events = await submitTransactionAsync(senderPrivateKey, tx);574    const result = getGenericResult(events);575576    // Get the collection577    const collection = await queryCollectionExpectSuccess(api, collectionId);578579    // What to expect580    expect(result.success).to.be.true;581    expect(collection.sponsorship.toJSON()).to.deep.equal({582      unconfirmed: sponsor,583    });584  });585}586587export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {588  await usingApi(async (api) => {589590    // Run the transaction591    const alicePrivateKey = privateKey(sender);592    const tx = api.tx.unique.removeCollectionSponsor(collectionId);593    const events = await submitTransactionAsync(alicePrivateKey, tx);594    const result = getGenericResult(events);595596    // Get the collection597    const collection = await queryCollectionExpectSuccess(api, collectionId);598599    // What to expect600    expect(result.success).to.be.true;601    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});602  });603}604605export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {606  await usingApi(async (api) => {607608    // Run the transaction609    const alicePrivateKey = privateKey(senderSeed);610    const tx = api.tx.unique.removeCollectionSponsor(collectionId);611    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;612  });613}614615export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {616  await usingApi(async (api) => {617618    // Run the transaction619    const alicePrivateKey = privateKey(senderSeed);620    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);621    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;622  });623}624625export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {626  await usingApi(async (api) => {627628    // Run the transaction629    const sender = privateKey(senderSeed);630    const tx = api.tx.unique.confirmSponsorship(collectionId);631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    // Get the collection635    const collection = await queryCollectionExpectSuccess(api, collectionId);636637    // What to expect638    expect(result.success).to.be.true;639    expect(collection.sponsorship.toJSON()).to.be.deep.equal({640      confirmed: sender.address,641    });642  });643}644645646export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {647  await usingApi(async (api) => {648649    // Run the transaction650    const sender = privateKey(senderSeed);651    const tx = api.tx.unique.confirmSponsorship(collectionId);652    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;653  });654}655656export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {657658  await usingApi(async (api) => {659    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);660    const events = await submitTransactionAsync(sender, tx);661    const result = getGenericResult(events);662663    expect(result.success).to.be.true;664  });665}666667export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {668669  await usingApi(async (api) => {670    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);671    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;672    const result = getGenericResult(events);673674    expect(result.success).to.be.false;675  });676}677678export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);681    const events = await submitTransactionAsync(sender, tx);682    const result = getGenericResult(events);683684    expect(result.success).to.be.true;685  });686}687688export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {689  await usingApi(async (api) => {690    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692    const result = getGenericResult(events);693694    expect(result.success).to.be.false;695  });696}697698export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700  await usingApi(async (api) => {701702    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703    const events = await submitTransactionAsync(sender, tx);704    const result = getGenericResult(events);705706    expect(result.success).to.be.true;707  });708}709710export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {711712  await usingApi(async (api) => {713714    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);715    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;716    const result = getGenericResult(events);717718    expect(result.success).to.be.false;719  });720}721722export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {723  await usingApi(async (api) => {724    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);725    const events = await submitTransactionAsync(sender, tx);726    const result = getGenericResult(events);727728    expect(result.success).to.be.true;729  });730}731732export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {733  await usingApi(async (api) => {734    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);735    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;736    const result = getGenericResult(events);737738    expect(result.success).to.be.false;739  });740}741742export async function getNextSponsored(743  api: ApiPromise,744  collectionId: number,745  account: string | CrossAccountId,746  tokenId: number,747): Promise<number> {748  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));749}750751export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {752  await usingApi(async (api) => {753    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);754    const events = await submitTransactionAsync(sender, tx);755    const result = getGenericResult(events);756757    expect(result.success).to.be.true;758  });759}760761export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {762  let allowlisted = false;763  await usingApi(async (api) => {764    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;765  });766  return allowlisted;767}768769export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {770  await usingApi(async (api) => {771    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());772    const events = await submitTransactionAsync(sender, tx);773    const result = getGenericResult(events);774775    expect(result.success).to.be.true;776  });777}778779export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {780  await usingApi(async (api) => {781    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());782    const events = await submitTransactionAsync(sender, tx);783    const result = getGenericResult(events);784785    expect(result.success).to.be.true;786  });787}788789export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {790  await usingApi(async (api) => {791    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());792    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793    const result = getGenericResult(events);794795    expect(result.success).to.be.false;796  });797}798799export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {800  await usingApi(async (api) => {801    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));802    const events = await submitTransactionAsync(sender, tx);803    const result = getGenericResult(events);804805    expect(result.success).to.be.true;806  });807}808809export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {810  await usingApi(async (api) => {811    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));812    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;813  });814}815816export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {817  await usingApi(async (api) => {818    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));819    const events = await submitTransactionAsync(sender, tx);820    const result = getGenericResult(events);821822    expect(result.success).to.be.true;823  });824}825826export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {827  await usingApi(async (api) => {828    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));829    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;830  });831}832833export interface CreateFungibleData {834  readonly Value: bigint;835}836837export interface CreateReFungibleData { }838export interface CreateNftData { }839840export type CreateItemData = {841  NFT: CreateNftData;842} | {843  Fungible: CreateFungibleData;844} | {845  ReFungible: CreateReFungibleData;846};847848export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {849  await usingApi(async (api) => {850    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);851    // if burning token by admin - use adminButnItemExpectSuccess852    expect(balanceBefore >= BigInt(value)).to.be.true;853854    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);855    const events = await submitTransactionAsync(sender, tx);856    const result = getGenericResult(events);857    expect(result.success).to.be.true;858859    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);860    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);861  });862}863864export async function865approveExpectSuccess(866  collectionId: number,867  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,868) {869  await usingApi(async (api: ApiPromise) => {870    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);871    const events = await submitTransactionAsync(owner, approveUniqueTx);872    const result = getGenericResult(events);873    expect(result.success).to.be.true;874875    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));876  });877}878879export async function adminApproveFromExpectSuccess(880  collectionId: number,881  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,882) {883  await usingApi(async (api: ApiPromise) => {884    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);885    const events = await submitTransactionAsync(admin, approveUniqueTx);886    const result = getGenericResult(events);887    expect(result.success).to.be.true;888889    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));890  });891}892893export async function894transferFromExpectSuccess(895  collectionId: number,896  tokenId: number,897  accountApproved: IKeyringPair,898  accountFrom: IKeyringPair | CrossAccountId,899  accountTo: IKeyringPair | CrossAccountId,900  value: number | bigint = 1,901  type = 'NFT',902) {903  await usingApi(async (api: ApiPromise) => {904    const from = normalizeAccountId(accountFrom);905    const to = normalizeAccountId(accountTo);906    let balanceBefore = 0n;907    if (type === 'Fungible') {908      balanceBefore = await getBalance(api, collectionId, to, tokenId);909    }910    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);911    const events = await submitTransactionAsync(accountApproved, transferFromTx);912    const result = getCreateItemResult(events);913    // tslint:disable-next-line:no-unused-expression914    expect(result.success).to.be.true;915    if (type === 'NFT') {916      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);917    }918    if (type === 'Fungible') {919      const balanceAfter = await getBalance(api, collectionId, to, tokenId);920      if (JSON.stringify(to) !== JSON.stringify(from)) {921        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));922      } else {923        expect(balanceAfter).to.be.equal(balanceBefore);924      }925    }926    if (type === 'ReFungible') {927      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));928    }929  });930}931932export async function933transferFromExpectFail(934  collectionId: number,935  tokenId: number,936  accountApproved: IKeyringPair,937  accountFrom: IKeyringPair,938  accountTo: IKeyringPair,939  value: number | bigint = 1,940) {941  await usingApi(async (api: ApiPromise) => {942    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);943    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;944    const result = getCreateCollectionResult(events);945    // tslint:disable-next-line:no-unused-expression946    expect(result.success).to.be.false;947  });948}949950/* eslint no-async-promise-executor: "off" */951async function getBlockNumber(api: ApiPromise): Promise<number> {952  return new Promise<number>(async (resolve) => {953    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {954      unsubscribe();955      resolve(head.number.toNumber());956    });957  });958}959960export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {961  await usingApi(async (api) => {962    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));963    const events = await submitTransactionAsync(sender, changeAdminTx);964    const result = getCreateCollectionResult(events);965    expect(result.success).to.be.true;966  });967}968969export async function970getFreeBalance(account: IKeyringPair): Promise<bigint> {971  let balance = 0n;972  await usingApi(async (api) => {973    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());974  });975976  return balance;977}978979export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {980  const tx = api.tx.balances.transfer(target, amount);981  const events = await submitTransactionAsync(source, tx);982  const result = getGenericResult(events);983  expect(result.success).to.be.true;984}985986export async function987scheduleTransferExpectSuccess(988  collectionId: number,989  tokenId: number,990  sender: IKeyringPair,991  recipient: IKeyringPair,992  value: number | bigint = 1,993  blockSchedule: number,994) {995  await usingApi(async (api: ApiPromise) => {996    const blockNumber: number | undefined = await getBlockNumber(api);997    const expectedBlockNumber = blockNumber + blockSchedule;998999    expect(blockNumber).to.be.greaterThan(0);1000    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1001    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10021003    await submitTransactionAsync(sender, scheduleTx);10041005    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10061007    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10081009    // sleep for 4 blocks1010    await waitNewBlocks(blockSchedule + 1);10111012    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10131014    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1015    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1016  });1017}101810191020export async function1021transferExpectSuccess(1022  collectionId: number,1023  tokenId: number,1024  sender: IKeyringPair,1025  recipient: IKeyringPair | CrossAccountId,1026  value: number | bigint = 1,1027  type = 'NFT',1028) {1029  await usingApi(async (api: ApiPromise) => {1030    const from = normalizeAccountId(sender);1031    const to = normalizeAccountId(recipient);10321033    let balanceBefore = 0n;1034    if (type === 'Fungible') {1035      balanceBefore = await getBalance(api, collectionId, to, tokenId);1036    }1037    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1038    const events = await executeTransaction(api, sender, transferTx);10391040    const result = getTransferResult(api, events);1041    expect(result.collectionId).to.be.equal(collectionId);1042    expect(result.itemId).to.be.equal(tokenId);1043    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1044    expect(result.recipient).to.be.deep.equal(to);1045    expect(result.value).to.be.equal(BigInt(value));10461047    if (type === 'NFT') {1048      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1049    }1050    if (type === 'Fungible') {1051      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1052      if (JSON.stringify(to) !== JSON.stringify(from)) {1053        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1054      } else {1055        expect(balanceAfter).to.be.equal(balanceBefore);1056      }1057    }1058    if (type === 'ReFungible') {1059      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1060    }1061  });1062}10631064export async function1065transferExpectFailure(1066  collectionId: number,1067  tokenId: number,1068  sender: IKeyringPair,1069  recipient: IKeyringPair | CrossAccountId,1070  value: number | bigint = 1,1071) {1072  await usingApi(async (api: ApiPromise) => {1073    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1074    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1075    const result = getGenericResult(events);1076    // if (events && Array.isArray(events)) {1077    //   const result = getCreateCollectionResult(events);1078    // tslint:disable-next-line:no-unused-expression1079    expect(result.success).to.be.false;1080    //}1081  });1082}10831084export async function1085approveExpectFail(1086  collectionId: number,1087  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1088) {1089  await usingApi(async (api: ApiPromise) => {1090    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1091    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1092    const result = getCreateCollectionResult(events);1093    // tslint:disable-next-line:no-unused-expression1094    expect(result.success).to.be.false;1095  });1096}10971098export async function getBalance(1099  api: ApiPromise,1100  collectionId: number,1101  owner: string | CrossAccountId,1102  token: number,1103): Promise<bigint> {1104  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1105}1106export async function getTokenOwner(1107  api: ApiPromise,1108  collectionId: number,1109  token: number,1110): Promise<CrossAccountId> {1111  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1112  if (owner == null) throw new Error('owner == null');1113  return normalizeAccountId(owner);1114}1115export async function getTopmostTokenOwner(1116  api: ApiPromise,1117  collectionId: number,1118  token: number,1119): Promise<CrossAccountId> {1120  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1121  if (owner == null) throw new Error('owner == null');1122  return normalizeAccountId(owner);1123}1124export async function isTokenExists(1125  api: ApiPromise,1126  collectionId: number,1127  token: number,1128): Promise<boolean> {1129  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1130}1131export async function getLastTokenId(1132  api: ApiPromise,1133  collectionId: number,1134): Promise<number> {1135  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1136}1137export async function getAdminList(1138  api: ApiPromise,1139  collectionId: number,1140): Promise<string[]> {1141  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1142}1143export async function getVariableMetadata(1144  api: ApiPromise,1145  collectionId: number,1146  tokenId: number,1147): Promise<number[]> {1148  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1149}1150export async function getConstMetadata(1151  api: ApiPromise,1152  collectionId: number,1153  tokenId: number,1154): Promise<number[]> {1155  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1156}11571158export async function createFungibleItemExpectSuccess(1159  sender: IKeyringPair,1160  collectionId: number,1161  data: CreateFungibleData,1162  owner: CrossAccountId | string = sender.address,1163) {1164  return await usingApi(async (api) => {1165    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11661167    const events = await submitTransactionAsync(sender, tx);1168    const result = getCreateItemResult(events);11691170    expect(result.success).to.be.true;1171    return result.itemId;1172  });1173}11741175export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1176  let newItemId = 0;1177  await usingApi(async (api) => {1178    const to = normalizeAccountId(owner);1179    const itemCountBefore = await getLastTokenId(api, collectionId);1180    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11811182    let tx;1183    if (createMode === 'Fungible') {1184      const createData = {fungible: {value: 10}};1185      tx = api.tx.unique.createItem(collectionId, to, createData as any);1186    } else if (createMode === 'ReFungible') {1187      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1188      tx = api.tx.unique.createItem(collectionId, to, createData as any);1189    } else {1190      const createData = {nft: {const_data: [], variable_data: []}};1191      tx = api.tx.unique.createItem(collectionId, to, createData as any);1192    }11931194    const events = await submitTransactionAsync(sender, tx);1195    const result = getCreateItemResult(events);11961197    const itemCountAfter = await getLastTokenId(api, collectionId);1198    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11991200    // What to expect1201    // tslint:disable-next-line:no-unused-expression1202    expect(result.success).to.be.true;1203    if (createMode === 'Fungible') {1204      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1205    } else {1206      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1207    }1208    expect(collectionId).to.be.equal(result.collectionId);1209    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1210    expect(to).to.be.deep.equal(result.recipient);1211    newItemId = result.itemId;1212  });1213  return newItemId;1214}12151216export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1217  await usingApi(async (api) => {1218    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12191220    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1221    const result = getCreateItemResult(events);12221223    expect(result.success).to.be.false;1224  });1225}12261227export async function setPublicAccessModeExpectSuccess(1228  sender: IKeyringPair, collectionId: number,1229  accessMode: 'Normal' | 'AllowList',1230) {1231  await usingApi(async (api) => {12321233    // Run the transaction1234    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1235    const events = await submitTransactionAsync(sender, tx);1236    const result = getGenericResult(events);12371238    // Get the collection1239    const collection = await queryCollectionExpectSuccess(api, collectionId);12401241    // What to expect1242    // tslint:disable-next-line:no-unused-expression1243    expect(result.success).to.be.true;1244    expect(collection.access.toHuman()).to.be.equal(accessMode);1245  });1246}12471248export async function setPublicAccessModeExpectFail(1249  sender: IKeyringPair, collectionId: number,1250  accessMode: 'Normal' | 'AllowList',1251) {1252  await usingApi(async (api) => {12531254    // Run the transaction1255    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1256    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1257    const result = getGenericResult(events);12581259    // What to expect1260    // tslint:disable-next-line:no-unused-expression1261    expect(result.success).to.be.false;1262  });1263}12641265export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1266  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1267}12681269export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1270  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1271}12721273export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1274  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1275}12761277export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1278  await usingApi(async (api) => {12791280    // Run the transaction1281    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1282    const events = await submitTransactionAsync(sender, tx);1283    const result = getGenericResult(events);1284    expect(result.success).to.be.true;12851286    // Get the collection1287    const collection = await queryCollectionExpectSuccess(api, collectionId);12881289    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1290  });1291}12921293export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1294  await setMintPermissionExpectSuccess(sender, collectionId, true);1295}12961297export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1298  await usingApi(async (api) => {1299    // Run the transaction1300    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1301    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1302    const result = getCreateCollectionResult(events);1303    // tslint:disable-next-line:no-unused-expression1304    expect(result.success).to.be.false;1305  });1306}13071308export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1309  await usingApi(async (api) => {1310    // Run the transaction1311    const tx = api.tx.unique.setChainLimits(limits);1312    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1313    const result = getCreateCollectionResult(events);1314    // tslint:disable-next-line:no-unused-expression1315    expect(result.success).to.be.false;1316  });1317}13181319export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1320  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1321}13221323export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1324  await usingApi(async (api) => {1325    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13261327    // Run the transaction1328    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1329    const events = await submitTransactionAsync(sender, tx);1330    const result = getGenericResult(events);1331    expect(result.success).to.be.true;13321333    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1334  });1335}13361337export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1338  await usingApi(async (api) => {13391340    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13411342    // Run the transaction1343    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1344    const events = await submitTransactionAsync(sender, tx);1345    const result = getGenericResult(events);1346    expect(result.success).to.be.true;13471348    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1349  });1350}13511352export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1353  await usingApi(async (api) => {13541355    // Run the transaction1356    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1357    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1358    const result = getGenericResult(events);13591360    // What to expect1361    // tslint:disable-next-line:no-unused-expression1362    expect(result.success).to.be.false;1363  });1364}13651366export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1367  await usingApi(async (api) => {1368    // Run the transaction1369    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1370    const events = await submitTransactionAsync(sender, tx);1371    const result = getGenericResult(events);13721373    // What to expect1374    // tslint:disable-next-line:no-unused-expression1375    expect(result.success).to.be.true;1376  });1377}13781379export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1380  await usingApi(async (api) => {1381    // Run the transaction1382    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1383    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1384    const result = getGenericResult(events);13851386    // What to expect1387    // tslint:disable-next-line:no-unused-expression1388    expect(result.success).to.be.false;1389  });1390}13911392export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1393  : Promise<UpDataStructsRpcCollection | null> => {1394  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1395};13961397export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1398  // set global object - collectionsCount1399  return (await api.rpc.unique.collectionStats()).created.toNumber();1400};14011402export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1403  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1404}14051406export async function waitNewBlocks(blocksCount = 1): Promise<void> {1407  await usingApi(async (api) => {1408    const promise = new Promise<void>(async (resolve) => {1409      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1410        if (blocksCount > 0) {1411          blocksCount--;1412        } else {1413          unsubscribe();1414          resolve();1415        }1416      });1417    });1418    return promise;1419  });1420}