difftreelog
Remove variableOnChainSchema
in: master
12 files changed
pallets/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()
},
pallets/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(
pallets/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())?;
pallets/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(())
pallets/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))
}
primitives/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,
runtime/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()
- );
});
}
tests/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;
});
tests/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
tests/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,
};
});
tests/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;
- });
- });
-
-});
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, 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}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 variableData: number[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult(events: EventRecord[]): GenericResult {176 const result: GenericResult = {177 success: false,178 };179 events.forEach(({event: {method}}) => {180 // console.log(` ${phase}: ${section}.${method}:: ${data}`);181 if (method === 'ExtrinsicSuccess') {182 result.success = true;183 }184 });185 return result;186}187188189190export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {191 let success = false;192 let collectionId = 0;193 events.forEach(({event: {data, method, section}}) => {194 // console.log(` ${phase}: ${section}.${method}:: ${data}`);195 if (method == 'ExtrinsicSuccess') {196 success = true;197 } else if ((section == 'common') && (method == 'CollectionCreated')) {198 collectionId = parseInt(data[0].toString(), 10);199 }200 });201 const result: CreateCollectionResult = {202 success,203 collectionId,204 };205 return result;206}207208export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {209 let success = false;210 let collectionId = 0;211 let itemId = 0;212 let recipient;213214 const results : CreateItemResult[] = [];215216 events.forEach(({event: {data, method, section}}) => {217 // console.log(` ${phase}: ${section}.${method}:: ${data}`);218 if (method == 'ExtrinsicSuccess') {219 success = true;220 } else if ((section == 'common') && (method == 'ItemCreated')) {221 collectionId = parseInt(data[0].toString(), 10);222 itemId = parseInt(data[1].toString(), 10);223 recipient = normalizeAccountId(data[2].toJSON() as any);224225 const itemRes: CreateItemResult = {226 success,227 collectionId,228 itemId,229 recipient,230 };231232 results.push(itemRes);233 }234 });235236 return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240 let success = false;241 let collectionId = 0;242 let itemId = 0;243 let recipient;244 events.forEach(({event: {data, method, section}}) => {245 // console.log(` ${phase}: ${section}.${method}:: ${data}`);246 if (method == 'ExtrinsicSuccess') {247 success = true;248 } else if ((section == 'common') && (method == 'ItemCreated')) {249 collectionId = parseInt(data[0].toString(), 10);250 itemId = parseInt(data[1].toString(), 10);251 recipient = normalizeAccountId(data[2].toJSON() as any);252 }253 });254 const result: CreateItemResult = {255 success,256 collectionId,257 itemId,258 recipient,259 };260 return result;261}262263export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {264 for (const {event} of events) {265 if (api.events.common.Transfer.is(event)) {266 const [collection, token, sender, recipient, value] = event.data;267 return {268 collectionId: collection.toNumber(),269 itemId: token.toNumber(),270 sender: normalizeAccountId(sender.toJSON() as any),271 recipient: normalizeAccountId(recipient.toJSON() as any),272 value: value.toBigInt(),273 };274 }275 }276 throw new Error('no transfer event');277}278279interface Nft {280 type: 'NFT';281}282283interface Fungible {284 type: 'Fungible';285 decimalPoints: number;286}287288interface ReFungible {289 type: 'ReFungible';290}291292type CollectionMode = Nft | Fungible | ReFungible;293294export type Property = {295 key: any,296 value: any,297};298299type PropertyPermission = {300 key: any,301 mutable: boolean;302 collectionAdmin: boolean;303 tokenOwner: boolean;304}305306export type CreateCollectionParams = {307 mode: CollectionMode,308 name: string,309 description: string,310 tokenPrefix: string,311 schemaVersion: string,312 properties?: Array<Property>,313 propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317 description: 'description',318 mode: {type: 'NFT'},319 name: 'name',320 tokenPrefix: 'prefix',321 schemaVersion: 'ImageURL',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api) => {329 // Get number of collections before the transaction330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 // Run the CreateCollection transaction333 const alicePrivateKey = privateKey('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 schemaVersion: schemaVersion,350 });351 const events = await submitTransactionAsync(alicePrivateKey, tx);352 const result = getCreateCollectionResult(events);353354 // Get number of collections after the transaction355 const collectionCountAfter = await getCreatedCollectionCount(api);356357 // Get the collection358 const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360 // What to expect361 // tslint:disable-next-line:no-unused-expression362 expect(result.success).to.be.true;363 expect(result.collectionId).to.be.equal(collectionCountAfter);364 // tslint:disable-next-line:no-unused-expression365 expect(collection).to.be.not.null;366 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372 collectionId = result.collectionId;373 });374375 return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381 let collectionId = 0;382 await usingApi(async (api) => {383 // Get number of collections before the transaction384 const collectionCountBefore = await getCreatedCollectionCount(api);385386 // Run the CreateCollection transaction387 const alicePrivateKey = privateKey('//Alice');388389 let modeprm = {};390 if (mode.type === 'NFT') {391 modeprm = {nft: null};392 } else if (mode.type === 'Fungible') {393 modeprm = {fungible: mode.decimalPoints};394 } else if (mode.type === 'ReFungible') {395 modeprm = {refungible: null};396 }397398 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});399 const events = await submitTransactionAsync(alicePrivateKey, tx);400 const result = getCreateCollectionResult(events);401402 // Get number of collections after the transaction403 const collectionCountAfter = await getCreatedCollectionCount(api);404405 // Get the collection406 const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408 // What to expect409 // tslint:disable-next-line:no-unused-expression410 expect(result.success).to.be.true;411 expect(result.collectionId).to.be.equal(collectionCountAfter);412 // tslint:disable-next-line:no-unused-expression413 expect(collection).to.be.not.null;414 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421 collectionId = result.collectionId;422 });423424 return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430 const collectionId = 0;431 await usingApi(async (api) => {432 // Get number of collections before the transaction433 const collectionCountBefore = await getCreatedCollectionCount(api);434435 // Run the CreateCollection transaction436 const alicePrivateKey = privateKey('//Alice');437438 let modeprm = {};439 if (mode.type === 'NFT') {440 modeprm = {nft: null};441 } else if (mode.type === 'Fungible') {442 modeprm = {fungible: mode.decimalPoints};443 } else if (mode.type === 'ReFungible') {444 modeprm = {refungible: null};445 }446447 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});448 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449450451 // Get number of collections after the transaction452 const collectionCountAfter = await getCreatedCollectionCount(api);453454 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');455 });456}457458export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {459 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};460461 let modeprm = {};462 if (mode.type === 'NFT') {463 modeprm = {nft: null};464 } else if (mode.type === 'Fungible') {465 modeprm = {fungible: mode.decimalPoints};466 } else if (mode.type === 'ReFungible') {467 modeprm = {refungible: null};468 }469470 await usingApi(async (api) => {471 // Get number of collections before the transaction472 const collectionCountBefore = await getCreatedCollectionCount(api);473474 // Run the CreateCollection transaction475 const alicePrivateKey = privateKey('//Alice');476 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});477 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;478479 // Get number of collections after the transaction480 const collectionCountAfter = await getCreatedCollectionCount(api);481482 // What to expect483 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');484 });485}486487export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {488 let bal = 0n;489 let unused;490 do {491 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;492 const keyring = new Keyring({type: 'sr25519'});493 unused = keyring.addFromUri(`//${randomSeed}`);494 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();495 } while (bal !== 0n);496 return unused;497}498499export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {500 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();501}502503export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {504 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));505}506507export async function findNotExistingCollection(api: ApiPromise): Promise<number> {508 const totalNumber = await getCreatedCollectionCount(api);509 const newCollection: number = totalNumber + 1;510 return newCollection;511}512513function getDestroyResult(events: EventRecord[]): boolean {514 let success = false;515 events.forEach(({event: {method}}) => {516 if (method == 'ExtrinsicSuccess') {517 success = true;518 }519 });520 return success;521}522523export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {524 await usingApi(async (api) => {525 // Run the DestroyCollection transaction526 const alicePrivateKey = privateKey(senderSeed);527 const tx = api.tx.unique.destroyCollection(collectionId);528 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;529 });530}531532export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {533 await usingApi(async (api) => {534 // Run the DestroyCollection transaction535 const alicePrivateKey = privateKey(senderSeed);536 const tx = api.tx.unique.destroyCollection(collectionId);537 const events = await submitTransactionAsync(alicePrivateKey, tx);538 const result = getDestroyResult(events);539 expect(result).to.be.true;540541 // What to expect542 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;543 });544}545546export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {547 await usingApi(async (api) => {548 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);549 const events = await submitTransactionAsync(sender, tx);550 const result = getGenericResult(events);551552 expect(result.success).to.be.true;553 });554}555556export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {557 await usingApi(async (api) => {558 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);559 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;560 const result = getGenericResult(events);561562 expect(result.success).to.be.false;563 });564}565566export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {567 await usingApi(async (api) => {568569 // Run the transaction570 const senderPrivateKey = privateKey(sender);571 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);572 const events = await submitTransactionAsync(senderPrivateKey, tx);573 const result = getGenericResult(events);574575 // Get the collection576 const collection = await queryCollectionExpectSuccess(api, collectionId);577578 // What to expect579 expect(result.success).to.be.true;580 expect(collection.sponsorship.toJSON()).to.deep.equal({581 unconfirmed: sponsor,582 });583 });584}585586export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {587 await usingApi(async (api) => {588589 // Run the transaction590 const alicePrivateKey = privateKey(sender);591 const tx = api.tx.unique.removeCollectionSponsor(collectionId);592 const events = await submitTransactionAsync(alicePrivateKey, tx);593 const result = getGenericResult(events);594595 // Get the collection596 const collection = await queryCollectionExpectSuccess(api, collectionId);597598 // What to expect599 expect(result.success).to.be.true;600 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});601 });602}603604export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {605 await usingApi(async (api) => {606607 // Run the transaction608 const alicePrivateKey = privateKey(senderSeed);609 const tx = api.tx.unique.removeCollectionSponsor(collectionId);610 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;611 });612}613614export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {615 await usingApi(async (api) => {616617 // Run the transaction618 const alicePrivateKey = privateKey(senderSeed);619 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);620 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;621 });622}623624export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {625 await usingApi(async (api) => {626627 // Run the transaction628 const sender = privateKey(senderSeed);629 const tx = api.tx.unique.confirmSponsorship(collectionId);630 const events = await submitTransactionAsync(sender, tx);631 const result = getGenericResult(events);632633 // Get the collection634 const collection = await queryCollectionExpectSuccess(api, collectionId);635636 // What to expect637 expect(result.success).to.be.true;638 expect(collection.sponsorship.toJSON()).to.be.deep.equal({639 confirmed: sender.address,640 });641 });642}643644645export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {646 await usingApi(async (api) => {647648 // Run the transaction649 const sender = privateKey(senderSeed);650 const tx = api.tx.unique.confirmSponsorship(collectionId);651 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;652 });653}654655export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {656657 await usingApi(async (api) => {658 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);659 const events = await submitTransactionAsync(sender, tx);660 const result = getGenericResult(events);661662 expect(result.success).to.be.true;663 });664}665666export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {667668 await usingApi(async (api) => {669 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);670 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671 const result = getGenericResult(events);672673 expect(result.success).to.be.false;674 });675}676677export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {678 await usingApi(async (api) => {679 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);680 const events = await submitTransactionAsync(sender, tx);681 const result = getGenericResult(events);682683 expect(result.success).to.be.true;684 });685}686687export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {688 await usingApi(async (api) => {689 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);690 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;691 const result = getGenericResult(events);692693 expect(result.success).to.be.false;694 });695}696697export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {698699 await usingApi(async (api) => {700701 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);702 const events = await submitTransactionAsync(sender, tx);703 const result = getGenericResult(events);704705 expect(result.success).to.be.true;706 });707}708709export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {710711 await usingApi(async (api) => {712713 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);714 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;715 const result = getGenericResult(events);716717 expect(result.success).to.be.false;718 });719}720721export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {722 await usingApi(async (api) => {723 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);724 const events = await submitTransactionAsync(sender, tx);725 const result = getGenericResult(events);726727 expect(result.success).to.be.true;728 });729}730731export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {732 await usingApi(async (api) => {733 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);734 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;735 const result = getGenericResult(events);736737 expect(result.success).to.be.false;738 });739}740741export async function getNextSponsored(742 api: ApiPromise,743 collectionId: number,744 account: string | CrossAccountId,745 tokenId: number,746): Promise<number> {747 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));748}749750export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {751 await usingApi(async (api) => {752 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);753 const events = await submitTransactionAsync(sender, tx);754 const result = getGenericResult(events);755756 expect(result.success).to.be.true;757 });758}759760export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {761 let allowlisted = false;762 await usingApi(async (api) => {763 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;764 });765 return allowlisted;766}767768export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769 await usingApi(async (api) => {770 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());771 const events = await submitTransactionAsync(sender, tx);772 const result = getGenericResult(events);773774 expect(result.success).to.be.true;775 });776}777778export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {779 await usingApi(async (api) => {780 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());781 const events = await submitTransactionAsync(sender, tx);782 const result = getGenericResult(events);783784 expect(result.success).to.be.true;785 });786}787788export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {789 await usingApi(async (api) => {790 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());791 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792 const result = getGenericResult(events);793794 expect(result.success).to.be.false;795 });796}797798export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {799 await usingApi(async (api) => {800 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));801 const events = await submitTransactionAsync(sender, tx);802 const result = getGenericResult(events);803804 expect(result.success).to.be.true;805 });806}807808export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {809 await usingApi(async (api) => {810 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));811 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;812 });813}814815export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {816 await usingApi(async (api) => {817 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));818 const events = await submitTransactionAsync(sender, tx);819 const result = getGenericResult(events);820821 expect(result.success).to.be.true;822 });823}824825export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {826 await usingApi(async (api) => {827 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));828 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;829 });830}831832export interface CreateFungibleData {833 readonly Value: bigint;834}835836export interface CreateReFungibleData { }837export interface CreateNftData { }838839export type CreateItemData = {840 NFT: CreateNftData;841} | {842 Fungible: CreateFungibleData;843} | {844 ReFungible: CreateReFungibleData;845};846847export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {848 await usingApi(async (api) => {849 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);850 // if burning token by admin - use adminButnItemExpectSuccess851 expect(balanceBefore >= BigInt(value)).to.be.true;852853 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);854 const events = await submitTransactionAsync(sender, tx);855 const result = getGenericResult(events);856 expect(result.success).to.be.true;857858 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);859 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);860 });861}862863export async function864approveExpectSuccess(865 collectionId: number,866 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,867) {868 await usingApi(async (api: ApiPromise) => {869 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);870 const events = await submitTransactionAsync(owner, approveUniqueTx);871 const result = getGenericResult(events);872 expect(result.success).to.be.true;873874 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));875 });876}877878export async function adminApproveFromExpectSuccess(879 collectionId: number,880 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,881) {882 await usingApi(async (api: ApiPromise) => {883 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);884 const events = await submitTransactionAsync(admin, approveUniqueTx);885 const result = getGenericResult(events);886 expect(result.success).to.be.true;887888 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));889 });890}891892export async function893transferFromExpectSuccess(894 collectionId: number,895 tokenId: number,896 accountApproved: IKeyringPair,897 accountFrom: IKeyringPair | CrossAccountId,898 accountTo: IKeyringPair | CrossAccountId,899 value: number | bigint = 1,900 type = 'NFT',901) {902 await usingApi(async (api: ApiPromise) => {903 const from = normalizeAccountId(accountFrom);904 const to = normalizeAccountId(accountTo);905 let balanceBefore = 0n;906 if (type === 'Fungible') {907 balanceBefore = await getBalance(api, collectionId, to, tokenId);908 }909 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);910 const events = await submitTransactionAsync(accountApproved, transferFromTx);911 const result = getCreateItemResult(events);912 // tslint:disable-next-line:no-unused-expression913 expect(result.success).to.be.true;914 if (type === 'NFT') {915 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);916 }917 if (type === 'Fungible') {918 const balanceAfter = await getBalance(api, collectionId, to, tokenId);919 if (JSON.stringify(to) !== JSON.stringify(from)) {920 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));921 } else {922 expect(balanceAfter).to.be.equal(balanceBefore);923 }924 }925 if (type === 'ReFungible') {926 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));927 }928 });929}930931export async function932transferFromExpectFail(933 collectionId: number,934 tokenId: number,935 accountApproved: IKeyringPair,936 accountFrom: IKeyringPair,937 accountTo: IKeyringPair,938 value: number | bigint = 1,939) {940 await usingApi(async (api: ApiPromise) => {941 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);942 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;943 const result = getCreateCollectionResult(events);944 // tslint:disable-next-line:no-unused-expression945 expect(result.success).to.be.false;946 });947}948949/* eslint no-async-promise-executor: "off" */950async function getBlockNumber(api: ApiPromise): Promise<number> {951 return new Promise<number>(async (resolve) => {952 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {953 unsubscribe();954 resolve(head.number.toNumber());955 });956 });957}958959export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {960 await usingApi(async (api) => {961 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));962 const events = await submitTransactionAsync(sender, changeAdminTx);963 const result = getCreateCollectionResult(events);964 expect(result.success).to.be.true;965 });966}967968export async function969getFreeBalance(account: IKeyringPair): Promise<bigint> {970 let balance = 0n;971 await usingApi(async (api) => {972 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());973 });974975 return balance;976}977978export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {979 const tx = api.tx.balances.transfer(target, amount);980 const events = await submitTransactionAsync(source, tx);981 const result = getGenericResult(events);982 expect(result.success).to.be.true;983}984985export async function986scheduleTransferExpectSuccess(987 collectionId: number,988 tokenId: number,989 sender: IKeyringPair,990 recipient: IKeyringPair,991 value: number | bigint = 1,992 blockSchedule: number,993) {994 await usingApi(async (api: ApiPromise) => {995 const blockNumber: number | undefined = await getBlockNumber(api);996 const expectedBlockNumber = blockNumber + blockSchedule;997998 expect(blockNumber).to.be.greaterThan(0);999 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1000 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10011002 await submitTransactionAsync(sender, scheduleTx);10031004 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10051006 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10071008 // sleep for 4 blocks1009 await waitNewBlocks(blockSchedule + 1);10101011 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1014 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1015 });1016}101710181019export async function1020transferExpectSuccess(1021 collectionId: number,1022 tokenId: number,1023 sender: IKeyringPair,1024 recipient: IKeyringPair | CrossAccountId,1025 value: number | bigint = 1,1026 type = 'NFT',1027) {1028 await usingApi(async (api: ApiPromise) => {1029 const from = normalizeAccountId(sender);1030 const to = normalizeAccountId(recipient);10311032 let balanceBefore = 0n;1033 if (type === 'Fungible') {1034 balanceBefore = await getBalance(api, collectionId, to, tokenId);1035 }1036 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1037 const events = await executeTransaction(api, sender, transferTx);10381039 const result = getTransferResult(api, events);1040 expect(result.collectionId).to.be.equal(collectionId);1041 expect(result.itemId).to.be.equal(tokenId);1042 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1043 expect(result.recipient).to.be.deep.equal(to);1044 expect(result.value).to.be.equal(BigInt(value));10451046 if (type === 'NFT') {1047 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1048 }1049 if (type === 'Fungible') {1050 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1051 if (JSON.stringify(to) !== JSON.stringify(from)) {1052 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1053 } else {1054 expect(balanceAfter).to.be.equal(balanceBefore);1055 }1056 }1057 if (type === 'ReFungible') {1058 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1059 }1060 });1061}10621063export async function1064transferExpectFailure(1065 collectionId: number,1066 tokenId: number,1067 sender: IKeyringPair,1068 recipient: IKeyringPair | CrossAccountId,1069 value: number | bigint = 1,1070) {1071 await usingApi(async (api: ApiPromise) => {1072 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1073 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1074 const result = getGenericResult(events);1075 // if (events && Array.isArray(events)) {1076 // const result = getCreateCollectionResult(events);1077 // tslint:disable-next-line:no-unused-expression1078 expect(result.success).to.be.false;1079 //}1080 });1081}10821083export async function1084approveExpectFail(1085 collectionId: number,1086 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1087) {1088 await usingApi(async (api: ApiPromise) => {1089 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1090 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1091 const result = getCreateCollectionResult(events);1092 // tslint:disable-next-line:no-unused-expression1093 expect(result.success).to.be.false;1094 });1095}10961097export async function getBalance(1098 api: ApiPromise,1099 collectionId: number,1100 owner: string | CrossAccountId,1101 token: number,1102): Promise<bigint> {1103 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1104}1105export async function getTokenOwner(1106 api: ApiPromise,1107 collectionId: number,1108 token: number,1109): Promise<CrossAccountId> {1110 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1111 if (owner == null) throw new Error('owner == null');1112 return normalizeAccountId(owner);1113}1114export async function getTopmostTokenOwner(1115 api: ApiPromise,1116 collectionId: number,1117 token: number,1118): Promise<CrossAccountId> {1119 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1120 if (owner == null) throw new Error('owner == null');1121 return normalizeAccountId(owner);1122}1123export async function isTokenExists(1124 api: ApiPromise,1125 collectionId: number,1126 token: number,1127): Promise<boolean> {1128 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1129}1130export async function getLastTokenId(1131 api: ApiPromise,1132 collectionId: number,1133): Promise<number> {1134 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1135}1136export async function getAdminList(1137 api: ApiPromise,1138 collectionId: number,1139): Promise<string[]> {1140 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1141}1142export async function getVariableMetadata(1143 api: ApiPromise,1144 collectionId: number,1145 tokenId: number,1146): Promise<number[]> {1147 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1148}1149export async function getConstMetadata(1150 api: ApiPromise,1151 collectionId: number,1152 tokenId: number,1153): Promise<number[]> {1154 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1155}11561157export async function createFungibleItemExpectSuccess(1158 sender: IKeyringPair,1159 collectionId: number,1160 data: CreateFungibleData,1161 owner: CrossAccountId | string = sender.address,1162) {1163 return await usingApi(async (api) => {1164 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11651166 const events = await submitTransactionAsync(sender, tx);1167 const result = getCreateItemResult(events);11681169 expect(result.success).to.be.true;1170 return result.itemId;1171 });1172}11731174export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1175 let newItemId = 0;1176 await usingApi(async (api) => {1177 const to = normalizeAccountId(owner);1178 const itemCountBefore = await getLastTokenId(api, collectionId);1179 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11801181 let tx;1182 if (createMode === 'Fungible') {1183 const createData = {fungible: {value: 10}};1184 tx = api.tx.unique.createItem(collectionId, to, createData as any);1185 } else if (createMode === 'ReFungible') {1186 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1187 tx = api.tx.unique.createItem(collectionId, to, createData as any);1188 } else {1189 const createData = {nft: {const_data: [], variable_data: []}};1190 tx = api.tx.unique.createItem(collectionId, to, createData as any);1191 }11921193 const events = await submitTransactionAsync(sender, tx);1194 const result = getCreateItemResult(events);11951196 const itemCountAfter = await getLastTokenId(api, collectionId);1197 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11981199 // What to expect1200 // tslint:disable-next-line:no-unused-expression1201 expect(result.success).to.be.true;1202 if (createMode === 'Fungible') {1203 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1204 } else {1205 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1206 }1207 expect(collectionId).to.be.equal(result.collectionId);1208 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1209 expect(to).to.be.deep.equal(result.recipient);1210 newItemId = result.itemId;1211 });1212 return newItemId;1213}12141215export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1216 await usingApi(async (api) => {1217 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12181219 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1220 const result = getCreateItemResult(events);12211222 expect(result.success).to.be.false;1223 });1224}12251226export async function setPublicAccessModeExpectSuccess(1227 sender: IKeyringPair, collectionId: number,1228 accessMode: 'Normal' | 'AllowList',1229) {1230 await usingApi(async (api) => {12311232 // Run the transaction1233 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1234 const events = await submitTransactionAsync(sender, tx);1235 const result = getGenericResult(events);12361237 // Get the collection1238 const collection = await queryCollectionExpectSuccess(api, collectionId);12391240 // What to expect1241 // tslint:disable-next-line:no-unused-expression1242 expect(result.success).to.be.true;1243 expect(collection.access.toHuman()).to.be.equal(accessMode);1244 });1245}12461247export async function setPublicAccessModeExpectFail(1248 sender: IKeyringPair, collectionId: number,1249 accessMode: 'Normal' | 'AllowList',1250) {1251 await usingApi(async (api) => {12521253 // Run the transaction1254 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1255 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1256 const result = getGenericResult(events);12571258 // What to expect1259 // tslint:disable-next-line:no-unused-expression1260 expect(result.success).to.be.false;1261 });1262}12631264export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1265 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1266}12671268export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1269 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1270}12711272export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1273 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1274}12751276export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1277 await usingApi(async (api) => {12781279 // Run the transaction1280 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1281 const events = await submitTransactionAsync(sender, tx);1282 const result = getGenericResult(events);1283 expect(result.success).to.be.true;12841285 // Get the collection1286 const collection = await queryCollectionExpectSuccess(api, collectionId);12871288 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1289 });1290}12911292export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1293 await setMintPermissionExpectSuccess(sender, collectionId, true);1294}12951296export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1297 await usingApi(async (api) => {1298 // Run the transaction1299 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1300 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1301 const result = getCreateCollectionResult(events);1302 // tslint:disable-next-line:no-unused-expression1303 expect(result.success).to.be.false;1304 });1305}13061307export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1308 await usingApi(async (api) => {1309 // Run the transaction1310 const tx = api.tx.unique.setChainLimits(limits);1311 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1312 const result = getCreateCollectionResult(events);1313 // tslint:disable-next-line:no-unused-expression1314 expect(result.success).to.be.false;1315 });1316}13171318export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1319 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1320}13211322export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1323 await usingApi(async (api) => {1324 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13251326 // Run the transaction1327 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1328 const events = await submitTransactionAsync(sender, tx);1329 const result = getGenericResult(events);1330 expect(result.success).to.be.true;13311332 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1333 });1334}13351336export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1337 await usingApi(async (api) => {13381339 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13401341 // Run the transaction1342 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1343 const events = await submitTransactionAsync(sender, tx);1344 const result = getGenericResult(events);1345 expect(result.success).to.be.true;13461347 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1348 });1349}13501351export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1352 await usingApi(async (api) => {13531354 // Run the transaction1355 const tx = api.tx.unique.addToAllowList(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 async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1366 await usingApi(async (api) => {1367 // Run the transaction1368 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1369 const events = await submitTransactionAsync(sender, tx);1370 const result = getGenericResult(events);13711372 // What to expect1373 // tslint:disable-next-line:no-unused-expression1374 expect(result.success).to.be.true;1375 });1376}13771378export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1379 await usingApi(async (api) => {1380 // Run the transaction1381 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1382 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1383 const result = getGenericResult(events);13841385 // What to expect1386 // tslint:disable-next-line:no-unused-expression1387 expect(result.success).to.be.false;1388 });1389}13901391export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1392 : Promise<UpDataStructsRpcCollection | null> => {1393 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1394};13951396export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1397 // set global object - collectionsCount1398 return (await api.rpc.unique.collectionStats()).created.toNumber();1399};14001401export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1402 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1403}14041405export async function waitNewBlocks(blocksCount = 1): Promise<void> {1406 await usingApi(async (api) => {1407 const promise = new Promise<void>(async (resolve) => {1408 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1409 if (blocksCount > 0) {1410 blocksCount--;1411 } else {1412 unsubscribe();1413 resolve();1414 }1415 });1416 });1417 return promise;1418 });1419}