git.delta.rocks / unique-network / refs/commits / dfe6d1900e26

difftreelog

Merge commit '2074c933e3ff90b7ea5fc778111ead850fd4a5ea' into release-v922000

Yaroslav Bolyukin2022-06-07parents: #0713a71 #2074c93.patch.diff
in: master

20 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -25,7 +25,7 @@
 use anyhow::anyhow;
 use up_data_structs::{
 	RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,
-	PropertyKeyPermission, TokenData,
+	PropertyKeyPermission, TokenData, TokenChild,
 };
 use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
 use sp_blockchain::HeaderBackend;
@@ -77,6 +77,13 @@
 		token: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<CrossAccountId>>;
+	#[method(name = "unique_tokenChildren")]
+	fn token_children(
+		&self,
+		collection: CollectionId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<Vec<TokenChild>>;
 
 	#[method(name = "unique_collectionProperties")]
 	fn collection_properties(
@@ -394,6 +401,7 @@
 	pass_method!(
 		topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
 	);
+	pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);
 	pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
 	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
 	pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -40,6 +40,7 @@
 	MAX_TOKEN_PREFIX_LENGTH,
 	COLLECTION_ADMINS_LIMIT,
 	TokenId,
+	TokenChild,
 	CollectionStats,
 	MAX_TOKEN_OWNERSHIP,
 	CollectionMode,
@@ -502,6 +503,7 @@
 			CollectionStats,
 			CollectionId,
 			TokenId,
+			TokenChild,
 			PhantomType<(
 				TokenData<T::CrossAccountId>,
 				RpcCollection<T::AccountId>,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -22,7 +22,7 @@
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
 	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
-	PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
+	PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,
 };
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
@@ -604,7 +604,7 @@
 
 		// =========
 
-		<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
+		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);
 
 		<TokenData<T>>::insert(
 			(collection.id, token),
@@ -988,6 +988,15 @@
 			.is_some()
 	}
 
+	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {
+		<TokenChildren<T>>::iter_prefix((collection_id, token_id))
+			.map(|((child_collection_id, child_id), _)| TokenChild {
+				collection: child_collection_id,
+				token: child_id,
+			})
+			.collect()
+	}
+
 	/// Delegated to `create_multiple_items`
 	pub fn create_item(
 		collection: &NonfungibleHandle<T>,
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -191,8 +191,8 @@
 		token_id: TokenId,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::try_exec_if_owner_is_valid_nft(under, |d, parent_id| {
-			d.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)
+		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {
+			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)
 		})
 	}
 
@@ -203,10 +203,10 @@
 		token_id: TokenId,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::try_exec_if_owner_is_valid_nft(under, |d, parent_id| {
-			d.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;
+		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {
+			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;
 
-			d.nest(parent_id, (collection_id, token_id));
+			collection.nest(parent_id, (collection_id, token_id));
 
 			Ok(())
 		})
@@ -217,8 +217,8 @@
 		collection_id: CollectionId,
 		token_id: TokenId,
 	) {
-		Self::exec_if_owner_is_valid_nft(owner, |d, parent_id| {
-			d.nest(parent_id, (collection_id, token_id))
+		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {
+			collection.nest(parent_id, (collection_id, token_id))
 		});
 	}
 
@@ -227,8 +227,8 @@
 		collection_id: CollectionId,
 		token_id: TokenId,
 	) {
-		Self::exec_if_owner_is_valid_nft(owner, |d, parent_id| {
-			d.unnest(parent_id, (collection_id, token_id))
+		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {
+			collection.unnest(parent_id, (collection_id, token_id))
 		});
 	}
 
@@ -236,8 +236,8 @@
 		account: &T::CrossAccountId,
 		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),
 	) {
-		Self::try_exec_if_owner_is_valid_nft(account, |d, id| {
-			action(d, id);
+		Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {
+			action(collection, id);
 			Ok(())
 		})
 		.unwrap();
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -585,6 +585,14 @@
 
 #[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+// todo possibly rename to be used generally as an address pair
+pub struct TokenChild {
+	pub token: TokenId,
+	pub collection: CollectionId,
+}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionStats {
 	pub created: u32,
 	pub destroyed: u32,
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -18,7 +18,7 @@
 
 use up_data_structs::{
 	CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
-	PropertyKeyPermission, TokenData,
+	PropertyKeyPermission, TokenData, TokenChild,
 };
 use sp_std::vec::Vec;
 use codec::Decode;
@@ -41,6 +41,7 @@
 
 		fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
 		fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
+		fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;
 
 		fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
 
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -29,7 +29,9 @@
 
                     Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
                 }
-
+                fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
+                    Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
+                }
                 fn collection_properties(
                     collection: CollectionId,
                     keys: Option<Vec<Vec<u8>>>
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -73,6 +73,7 @@
 	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
 	CollectionStats, RpcCollection,
 	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
+	TokenChild,
 };
 
 // use pallet_contracts::weights::WeightInfo;
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -72,7 +72,8 @@
 use up_data_structs::{
 	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits, 
 	CollectionStats, RpcCollection, 
-	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
+	TokenChild,
 };
 
 // use pallet_contracts::weights::WeightInfo;
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -21,7 +21,7 @@
 	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, TokenId,
 	MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionMode, AccessMode, CollectionPermissions,
 	PropertyKeyPermission, PropertyPermission, Property, CollectionPropertiesVec,
-	CollectionPropertiesPermissionsVec,
+	CollectionPropertiesPermissionsVec, TokenChild,
 };
 use frame_support::{assert_noop, assert_ok, assert_err};
 use sp_std::convert::TryInto;
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -5,7 +5,7 @@
 import type { BTreeMap, Bytes, Option, U256, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types-codec';
 import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';
 import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';
-import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueQueueConfigData, EthereumBlock, EthereumLog, EthereumReceiptReceiptV3, EthereumTransactionTransactionV2, FpRpcTransactionStatus, FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmContractHelpersSponsoringModeT, PalletNonfungibleItemData, PalletRefungibleItemData, PalletTransactionPaymentReleases, PalletTreasuryProposal, PhantomTypeUpDataStructs, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpRuntimeDigest, SpTrieStorageProof, UpDataStructsCollection, UpDataStructsCollectionStats, UpDataStructsProperties, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsPropertyPermission } from '@polkadot/types/lookup';
+import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueQueueConfigData, EthereumBlock, EthereumLog, EthereumReceiptReceiptV3, EthereumTransactionTransactionV2, FpRpcTransactionStatus, FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmContractHelpersSponsoringModeT, PalletNonfungibleItemData, PalletRefungibleItemData, PalletTransactionPaymentReleases, PalletTreasuryProposal, PhantomTypeUpDataStructs, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpRuntimeDigest, SpTrieStorageProof, UpDataStructsCollection, UpDataStructsCollectionStats, UpDataStructsProperties, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsPropertyPermission, UpDataStructsTokenChild } from '@polkadot/types/lookup';
 import type { Observable } from '@polkadot/types/types';
 
 declare module '@polkadot/api-base/types/storage' {
@@ -88,7 +88,7 @@
       /**
        * Not used by code, exists only to provide some types to metadata
        **/
-      dummyStorageValue: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[UpDataStructsCollectionStats, u32, u32, PhantomTypeUpDataStructs]>>>, []> & QueryableStorageEntry<ApiType, []>;
+      dummyStorageValue: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[UpDataStructsCollectionStats, u32, u32, UpDataStructsTokenChild, PhantomTypeUpDataStructs]>>>, []> & QueryableStorageEntry<ApiType, []>;
       /**
        * List of collection admins
        **/
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -1,7 +1,7 @@
 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit
 /* eslint-disable */
 
-import type { PalletEvmAccountBasicCrossAccountIdRepr, UpDataStructsCollectionLimits, UpDataStructsCollectionStats, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsRpcCollection, UpDataStructsTokenData } from './default';
+import type { PalletEvmAccountBasicCrossAccountIdRepr, UpDataStructsCollectionLimits, UpDataStructsCollectionStats, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsRpcCollection, UpDataStructsTokenChild, UpDataStructsTokenData } from './default';
 import type { AugmentedRpc } from '@polkadot/rpc-core/types';
 import type { Metadata, StorageKey } from '@polkadot/types';
 import type { Bytes, HashMap, Json, Null, Option, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types-codec';
@@ -639,6 +639,10 @@
        **/
       propertyPermissions: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, propertyKeys?: Vec<Text> | (Text | string)[], at?: Hash | string | Uint8Array) => Observable<Vec<UpDataStructsPropertyKeyPermission>>>;
       /**
+       * Get tokens nested directly into the token
+       **/
+      tokenChildren: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<UpDataStructsTokenChild>>>;
+      /**
        * Get token data
        **/
       tokenData: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, propertyKeys?: Vec<Text> | (Text | string)[], at?: Hash | string | Uint8Array) => Observable<UpDataStructsTokenData>>;
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -1,7 +1,7 @@
 // Auto-generated via `yarn polkadot-types-from-defs`, do not edit
 /* eslint-disable */
 
-import type { CumulusPalletDmpQueueCall, CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueueError, CumulusPalletDmpQueueEvent, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemCall, CumulusPalletParachainSystemError, CumulusPalletParachainSystemEvent, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmCall, CumulusPalletXcmError, CumulusPalletXcmEvent, CumulusPalletXcmpQueueCall, CumulusPalletXcmpQueueError, CumulusPalletXcmpQueueEvent, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueInboundState, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueOutboundState, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, EthbloomBloom, EthereumBlock, EthereumHeader, EthereumLog, EthereumReceiptEip658ReceiptData, EthereumReceiptReceiptV3, EthereumTransactionAccessListItem, EthereumTransactionEip1559Transaction, EthereumTransactionEip2930Transaction, EthereumTransactionLegacyTransaction, EthereumTransactionTransactionAction, EthereumTransactionTransactionSignature, EthereumTransactionTransactionV2, EthereumTypesHashH64, EvmCoreErrorExitError, EvmCoreErrorExitFatal, EvmCoreErrorExitReason, EvmCoreErrorExitRevert, EvmCoreErrorExitSucceed, FpRpcTransactionStatus, FrameSupportPalletId, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchClass, FrameSupportWeightsDispatchInfo, FrameSupportWeightsPays, FrameSupportWeightsPerDispatchClassU32, FrameSupportWeightsPerDispatchClassU64, FrameSupportWeightsPerDispatchClassWeightsPerClass, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemAccountInfo, FrameSystemCall, FrameSystemError, FrameSystemEvent, FrameSystemEventRecord, FrameSystemExtensionsCheckGenesis, FrameSystemExtensionsCheckNonce, FrameSystemExtensionsCheckSpecVersion, FrameSystemExtensionsCheckWeight, FrameSystemLastRuntimeUpgradeInfo, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, FrameSystemLimitsWeightsPerClass, FrameSystemPhase, OpalRuntimeRuntime, OrmlVestingModuleCall, OrmlVestingModuleError, OrmlVestingModuleEvent, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesCall, PalletBalancesError, PalletBalancesEvent, PalletBalancesReasons, PalletBalancesReleases, PalletBalancesReserveData, PalletCommonError, PalletCommonEvent, PalletEthereumCall, PalletEthereumError, PalletEthereumEvent, PalletEthereumFakeTransactionFinalizer, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmCall, PalletEvmCoderSubstrateError, PalletEvmContractHelpersError, PalletEvmContractHelpersSponsoringModeT, PalletEvmError, PalletEvmEvent, PalletEvmMigrationCall, PalletEvmMigrationError, PalletFungibleError, PalletInflationCall, PalletNonfungibleError, PalletNonfungibleItemData, PalletRefungibleError, PalletRefungibleItemData, PalletStructureCall, PalletStructureError, PalletStructureEvent, PalletSudoCall, PalletSudoError, PalletSudoEvent, PalletTemplateTransactionPaymentCall, PalletTemplateTransactionPaymentChargeTransactionPayment, PalletTimestampCall, PalletTransactionPaymentReleases, PalletTreasuryCall, PalletTreasuryError, PalletTreasuryEvent, PalletTreasuryProposal, PalletUniqueCall, PalletUniqueError, PalletUniqueRawEvent, PalletXcmCall, PalletXcmError, PalletXcmEvent, PhantomTypeUpDataStructs, PolkadotCorePrimitivesInboundDownwardMessage, PolkadotCorePrimitivesInboundHrmpMessage, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2AbridgedHrmpChannel, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpCoreEcdsaSignature, SpCoreEd25519Signature, SpCoreSr25519Signature, SpRuntimeArithmeticError, SpRuntimeDigest, SpRuntimeDigestDigestItem, SpRuntimeDispatchError, SpRuntimeModuleError, SpRuntimeMultiSignature, SpRuntimeTokenError, SpRuntimeTransactionalError, SpTrieStorageProof, SpVersionRuntimeVersion, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionPermissions, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateFungibleData, UpDataStructsCreateItemData, UpDataStructsCreateItemExData, UpDataStructsCreateNftData, UpDataStructsCreateNftExData, UpDataStructsCreateReFungibleData, UpDataStructsCreateRefungibleExData, UpDataStructsNestingRule, UpDataStructsProperties, UpDataStructsPropertiesMapBoundedVec, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsPropertyPermission, UpDataStructsRmrkAccountIdOrCollectionNftTuple, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkBasicResource, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkComposableResource, UpDataStructsRmrkEquippableList, UpDataStructsRmrkFixedPart, UpDataStructsRmrkNftChild, UpDataStructsRmrkNftInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkResourceTypes, UpDataStructsRmrkRoyaltyInfo, UpDataStructsRmrkSlotPart, UpDataStructsRmrkSlotResource, UpDataStructsRmrkTheme, UpDataStructsRmrkThemeProperty, UpDataStructsRpcCollection, UpDataStructsSponsoringRateLimit, UpDataStructsSponsorshipState, UpDataStructsTokenData, XcmDoubleEncoded, XcmV0Junction, XcmV0JunctionBodyId, XcmV0JunctionBodyPart, XcmV0JunctionNetworkId, XcmV0MultiAsset, XcmV0MultiLocation, XcmV0Order, XcmV0OriginKind, XcmV0Response, XcmV0Xcm, XcmV1Junction, XcmV1MultiAsset, XcmV1MultiLocation, XcmV1MultiassetAssetId, XcmV1MultiassetAssetInstance, XcmV1MultiassetFungibility, XcmV1MultiassetMultiAssetFilter, XcmV1MultiassetMultiAssets, XcmV1MultiassetWildFungibility, XcmV1MultiassetWildMultiAsset, XcmV1MultilocationJunctions, XcmV1Order, XcmV1Response, XcmV1Xcm, XcmV2Instruction, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2WeightLimit, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from './default';
+import type { CumulusPalletDmpQueueCall, CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueueError, CumulusPalletDmpQueueEvent, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemCall, CumulusPalletParachainSystemError, CumulusPalletParachainSystemEvent, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmCall, CumulusPalletXcmError, CumulusPalletXcmEvent, CumulusPalletXcmpQueueCall, CumulusPalletXcmpQueueError, CumulusPalletXcmpQueueEvent, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueInboundState, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueOutboundState, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, EthbloomBloom, EthereumBlock, EthereumHeader, EthereumLog, EthereumReceiptEip658ReceiptData, EthereumReceiptReceiptV3, EthereumTransactionAccessListItem, EthereumTransactionEip1559Transaction, EthereumTransactionEip2930Transaction, EthereumTransactionLegacyTransaction, EthereumTransactionTransactionAction, EthereumTransactionTransactionSignature, EthereumTransactionTransactionV2, EthereumTypesHashH64, EvmCoreErrorExitError, EvmCoreErrorExitFatal, EvmCoreErrorExitReason, EvmCoreErrorExitRevert, EvmCoreErrorExitSucceed, FpRpcTransactionStatus, FrameSupportPalletId, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchClass, FrameSupportWeightsDispatchInfo, FrameSupportWeightsPays, FrameSupportWeightsPerDispatchClassU32, FrameSupportWeightsPerDispatchClassU64, FrameSupportWeightsPerDispatchClassWeightsPerClass, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemAccountInfo, FrameSystemCall, FrameSystemError, FrameSystemEvent, FrameSystemEventRecord, FrameSystemExtensionsCheckGenesis, FrameSystemExtensionsCheckNonce, FrameSystemExtensionsCheckSpecVersion, FrameSystemExtensionsCheckWeight, FrameSystemLastRuntimeUpgradeInfo, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, FrameSystemLimitsWeightsPerClass, FrameSystemPhase, OpalRuntimeRuntime, OrmlVestingModuleCall, OrmlVestingModuleError, OrmlVestingModuleEvent, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesCall, PalletBalancesError, PalletBalancesEvent, PalletBalancesReasons, PalletBalancesReleases, PalletBalancesReserveData, PalletCommonError, PalletCommonEvent, PalletEthereumCall, PalletEthereumError, PalletEthereumEvent, PalletEthereumFakeTransactionFinalizer, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmCall, PalletEvmCoderSubstrateError, PalletEvmContractHelpersError, PalletEvmContractHelpersSponsoringModeT, PalletEvmError, PalletEvmEvent, PalletEvmMigrationCall, PalletEvmMigrationError, PalletFungibleError, PalletInflationCall, PalletNonfungibleError, PalletNonfungibleItemData, PalletRefungibleError, PalletRefungibleItemData, PalletStructureCall, PalletStructureError, PalletStructureEvent, PalletSudoCall, PalletSudoError, PalletSudoEvent, PalletTemplateTransactionPaymentCall, PalletTemplateTransactionPaymentChargeTransactionPayment, PalletTimestampCall, PalletTransactionPaymentReleases, PalletTreasuryCall, PalletTreasuryError, PalletTreasuryEvent, PalletTreasuryProposal, PalletUniqueCall, PalletUniqueError, PalletUniqueRawEvent, PalletXcmCall, PalletXcmError, PalletXcmEvent, PhantomTypeUpDataStructs, PolkadotCorePrimitivesInboundDownwardMessage, PolkadotCorePrimitivesInboundHrmpMessage, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2AbridgedHrmpChannel, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpCoreEcdsaSignature, SpCoreEd25519Signature, SpCoreSr25519Signature, SpRuntimeArithmeticError, SpRuntimeDigest, SpRuntimeDigestDigestItem, SpRuntimeDispatchError, SpRuntimeModuleError, SpRuntimeMultiSignature, SpRuntimeTokenError, SpRuntimeTransactionalError, SpTrieStorageProof, SpVersionRuntimeVersion, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionPermissions, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateFungibleData, UpDataStructsCreateItemData, UpDataStructsCreateItemExData, UpDataStructsCreateNftData, UpDataStructsCreateNftExData, UpDataStructsCreateReFungibleData, UpDataStructsCreateRefungibleExData, UpDataStructsNestingRule, UpDataStructsProperties, UpDataStructsPropertiesMapBoundedVec, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsPropertyPermission, UpDataStructsRmrkAccountIdOrCollectionNftTuple, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkBasicResource, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkComposableResource, UpDataStructsRmrkEquippableList, UpDataStructsRmrkFixedPart, UpDataStructsRmrkNftChild, UpDataStructsRmrkNftInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkResourceTypes, UpDataStructsRmrkRoyaltyInfo, UpDataStructsRmrkSlotPart, UpDataStructsRmrkSlotResource, UpDataStructsRmrkTheme, UpDataStructsRmrkThemeProperty, UpDataStructsRpcCollection, UpDataStructsSponsoringRateLimit, UpDataStructsSponsorshipState, UpDataStructsTokenChild, UpDataStructsTokenData, XcmDoubleEncoded, XcmV0Junction, XcmV0JunctionBodyId, XcmV0JunctionBodyPart, XcmV0JunctionNetworkId, XcmV0MultiAsset, XcmV0MultiLocation, XcmV0Order, XcmV0OriginKind, XcmV0Response, XcmV0Xcm, XcmV1Junction, XcmV1MultiAsset, XcmV1MultiLocation, XcmV1MultiassetAssetId, XcmV1MultiassetAssetInstance, XcmV1MultiassetFungibility, XcmV1MultiassetMultiAssetFilter, XcmV1MultiassetMultiAssets, XcmV1MultiassetWildFungibility, XcmV1MultiassetWildMultiAsset, XcmV1MultilocationJunctions, XcmV1Order, XcmV1Response, XcmV1Xcm, XcmV2Instruction, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2WeightLimit, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from './default';
 import type { Data, StorageKey } from '@polkadot/types';
 import type { BitVec, Bool, Bytes, I128, I16, I256, I32, I64, I8, Json, Null, OptionBool, Raw, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types-codec';
 import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -1210,6 +1210,7 @@
     UpDataStructsRpcCollection: UpDataStructsRpcCollection;
     UpDataStructsSponsoringRateLimit: UpDataStructsSponsoringRateLimit;
     UpDataStructsSponsorshipState: UpDataStructsSponsorshipState;
+    UpDataStructsTokenChild: UpDataStructsTokenChild;
     UpDataStructsTokenData: UpDataStructsTokenData;
     UpgradeGoAhead: UpgradeGoAhead;
     UpgradeRestriction: UpgradeRestriction;
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1588,7 +1588,7 @@
 }
 
 /** @name PhantomTypeUpDataStructs */
-export interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, PalletEvmAccountBasicCrossAccountIdRepr, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkNftInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkTheme, UpDataStructsRmrkNftChild]>> {}
+export interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkNftInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkTheme, UpDataStructsRmrkNftChild]>> {}
 
 /** @name PolkadotCorePrimitivesInboundDownwardMessage */
 export interface PolkadotCorePrimitivesInboundDownwardMessage extends Struct {
@@ -1861,7 +1861,6 @@
 
 /** @name UpDataStructsCreateNftData */
 export interface UpDataStructsCreateNftData extends Struct {
-  readonly constData: Bytes;
   readonly properties: Vec<UpDataStructsProperty>;
 }
 
@@ -2101,6 +2100,12 @@
   readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
 }
 
+/** @name UpDataStructsTokenChild */
+export interface UpDataStructsTokenChild extends Struct {
+  readonly token: u32;
+  readonly collection: u32;
+}
+
 /** @name UpDataStructsTokenData */
 export interface UpDataStructsTokenData extends Struct {
   readonly properties: Vec<UpDataStructsProperty>;
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -1479,17 +1479,16 @@
    * Lookup186: up_data_structs::CreateNftData
    **/
   UpDataStructsCreateNftData: {
-    constData: 'Bytes',
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup188: up_data_structs::CreateFungibleData
+   * Lookup187: up_data_structs::CreateFungibleData
    **/
   UpDataStructsCreateFungibleData: {
     value: 'u128'
   },
   /**
-   * Lookup189: up_data_structs::CreateReFungibleData
+   * Lookup188: up_data_structs::CreateReFungibleData
    **/
   UpDataStructsCreateReFungibleData: {
     constData: 'Bytes',
@@ -2282,18 +2281,25 @@
     alive: 'u32'
   },
   /**
-   * Lookup323: PhantomType::up_data_structs<T>
+   * Lookup323: up_data_structs::TokenChild
    **/
-  PhantomTypeUpDataStructs: '[(UpDataStructsTokenData,UpDataStructsRpcCollection,PalletEvmAccountBasicCrossAccountIdRepr,UpDataStructsRmrkCollectionInfo,UpDataStructsRmrkNftInfo,UpDataStructsRmrkResourceInfo,UpDataStructsRmrkPropertyInfo,UpDataStructsRmrkBaseInfo,UpDataStructsRmrkPartType,UpDataStructsRmrkTheme,UpDataStructsRmrkNftChild);0]',
+  UpDataStructsTokenChild: {
+    token: 'u32',
+    collection: 'u32'
+  },
+  /**
+   * Lookup324: PhantomType::up_data_structs<T>
+   **/
+  PhantomTypeUpDataStructs: '[(UpDataStructsTokenData,UpDataStructsRpcCollection,UpDataStructsRmrkCollectionInfo,UpDataStructsRmrkNftInfo,UpDataStructsRmrkResourceInfo,UpDataStructsRmrkPropertyInfo,UpDataStructsRmrkBaseInfo,UpDataStructsRmrkPartType,UpDataStructsRmrkTheme,UpDataStructsRmrkNftChild);0]',
   /**
-   * Lookup325: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup326: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsTokenData: {
     properties: 'Vec<UpDataStructsProperty>',
     owner: 'Option<PalletEvmAccountBasicCrossAccountIdRepr>'
   },
   /**
-   * Lookup327: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
+   * Lookup328: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
    **/
   UpDataStructsRpcCollection: {
     owner: 'AccountId32',
@@ -2308,7 +2314,7 @@
     properties: 'Vec<UpDataStructsProperty>'
   },
   /**
-   * Lookup328: up_data_structs::rmrk::CollectionInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>, sp_core::crypto::AccountId32>
+   * Lookup329: up_data_structs::rmrk::CollectionInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>, sp_core::crypto::AccountId32>
    **/
   UpDataStructsRmrkCollectionInfo: {
     issuer: 'AccountId32',
@@ -2318,7 +2324,7 @@
     nftsCount: 'u32'
   },
   /**
-   * Lookup331: up_data_structs::rmrk::NftInfo<sp_core::crypto::AccountId32, sp_arithmetic::per_things::Permill, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup332: up_data_structs::rmrk::NftInfo<sp_core::crypto::AccountId32, sp_arithmetic::per_things::Permill, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkNftInfo: {
     owner: 'UpDataStructsRmrkAccountIdOrCollectionNftTuple',
@@ -2328,7 +2334,7 @@
     pending: 'bool'
   },
   /**
-   * Lookup332: up_data_structs::rmrk::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
+   * Lookup333: up_data_structs::rmrk::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
    **/
   UpDataStructsRmrkAccountIdOrCollectionNftTuple: {
     _enum: {
@@ -2337,14 +2343,14 @@
     }
   },
   /**
-   * Lookup334: up_data_structs::rmrk::RoyaltyInfo<sp_core::crypto::AccountId32, sp_arithmetic::per_things::Permill>
+   * Lookup335: up_data_structs::rmrk::RoyaltyInfo<sp_core::crypto::AccountId32, sp_arithmetic::per_things::Permill>
    **/
   UpDataStructsRmrkRoyaltyInfo: {
     recipient: 'AccountId32',
     amount: 'Permill'
   },
   /**
-   * Lookup335: up_data_structs::rmrk::ResourceInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup336: up_data_structs::rmrk::ResourceInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkResourceInfo: {
     id: 'Bytes',
@@ -2353,7 +2359,7 @@
     pendingRemoval: 'bool'
   },
   /**
-   * Lookup338: up_data_structs::rmrk::ResourceTypes<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup339: up_data_structs::rmrk::ResourceTypes<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkResourceTypes: {
     _enum: {
@@ -2363,7 +2369,7 @@
     }
   },
   /**
-   * Lookup339: up_data_structs::rmrk::BasicResource<frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup340: up_data_structs::rmrk::BasicResource<frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkBasicResource: {
     src: 'Option<Bytes>',
@@ -2372,7 +2378,7 @@
     thumb: 'Option<Bytes>'
   },
   /**
-   * Lookup341: up_data_structs::rmrk::ComposableResource<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup342: up_data_structs::rmrk::ComposableResource<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkComposableResource: {
     parts: 'Vec<u32>',
@@ -2383,7 +2389,7 @@
     thumb: 'Option<Bytes>'
   },
   /**
-   * Lookup342: up_data_structs::rmrk::SlotResource<frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup343: up_data_structs::rmrk::SlotResource<frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkSlotResource: {
     base: 'u32',
@@ -2394,14 +2400,14 @@
     thumb: 'Option<Bytes>'
   },
   /**
-   * Lookup343: up_data_structs::rmrk::PropertyInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup344: up_data_structs::rmrk::PropertyInfo<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkPropertyInfo: {
     key: 'Bytes',
     value: 'Bytes'
   },
   /**
-   * Lookup346: up_data_structs::rmrk::BaseInfo<sp_core::crypto::AccountId32, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup347: up_data_structs::rmrk::BaseInfo<sp_core::crypto::AccountId32, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkBaseInfo: {
     issuer: 'AccountId32',
@@ -2409,7 +2415,7 @@
     symbol: 'Bytes'
   },
   /**
-   * Lookup347: up_data_structs::rmrk::PartType<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup348: up_data_structs::rmrk::PartType<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkPartType: {
     _enum: {
@@ -2418,7 +2424,7 @@
     }
   },
   /**
-   * Lookup349: up_data_structs::rmrk::FixedPart<frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup350: up_data_structs::rmrk::FixedPart<frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkFixedPart: {
     id: 'u32',
@@ -2426,7 +2432,7 @@
     src: 'Bytes'
   },
   /**
-   * Lookup350: up_data_structs::rmrk::SlotPart<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup351: up_data_structs::rmrk::SlotPart<frame_support::storage::bounded_vec::BoundedVec<T, S>, frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkSlotPart: {
     id: 'u32',
@@ -2435,7 +2441,7 @@
     z: 'u32'
   },
   /**
-   * Lookup351: up_data_structs::rmrk::EquippableList<frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup352: up_data_structs::rmrk::EquippableList<frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkEquippableList: {
     _enum: {
@@ -2445,7 +2451,7 @@
     }
   },
   /**
-   * Lookup352: up_data_structs::rmrk::Theme<frame_support::storage::bounded_vec::BoundedVec<T, S>, PropertyList>
+   * Lookup353: up_data_structs::rmrk::Theme<frame_support::storage::bounded_vec::BoundedVec<T, S>, PropertyList>
    **/
   UpDataStructsRmrkTheme: {
     name: 'Bytes',
@@ -2453,69 +2459,69 @@
     inherit: 'bool'
   },
   /**
-   * Lookup354: up_data_structs::rmrk::ThemeProperty<frame_support::storage::bounded_vec::BoundedVec<T, S>>
+   * Lookup355: up_data_structs::rmrk::ThemeProperty<frame_support::storage::bounded_vec::BoundedVec<T, S>>
    **/
   UpDataStructsRmrkThemeProperty: {
     key: 'Bytes',
     value: 'Bytes'
   },
   /**
-   * Lookup355: up_data_structs::rmrk::NftChild
+   * Lookup356: up_data_structs::rmrk::NftChild
    **/
   UpDataStructsRmrkNftChild: {
     collectionId: 'u32',
     nftId: 'u32'
   },
   /**
-   * Lookup357: pallet_common::pallet::Error<T>
+   * Lookup358: pallet_common::pallet::Error<T>
    **/
   PalletCommonError: {
     _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'NestingIsDisabled', 'OnlyOwnerAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey']
   },
   /**
-   * Lookup359: pallet_fungible::pallet::Error<T>
+   * Lookup360: pallet_fungible::pallet::Error<T>
    **/
   PalletFungibleError: {
     _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
   },
   /**
-   * Lookup360: pallet_refungible::ItemData
+   * Lookup361: pallet_refungible::ItemData
    **/
   PalletRefungibleItemData: {
     constData: 'Bytes'
   },
   /**
-   * Lookup364: pallet_refungible::pallet::Error<T>
+   * Lookup365: pallet_refungible::pallet::Error<T>
    **/
   PalletRefungibleError: {
     _enum: ['NotRefungibleDataUsedToMintFungibleCollectionToken', 'WrongRefungiblePieces', 'RefungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
   },
   /**
-   * Lookup365: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup366: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   PalletNonfungibleItemData: {
     owner: 'PalletEvmAccountBasicCrossAccountIdRepr'
   },
   /**
-   * Lookup367: pallet_nonfungible::pallet::Error<T>
+   * Lookup368: pallet_nonfungible::pallet::Error<T>
    **/
   PalletNonfungibleError: {
     _enum: ['NotNonfungibleDataUsedToMintFungibleCollectionToken', 'NonfungibleItemsHaveNoAmount', 'CantBurnNftWithChildren']
   },
   /**
-   * Lookup368: pallet_structure::pallet::Error<T>
+   * Lookup369: pallet_structure::pallet::Error<T>
    **/
   PalletStructureError: {
     _enum: ['OuroborosDetected', 'DepthLimit', 'TokenNotFound']
   },
   /**
-   * Lookup371: pallet_evm::pallet::Error<T>
+   * Lookup372: pallet_evm::pallet::Error<T>
    **/
   PalletEvmError: {
     _enum: ['BalanceLow', 'FeeOverflow', 'PaymentOverflow', 'WithdrawFailed', 'GasPriceTooLow', 'InvalidNonce']
   },
   /**
-   * Lookup374: fp_rpc::TransactionStatus
+   * Lookup375: fp_rpc::TransactionStatus
    **/
   FpRpcTransactionStatus: {
     transactionHash: 'H256',
@@ -2527,11 +2533,11 @@
     logsBloom: 'EthbloomBloom'
   },
   /**
-   * Lookup376: ethbloom::Bloom
+   * Lookup377: ethbloom::Bloom
    **/
   EthbloomBloom: '[u8;256]',
   /**
-   * Lookup378: ethereum::receipt::ReceiptV3
+   * Lookup379: ethereum::receipt::ReceiptV3
    **/
   EthereumReceiptReceiptV3: {
     _enum: {
@@ -2541,7 +2547,7 @@
     }
   },
   /**
-   * Lookup379: ethereum::receipt::EIP658ReceiptData
+   * Lookup380: ethereum::receipt::EIP658ReceiptData
    **/
   EthereumReceiptEip658ReceiptData: {
     statusCode: 'u8',
@@ -2550,7 +2556,7 @@
     logs: 'Vec<EthereumLog>'
   },
   /**
-   * Lookup380: ethereum::block::Block<ethereum::transaction::TransactionV2>
+   * Lookup381: ethereum::block::Block<ethereum::transaction::TransactionV2>
    **/
   EthereumBlock: {
     header: 'EthereumHeader',
@@ -2558,7 +2564,7 @@
     ommers: 'Vec<EthereumHeader>'
   },
   /**
-   * Lookup381: ethereum::header::Header
+   * Lookup382: ethereum::header::Header
    **/
   EthereumHeader: {
     parentHash: 'H256',
@@ -2578,41 +2584,41 @@
     nonce: 'EthereumTypesHashH64'
   },
   /**
-   * Lookup382: ethereum_types::hash::H64
+   * Lookup383: ethereum_types::hash::H64
    **/
   EthereumTypesHashH64: '[u8;8]',
   /**
-   * Lookup387: pallet_ethereum::pallet::Error<T>
+   * Lookup388: pallet_ethereum::pallet::Error<T>
    **/
   PalletEthereumError: {
     _enum: ['InvalidSignature', 'PreLogExists']
   },
   /**
-   * Lookup388: pallet_evm_coder_substrate::pallet::Error<T>
+   * Lookup389: pallet_evm_coder_substrate::pallet::Error<T>
    **/
   PalletEvmCoderSubstrateError: {
     _enum: ['OutOfGas', 'OutOfFund']
   },
   /**
-   * Lookup389: pallet_evm_contract_helpers::SponsoringModeT
+   * Lookup390: pallet_evm_contract_helpers::SponsoringModeT
    **/
   PalletEvmContractHelpersSponsoringModeT: {
     _enum: ['Disabled', 'Allowlisted', 'Generous']
   },
   /**
-   * Lookup391: pallet_evm_contract_helpers::pallet::Error<T>
+   * Lookup392: pallet_evm_contract_helpers::pallet::Error<T>
    **/
   PalletEvmContractHelpersError: {
     _enum: ['NoPermission']
   },
   /**
-   * Lookup392: pallet_evm_migration::pallet::Error<T>
+   * Lookup393: pallet_evm_migration::pallet::Error<T>
    **/
   PalletEvmMigrationError: {
     _enum: ['AccountNotEmpty', 'AccountIsNotMigrating']
   },
   /**
-   * Lookup394: sp_runtime::MultiSignature
+   * Lookup395: sp_runtime::MultiSignature
    **/
   SpRuntimeMultiSignature: {
     _enum: {
@@ -2622,43 +2628,43 @@
     }
   },
   /**
-   * Lookup395: sp_core::ed25519::Signature
+   * Lookup396: sp_core::ed25519::Signature
    **/
   SpCoreEd25519Signature: '[u8;64]',
   /**
-   * Lookup397: sp_core::sr25519::Signature
+   * Lookup398: sp_core::sr25519::Signature
    **/
   SpCoreSr25519Signature: '[u8;64]',
   /**
-   * Lookup398: sp_core::ecdsa::Signature
+   * Lookup399: sp_core::ecdsa::Signature
    **/
   SpCoreEcdsaSignature: '[u8;65]',
   /**
-   * Lookup401: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
+   * Lookup402: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
    **/
   FrameSystemExtensionsCheckSpecVersion: 'Null',
   /**
-   * Lookup402: frame_system::extensions::check_genesis::CheckGenesis<T>
+   * Lookup403: frame_system::extensions::check_genesis::CheckGenesis<T>
    **/
   FrameSystemExtensionsCheckGenesis: 'Null',
   /**
-   * Lookup405: frame_system::extensions::check_nonce::CheckNonce<T>
+   * Lookup406: frame_system::extensions::check_nonce::CheckNonce<T>
    **/
   FrameSystemExtensionsCheckNonce: 'Compact<u32>',
   /**
-   * Lookup406: frame_system::extensions::check_weight::CheckWeight<T>
+   * Lookup407: frame_system::extensions::check_weight::CheckWeight<T>
    **/
   FrameSystemExtensionsCheckWeight: 'Null',
   /**
-   * Lookup407: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
+   * Lookup408: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
    **/
   PalletTemplateTransactionPaymentChargeTransactionPayment: 'Compact<u128>',
   /**
-   * Lookup408: opal_runtime::Runtime
+   * Lookup409: opal_runtime::Runtime
    **/
   OpalRuntimeRuntime: 'Null',
   /**
-   * Lookup409: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
+   * Lookup410: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
    **/
   PalletEthereumFakeTransactionFinalizer: 'Null'
 };
modifiedtests/src/interfaces/registry.tsdiffbeforeafterboth
--- a/tests/src/interfaces/registry.ts
+++ b/tests/src/interfaces/registry.ts
@@ -1,7 +1,7 @@
 // Auto-generated via `yarn polkadot-types-from-defs`, do not edit
 /* eslint-disable */
 
-import type { CumulusPalletDmpQueueCall, CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueueError, CumulusPalletDmpQueueEvent, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemCall, CumulusPalletParachainSystemError, CumulusPalletParachainSystemEvent, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmCall, CumulusPalletXcmError, CumulusPalletXcmEvent, CumulusPalletXcmpQueueCall, CumulusPalletXcmpQueueError, CumulusPalletXcmpQueueEvent, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueInboundState, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueOutboundState, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, EthbloomBloom, EthereumBlock, EthereumHeader, EthereumLog, EthereumReceiptEip658ReceiptData, EthereumReceiptReceiptV3, EthereumTransactionAccessListItem, EthereumTransactionEip1559Transaction, EthereumTransactionEip2930Transaction, EthereumTransactionLegacyTransaction, EthereumTransactionTransactionAction, EthereumTransactionTransactionSignature, EthereumTransactionTransactionV2, EthereumTypesHashH64, EvmCoreErrorExitError, EvmCoreErrorExitFatal, EvmCoreErrorExitReason, EvmCoreErrorExitRevert, EvmCoreErrorExitSucceed, FpRpcTransactionStatus, FrameSupportPalletId, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchClass, FrameSupportWeightsDispatchInfo, FrameSupportWeightsPays, FrameSupportWeightsPerDispatchClassU32, FrameSupportWeightsPerDispatchClassU64, FrameSupportWeightsPerDispatchClassWeightsPerClass, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemAccountInfo, FrameSystemCall, FrameSystemError, FrameSystemEvent, FrameSystemEventRecord, FrameSystemExtensionsCheckGenesis, FrameSystemExtensionsCheckNonce, FrameSystemExtensionsCheckSpecVersion, FrameSystemExtensionsCheckWeight, FrameSystemLastRuntimeUpgradeInfo, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, FrameSystemLimitsWeightsPerClass, FrameSystemPhase, OpalRuntimeRuntime, OrmlVestingModuleCall, OrmlVestingModuleError, OrmlVestingModuleEvent, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesCall, PalletBalancesError, PalletBalancesEvent, PalletBalancesReasons, PalletBalancesReleases, PalletBalancesReserveData, PalletCommonError, PalletCommonEvent, PalletEthereumCall, PalletEthereumError, PalletEthereumEvent, PalletEthereumFakeTransactionFinalizer, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmCall, PalletEvmCoderSubstrateError, PalletEvmContractHelpersError, PalletEvmContractHelpersSponsoringModeT, PalletEvmError, PalletEvmEvent, PalletEvmMigrationCall, PalletEvmMigrationError, PalletFungibleError, PalletInflationCall, PalletNonfungibleError, PalletNonfungibleItemData, PalletRefungibleError, PalletRefungibleItemData, PalletStructureCall, PalletStructureError, PalletStructureEvent, PalletSudoCall, PalletSudoError, PalletSudoEvent, PalletTemplateTransactionPaymentCall, PalletTemplateTransactionPaymentChargeTransactionPayment, PalletTimestampCall, PalletTransactionPaymentReleases, PalletTreasuryCall, PalletTreasuryError, PalletTreasuryEvent, PalletTreasuryProposal, PalletUniqueCall, PalletUniqueError, PalletUniqueRawEvent, PalletXcmCall, PalletXcmError, PalletXcmEvent, PhantomTypeUpDataStructs, PolkadotCorePrimitivesInboundDownwardMessage, PolkadotCorePrimitivesInboundHrmpMessage, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2AbridgedHrmpChannel, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpCoreEcdsaSignature, SpCoreEd25519Signature, SpCoreSr25519Signature, SpRuntimeArithmeticError, SpRuntimeDigest, SpRuntimeDigestDigestItem, SpRuntimeDispatchError, SpRuntimeModuleError, SpRuntimeMultiSignature, SpRuntimeTokenError, SpRuntimeTransactionalError, SpTrieStorageProof, SpVersionRuntimeVersion, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionPermissions, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateFungibleData, UpDataStructsCreateItemData, UpDataStructsCreateItemExData, UpDataStructsCreateNftData, UpDataStructsCreateNftExData, UpDataStructsCreateReFungibleData, UpDataStructsCreateRefungibleExData, UpDataStructsNestingRule, UpDataStructsProperties, UpDataStructsPropertiesMapBoundedVec, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsPropertyPermission, UpDataStructsRmrkAccountIdOrCollectionNftTuple, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkBasicResource, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkComposableResource, UpDataStructsRmrkEquippableList, UpDataStructsRmrkFixedPart, UpDataStructsRmrkNftChild, UpDataStructsRmrkNftInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkResourceTypes, UpDataStructsRmrkRoyaltyInfo, UpDataStructsRmrkSlotPart, UpDataStructsRmrkSlotResource, UpDataStructsRmrkTheme, UpDataStructsRmrkThemeProperty, UpDataStructsRpcCollection, UpDataStructsSponsoringRateLimit, UpDataStructsSponsorshipState, UpDataStructsTokenData, XcmDoubleEncoded, XcmV0Junction, XcmV0JunctionBodyId, XcmV0JunctionBodyPart, XcmV0JunctionNetworkId, XcmV0MultiAsset, XcmV0MultiLocation, XcmV0Order, XcmV0OriginKind, XcmV0Response, XcmV0Xcm, XcmV1Junction, XcmV1MultiAsset, XcmV1MultiLocation, XcmV1MultiassetAssetId, XcmV1MultiassetAssetInstance, XcmV1MultiassetFungibility, XcmV1MultiassetMultiAssetFilter, XcmV1MultiassetMultiAssets, XcmV1MultiassetWildFungibility, XcmV1MultiassetWildMultiAsset, XcmV1MultilocationJunctions, XcmV1Order, XcmV1Response, XcmV1Xcm, XcmV2Instruction, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2WeightLimit, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from '@polkadot/types/lookup';
+import type { CumulusPalletDmpQueueCall, CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueueError, CumulusPalletDmpQueueEvent, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemCall, CumulusPalletParachainSystemError, CumulusPalletParachainSystemEvent, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmCall, CumulusPalletXcmError, CumulusPalletXcmEvent, CumulusPalletXcmpQueueCall, CumulusPalletXcmpQueueError, CumulusPalletXcmpQueueEvent, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueInboundState, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueOutboundState, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, EthbloomBloom, EthereumBlock, EthereumHeader, EthereumLog, EthereumReceiptEip658ReceiptData, EthereumReceiptReceiptV3, EthereumTransactionAccessListItem, EthereumTransactionEip1559Transaction, EthereumTransactionEip2930Transaction, EthereumTransactionLegacyTransaction, EthereumTransactionTransactionAction, EthereumTransactionTransactionSignature, EthereumTransactionTransactionV2, EthereumTypesHashH64, EvmCoreErrorExitError, EvmCoreErrorExitFatal, EvmCoreErrorExitReason, EvmCoreErrorExitRevert, EvmCoreErrorExitSucceed, FpRpcTransactionStatus, FrameSupportPalletId, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchClass, FrameSupportWeightsDispatchInfo, FrameSupportWeightsPays, FrameSupportWeightsPerDispatchClassU32, FrameSupportWeightsPerDispatchClassU64, FrameSupportWeightsPerDispatchClassWeightsPerClass, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemAccountInfo, FrameSystemCall, FrameSystemError, FrameSystemEvent, FrameSystemEventRecord, FrameSystemExtensionsCheckGenesis, FrameSystemExtensionsCheckNonce, FrameSystemExtensionsCheckSpecVersion, FrameSystemExtensionsCheckWeight, FrameSystemLastRuntimeUpgradeInfo, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, FrameSystemLimitsWeightsPerClass, FrameSystemPhase, OpalRuntimeRuntime, OrmlVestingModuleCall, OrmlVestingModuleError, OrmlVestingModuleEvent, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesCall, PalletBalancesError, PalletBalancesEvent, PalletBalancesReasons, PalletBalancesReleases, PalletBalancesReserveData, PalletCommonError, PalletCommonEvent, PalletEthereumCall, PalletEthereumError, PalletEthereumEvent, PalletEthereumFakeTransactionFinalizer, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmCall, PalletEvmCoderSubstrateError, PalletEvmContractHelpersError, PalletEvmContractHelpersSponsoringModeT, PalletEvmError, PalletEvmEvent, PalletEvmMigrationCall, PalletEvmMigrationError, PalletFungibleError, PalletInflationCall, PalletNonfungibleError, PalletNonfungibleItemData, PalletRefungibleError, PalletRefungibleItemData, PalletStructureCall, PalletStructureError, PalletStructureEvent, PalletSudoCall, PalletSudoError, PalletSudoEvent, PalletTemplateTransactionPaymentCall, PalletTemplateTransactionPaymentChargeTransactionPayment, PalletTimestampCall, PalletTransactionPaymentReleases, PalletTreasuryCall, PalletTreasuryError, PalletTreasuryEvent, PalletTreasuryProposal, PalletUniqueCall, PalletUniqueError, PalletUniqueRawEvent, PalletXcmCall, PalletXcmError, PalletXcmEvent, PhantomTypeUpDataStructs, PolkadotCorePrimitivesInboundDownwardMessage, PolkadotCorePrimitivesInboundHrmpMessage, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2AbridgedHrmpChannel, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpCoreEcdsaSignature, SpCoreEd25519Signature, SpCoreSr25519Signature, SpRuntimeArithmeticError, SpRuntimeDigest, SpRuntimeDigestDigestItem, SpRuntimeDispatchError, SpRuntimeModuleError, SpRuntimeMultiSignature, SpRuntimeTokenError, SpRuntimeTransactionalError, SpTrieStorageProof, SpVersionRuntimeVersion, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionPermissions, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateFungibleData, UpDataStructsCreateItemData, UpDataStructsCreateItemExData, UpDataStructsCreateNftData, UpDataStructsCreateNftExData, UpDataStructsCreateReFungibleData, UpDataStructsCreateRefungibleExData, UpDataStructsNestingRule, UpDataStructsProperties, UpDataStructsPropertiesMapBoundedVec, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsPropertyPermission, UpDataStructsRmrkAccountIdOrCollectionNftTuple, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkBasicResource, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkComposableResource, UpDataStructsRmrkEquippableList, UpDataStructsRmrkFixedPart, UpDataStructsRmrkNftChild, UpDataStructsRmrkNftInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkResourceTypes, UpDataStructsRmrkRoyaltyInfo, UpDataStructsRmrkSlotPart, UpDataStructsRmrkSlotResource, UpDataStructsRmrkTheme, UpDataStructsRmrkThemeProperty, UpDataStructsRpcCollection, UpDataStructsSponsoringRateLimit, UpDataStructsSponsorshipState, UpDataStructsTokenChild, UpDataStructsTokenData, XcmDoubleEncoded, XcmV0Junction, XcmV0JunctionBodyId, XcmV0JunctionBodyPart, XcmV0JunctionNetworkId, XcmV0MultiAsset, XcmV0MultiLocation, XcmV0Order, XcmV0OriginKind, XcmV0Response, XcmV0Xcm, XcmV1Junction, XcmV1MultiAsset, XcmV1MultiLocation, XcmV1MultiassetAssetId, XcmV1MultiassetAssetInstance, XcmV1MultiassetFungibility, XcmV1MultiassetMultiAssetFilter, XcmV1MultiassetMultiAssets, XcmV1MultiassetWildFungibility, XcmV1MultiassetWildMultiAsset, XcmV1MultilocationJunctions, XcmV1Order, XcmV1Response, XcmV1Xcm, XcmV2Instruction, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2WeightLimit, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from '@polkadot/types/lookup';
 
 declare module '@polkadot/types/types/registry' {
   export interface InterfaceTypes {
@@ -188,6 +188,7 @@
     UpDataStructsRpcCollection: UpDataStructsRpcCollection;
     UpDataStructsSponsoringRateLimit: UpDataStructsSponsoringRateLimit;
     UpDataStructsSponsorshipState: UpDataStructsSponsorshipState;
+    UpDataStructsTokenChild: UpDataStructsTokenChild;
     UpDataStructsTokenData: UpDataStructsTokenData;
     XcmDoubleEncoded: XcmDoubleEncoded;
     XcmV0Junction: XcmV0Junction;
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -1604,16 +1604,15 @@
 
   /** @name UpDataStructsCreateNftData (186) */
   export interface UpDataStructsCreateNftData extends Struct {
-    readonly constData: Bytes;
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name UpDataStructsCreateFungibleData (188) */
+  /** @name UpDataStructsCreateFungibleData (187) */
   export interface UpDataStructsCreateFungibleData extends Struct {
     readonly value: u128;
   }
 
-  /** @name UpDataStructsCreateReFungibleData (189) */
+  /** @name UpDataStructsCreateReFungibleData (188) */
   export interface UpDataStructsCreateReFungibleData extends Struct {
     readonly constData: Bytes;
     readonly pieces: u128;
@@ -2469,16 +2468,22 @@
     readonly alive: u32;
   }
 
-  /** @name PhantomTypeUpDataStructs (323) */
-  export interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, PalletEvmAccountBasicCrossAccountIdRepr, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkNftInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkTheme, UpDataStructsRmrkNftChild]>> {}
+  /** @name UpDataStructsTokenChild (323) */
+  export interface UpDataStructsTokenChild extends Struct {
+    readonly token: u32;
+    readonly collection: u32;
+  }
+
+  /** @name PhantomTypeUpDataStructs (324) */
+  export interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkNftInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkTheme, UpDataStructsRmrkNftChild]>> {}
 
-  /** @name UpDataStructsTokenData (325) */
+  /** @name UpDataStructsTokenData (326) */
   export interface UpDataStructsTokenData extends Struct {
     readonly properties: Vec<UpDataStructsProperty>;
     readonly owner: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
   }
 
-  /** @name UpDataStructsRpcCollection (327) */
+  /** @name UpDataStructsRpcCollection (328) */
   export interface UpDataStructsRpcCollection extends Struct {
     readonly owner: AccountId32;
     readonly mode: UpDataStructsCollectionMode;
@@ -2492,7 +2497,7 @@
     readonly properties: Vec<UpDataStructsProperty>;
   }
 
-  /** @name UpDataStructsRmrkCollectionInfo (328) */
+  /** @name UpDataStructsRmrkCollectionInfo (329) */
   export interface UpDataStructsRmrkCollectionInfo extends Struct {
     readonly issuer: AccountId32;
     readonly metadata: Bytes;
@@ -2501,7 +2506,7 @@
     readonly nftsCount: u32;
   }
 
-  /** @name UpDataStructsRmrkNftInfo (331) */
+  /** @name UpDataStructsRmrkNftInfo (332) */
   export interface UpDataStructsRmrkNftInfo extends Struct {
     readonly owner: UpDataStructsRmrkAccountIdOrCollectionNftTuple;
     readonly royalty: Option<UpDataStructsRmrkRoyaltyInfo>;
@@ -2510,7 +2515,7 @@
     readonly pending: bool;
   }
 
-  /** @name UpDataStructsRmrkAccountIdOrCollectionNftTuple (332) */
+  /** @name UpDataStructsRmrkAccountIdOrCollectionNftTuple (333) */
   export interface UpDataStructsRmrkAccountIdOrCollectionNftTuple extends Enum {
     readonly isAccountId: boolean;
     readonly asAccountId: AccountId32;
@@ -2519,13 +2524,13 @@
     readonly type: 'AccountId' | 'CollectionAndNftTuple';
   }
 
-  /** @name UpDataStructsRmrkRoyaltyInfo (334) */
+  /** @name UpDataStructsRmrkRoyaltyInfo (335) */
   export interface UpDataStructsRmrkRoyaltyInfo extends Struct {
     readonly recipient: AccountId32;
     readonly amount: Permill;
   }
 
-  /** @name UpDataStructsRmrkResourceInfo (335) */
+  /** @name UpDataStructsRmrkResourceInfo (336) */
   export interface UpDataStructsRmrkResourceInfo extends Struct {
     readonly id: Bytes;
     readonly resource: UpDataStructsRmrkResourceTypes;
@@ -2533,7 +2538,7 @@
     readonly pendingRemoval: bool;
   }
 
-  /** @name UpDataStructsRmrkResourceTypes (338) */
+  /** @name UpDataStructsRmrkResourceTypes (339) */
   export interface UpDataStructsRmrkResourceTypes extends Enum {
     readonly isBasic: boolean;
     readonly asBasic: UpDataStructsRmrkBasicResource;
@@ -2544,7 +2549,7 @@
     readonly type: 'Basic' | 'Composable' | 'Slot';
   }
 
-  /** @name UpDataStructsRmrkBasicResource (339) */
+  /** @name UpDataStructsRmrkBasicResource (340) */
   export interface UpDataStructsRmrkBasicResource extends Struct {
     readonly src: Option<Bytes>;
     readonly metadata: Option<Bytes>;
@@ -2552,7 +2557,7 @@
     readonly thumb: Option<Bytes>;
   }
 
-  /** @name UpDataStructsRmrkComposableResource (341) */
+  /** @name UpDataStructsRmrkComposableResource (342) */
   export interface UpDataStructsRmrkComposableResource extends Struct {
     readonly parts: Vec<u32>;
     readonly base: u32;
@@ -2562,7 +2567,7 @@
     readonly thumb: Option<Bytes>;
   }
 
-  /** @name UpDataStructsRmrkSlotResource (342) */
+  /** @name UpDataStructsRmrkSlotResource (343) */
   export interface UpDataStructsRmrkSlotResource extends Struct {
     readonly base: u32;
     readonly src: Option<Bytes>;
@@ -2572,20 +2577,20 @@
     readonly thumb: Option<Bytes>;
   }
 
-  /** @name UpDataStructsRmrkPropertyInfo (343) */
+  /** @name UpDataStructsRmrkPropertyInfo (344) */
   export interface UpDataStructsRmrkPropertyInfo extends Struct {
     readonly key: Bytes;
     readonly value: Bytes;
   }
 
-  /** @name UpDataStructsRmrkBaseInfo (346) */
+  /** @name UpDataStructsRmrkBaseInfo (347) */
   export interface UpDataStructsRmrkBaseInfo extends Struct {
     readonly issuer: AccountId32;
     readonly baseType: Bytes;
     readonly symbol: Bytes;
   }
 
-  /** @name UpDataStructsRmrkPartType (347) */
+  /** @name UpDataStructsRmrkPartType (348) */
   export interface UpDataStructsRmrkPartType extends Enum {
     readonly isFixedPart: boolean;
     readonly asFixedPart: UpDataStructsRmrkFixedPart;
@@ -2594,14 +2599,14 @@
     readonly type: 'FixedPart' | 'SlotPart';
   }
 
-  /** @name UpDataStructsRmrkFixedPart (349) */
+  /** @name UpDataStructsRmrkFixedPart (350) */
   export interface UpDataStructsRmrkFixedPart extends Struct {
     readonly id: u32;
     readonly z: u32;
     readonly src: Bytes;
   }
 
-  /** @name UpDataStructsRmrkSlotPart (350) */
+  /** @name UpDataStructsRmrkSlotPart (351) */
   export interface UpDataStructsRmrkSlotPart extends Struct {
     readonly id: u32;
     readonly equippable: UpDataStructsRmrkEquippableList;
@@ -2609,7 +2614,7 @@
     readonly z: u32;
   }
 
-  /** @name UpDataStructsRmrkEquippableList (351) */
+  /** @name UpDataStructsRmrkEquippableList (352) */
   export interface UpDataStructsRmrkEquippableList extends Enum {
     readonly isAll: boolean;
     readonly isEmpty: boolean;
@@ -2618,26 +2623,26 @@
     readonly type: 'All' | 'Empty' | 'Custom';
   }
 
-  /** @name UpDataStructsRmrkTheme (352) */
+  /** @name UpDataStructsRmrkTheme (353) */
   export interface UpDataStructsRmrkTheme extends Struct {
     readonly name: Bytes;
     readonly properties: Vec<UpDataStructsRmrkThemeProperty>;
     readonly inherit: bool;
   }
 
-  /** @name UpDataStructsRmrkThemeProperty (354) */
+  /** @name UpDataStructsRmrkThemeProperty (355) */
   export interface UpDataStructsRmrkThemeProperty extends Struct {
     readonly key: Bytes;
     readonly value: Bytes;
   }
 
-  /** @name UpDataStructsRmrkNftChild (355) */
+  /** @name UpDataStructsRmrkNftChild (356) */
   export interface UpDataStructsRmrkNftChild extends Struct {
     readonly collectionId: u32;
     readonly nftId: u32;
   }
 
-  /** @name PalletCommonError (357) */
+  /** @name PalletCommonError (358) */
   export interface PalletCommonError extends Enum {
     readonly isCollectionNotFound: boolean;
     readonly isMustBeTokenOwner: boolean;
@@ -2675,7 +2680,7 @@
     readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'NestingIsDisabled' | 'OnlyOwnerAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey';
   }
 
-  /** @name PalletFungibleError (359) */
+  /** @name PalletFungibleError (360) */
   export interface PalletFungibleError extends Enum {
     readonly isNotFungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isFungibleItemsHaveNoId: boolean;
@@ -2685,12 +2690,12 @@
     readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
   }
 
-  /** @name PalletRefungibleItemData (360) */
+  /** @name PalletRefungibleItemData (361) */
   export interface PalletRefungibleItemData extends Struct {
     readonly constData: Bytes;
   }
 
-  /** @name PalletRefungibleError (364) */
+  /** @name PalletRefungibleError (365) */
   export interface PalletRefungibleError extends Enum {
     readonly isNotRefungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isWrongRefungiblePieces: boolean;
@@ -2699,12 +2704,12 @@
     readonly type: 'NotRefungibleDataUsedToMintFungibleCollectionToken' | 'WrongRefungiblePieces' | 'RefungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
   }
 
-  /** @name PalletNonfungibleItemData (365) */
+  /** @name PalletNonfungibleItemData (366) */
   export interface PalletNonfungibleItemData extends Struct {
     readonly owner: PalletEvmAccountBasicCrossAccountIdRepr;
   }
 
-  /** @name PalletNonfungibleError (367) */
+  /** @name PalletNonfungibleError (368) */
   export interface PalletNonfungibleError extends Enum {
     readonly isNotNonfungibleDataUsedToMintFungibleCollectionToken: boolean;
     readonly isNonfungibleItemsHaveNoAmount: boolean;
@@ -2712,7 +2717,7 @@
     readonly type: 'NotNonfungibleDataUsedToMintFungibleCollectionToken' | 'NonfungibleItemsHaveNoAmount' | 'CantBurnNftWithChildren';
   }
 
-  /** @name PalletStructureError (368) */
+  /** @name PalletStructureError (369) */
   export interface PalletStructureError extends Enum {
     readonly isOuroborosDetected: boolean;
     readonly isDepthLimit: boolean;
@@ -2720,7 +2725,7 @@
     readonly type: 'OuroborosDetected' | 'DepthLimit' | 'TokenNotFound';
   }
 
-  /** @name PalletEvmError (371) */
+  /** @name PalletEvmError (372) */
   export interface PalletEvmError extends Enum {
     readonly isBalanceLow: boolean;
     readonly isFeeOverflow: boolean;
@@ -2731,7 +2736,7 @@
     readonly type: 'BalanceLow' | 'FeeOverflow' | 'PaymentOverflow' | 'WithdrawFailed' | 'GasPriceTooLow' | 'InvalidNonce';
   }
 
-  /** @name FpRpcTransactionStatus (374) */
+  /** @name FpRpcTransactionStatus (375) */
   export interface FpRpcTransactionStatus extends Struct {
     readonly transactionHash: H256;
     readonly transactionIndex: u32;
@@ -2742,10 +2747,10 @@
     readonly logsBloom: EthbloomBloom;
   }
 
-  /** @name EthbloomBloom (376) */
+  /** @name EthbloomBloom (377) */
   export interface EthbloomBloom extends U8aFixed {}
 
-  /** @name EthereumReceiptReceiptV3 (378) */
+  /** @name EthereumReceiptReceiptV3 (379) */
   export interface EthereumReceiptReceiptV3 extends Enum {
     readonly isLegacy: boolean;
     readonly asLegacy: EthereumReceiptEip658ReceiptData;
@@ -2756,7 +2761,7 @@
     readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
   }
 
-  /** @name EthereumReceiptEip658ReceiptData (379) */
+  /** @name EthereumReceiptEip658ReceiptData (380) */
   export interface EthereumReceiptEip658ReceiptData extends Struct {
     readonly statusCode: u8;
     readonly usedGas: U256;
@@ -2764,14 +2769,14 @@
     readonly logs: Vec<EthereumLog>;
   }
 
-  /** @name EthereumBlock (380) */
+  /** @name EthereumBlock (381) */
   export interface EthereumBlock extends Struct {
     readonly header: EthereumHeader;
     readonly transactions: Vec<EthereumTransactionTransactionV2>;
     readonly ommers: Vec<EthereumHeader>;
   }
 
-  /** @name EthereumHeader (381) */
+  /** @name EthereumHeader (382) */
   export interface EthereumHeader extends Struct {
     readonly parentHash: H256;
     readonly ommersHash: H256;
@@ -2790,24 +2795,24 @@
     readonly nonce: EthereumTypesHashH64;
   }
 
-  /** @name EthereumTypesHashH64 (382) */
+  /** @name EthereumTypesHashH64 (383) */
   export interface EthereumTypesHashH64 extends U8aFixed {}
 
-  /** @name PalletEthereumError (387) */
+  /** @name PalletEthereumError (388) */
   export interface PalletEthereumError extends Enum {
     readonly isInvalidSignature: boolean;
     readonly isPreLogExists: boolean;
     readonly type: 'InvalidSignature' | 'PreLogExists';
   }
 
-  /** @name PalletEvmCoderSubstrateError (388) */
+  /** @name PalletEvmCoderSubstrateError (389) */
   export interface PalletEvmCoderSubstrateError extends Enum {
     readonly isOutOfGas: boolean;
     readonly isOutOfFund: boolean;
     readonly type: 'OutOfGas' | 'OutOfFund';
   }
 
-  /** @name PalletEvmContractHelpersSponsoringModeT (389) */
+  /** @name PalletEvmContractHelpersSponsoringModeT (390) */
   export interface PalletEvmContractHelpersSponsoringModeT extends Enum {
     readonly isDisabled: boolean;
     readonly isAllowlisted: boolean;
@@ -2815,20 +2820,20 @@
     readonly type: 'Disabled' | 'Allowlisted' | 'Generous';
   }
 
-  /** @name PalletEvmContractHelpersError (391) */
+  /** @name PalletEvmContractHelpersError (392) */
   export interface PalletEvmContractHelpersError extends Enum {
     readonly isNoPermission: boolean;
     readonly type: 'NoPermission';
   }
 
-  /** @name PalletEvmMigrationError (392) */
+  /** @name PalletEvmMigrationError (393) */
   export interface PalletEvmMigrationError extends Enum {
     readonly isAccountNotEmpty: boolean;
     readonly isAccountIsNotMigrating: boolean;
     readonly type: 'AccountNotEmpty' | 'AccountIsNotMigrating';
   }
 
-  /** @name SpRuntimeMultiSignature (394) */
+  /** @name SpRuntimeMultiSignature (395) */
   export interface SpRuntimeMultiSignature extends Enum {
     readonly isEd25519: boolean;
     readonly asEd25519: SpCoreEd25519Signature;
@@ -2839,34 +2844,34 @@
     readonly type: 'Ed25519' | 'Sr25519' | 'Ecdsa';
   }
 
-  /** @name SpCoreEd25519Signature (395) */
+  /** @name SpCoreEd25519Signature (396) */
   export interface SpCoreEd25519Signature extends U8aFixed {}
 
-  /** @name SpCoreSr25519Signature (397) */
+  /** @name SpCoreSr25519Signature (398) */
   export interface SpCoreSr25519Signature extends U8aFixed {}
 
-  /** @name SpCoreEcdsaSignature (398) */
+  /** @name SpCoreEcdsaSignature (399) */
   export interface SpCoreEcdsaSignature extends U8aFixed {}
 
-  /** @name FrameSystemExtensionsCheckSpecVersion (401) */
+  /** @name FrameSystemExtensionsCheckSpecVersion (402) */
   export type FrameSystemExtensionsCheckSpecVersion = Null;
 
-  /** @name FrameSystemExtensionsCheckGenesis (402) */
+  /** @name FrameSystemExtensionsCheckGenesis (403) */
   export type FrameSystemExtensionsCheckGenesis = Null;
 
-  /** @name FrameSystemExtensionsCheckNonce (405) */
+  /** @name FrameSystemExtensionsCheckNonce (406) */
   export interface FrameSystemExtensionsCheckNonce extends Compact<u32> {}
 
-  /** @name FrameSystemExtensionsCheckWeight (406) */
+  /** @name FrameSystemExtensionsCheckWeight (407) */
   export type FrameSystemExtensionsCheckWeight = Null;
 
-  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (407) */
+  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (408) */
   export interface PalletTemplateTransactionPaymentChargeTransactionPayment extends Compact<u128> {}
 
-  /** @name OpalRuntimeRuntime (408) */
+  /** @name OpalRuntimeRuntime (409) */
   export type OpalRuntimeRuntime = Null;
 
-  /** @name PalletEthereumFakeTransactionFinalizer (409) */
+  /** @name PalletEthereumFakeTransactionFinalizer (410) */
   export type PalletEthereumFakeTransactionFinalizer = Null;
 
 } // declare module
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -50,6 +50,7 @@
     allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),
     tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
     topmostTokenOwner: fun('Get token owner, in case of nested token - find parent recursive', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
+    tokenChildren: fun('Get tokens nested directly into the token', [collectionParam, tokenParam], 'Vec<UpDataStructsTokenChild>'),
     constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
     variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
     collectionProperties: fun(
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -7,6 +7,7 @@
   createItemExpectSuccess,
   enableAllowListExpectSuccess,
   enablePublicMintingExpectSuccess,
+  getTokenChildren,
   getTokenOwner,
   getTopmostTokenOwner,
   normalizeAccountId,
@@ -76,8 +77,8 @@
         api,
         alice,
         api.tx.unique.transferFrom(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}), 
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}), 
+          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}),
+          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}),
           collection,
           tokenC,
           1,
@@ -88,6 +89,63 @@
     });
   });
 
+  it('Checks token children', async () => {
+    await usingApi(async api => {
+      const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+      await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: 'Owner'});
+      const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+
+      const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
+      const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};
+      let children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(0, 'Children length check at creation');
+
+      // Create a nested NFT token
+      const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);
+      children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(1, 'Children length check at nesting #1');
+      expect(children).to.have.deep.members([
+        {token: tokenA, collection: collectionA},
+      ], 'Children contents check at nesting #1');
+
+      // Create then nest
+      const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');
+      await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);
+      children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(2, 'Children length check at nesting #2');
+      expect(children).to.have.deep.members([
+        {token: tokenA, collection: collectionA},
+        {token: tokenB, collection: collectionA},
+      ], 'Children contents check at nesting #2');
+
+      // Move token B to a different user outside the nesting tree
+      await transferExpectSuccess(collectionA, tokenB, alice, bob);
+      children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(1, 'Children length check at unnesting');
+      expect(children).to.be.have.deep.members([
+        {token: tokenA, collection: collectionA},
+      ], 'Children contents check at unnesting');
+
+      // Create a fungible token in another collection and then nest
+      const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');
+      await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');
+      children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');
+      expect(children).to.be.have.deep.members([
+        {token: tokenA, collection: collectionA},
+        {token: tokenC, collection: collectionB},
+      ], 'Children contents check at nesting #3 (from another collection)');
+
+      // Move the fungible token inside token A deeper in the nesting tree
+      await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');
+      children = await getTokenChildren(api, collectionA, targetToken);
+      expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');
+      expect(children).to.be.have.deep.members([
+        {token: tokenA, collection: collectionA},
+      ], 'Children contents check at deeper nesting');
+    });
+  });
+
   // ---------- Non-Fungible ----------
 
   it('NFT: allows an Owner to nest/unnest their token', async () => {
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';3031chai.use(chaiAsPromised);32const expect = chai.expect;3334export type CrossAccountId = {35  Substrate: string,36} | {37  Ethereum: string,38};3940export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {41  if (typeof input === 'string') {42    if (input.length === 48 || input.length === 47) {43      return {Substrate: input};44    } else if (input.length === 42 && input.startsWith('0x')) {45      return {Ethereum: input.toLowerCase()};46    } else if (input.length === 40 && !input.startsWith('0x')) {47      return {Ethereum: '0x' + input.toLowerCase()};48    } else {49      throw new Error(`Unknown address format: "${input}"`);50    }51  }52  if ('address' in input) {53    return {Substrate: input.address};54  }55  if ('Ethereum' in input) {56    return {57      Ethereum: input.Ethereum.toLowerCase(),58    };59  } else if ('ethereum' in input) {60    return {61      Ethereum: (input as any).ethereum.toLowerCase(),62    };63  } else if ('Substrate' in input) {64    return input;65  } else if ('substrate' in input) {66    return {67      Substrate: (input as any).substrate,68    };69  }7071  // AccountId72  return {Substrate: input.toString()};73}74export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {75  input = normalizeAccountId(input);76  if ('Substrate' in input) {77    return input.Substrate;78  } else {79    return evmToAddress(input.Ethereum);80  }81}8283export const U128_MAX = (1n << 128n) - 1n;8485const MICROUNIQUE = 1_000_000_000_000n;86const MILLIUNIQUE = 1_000n * MICROUNIQUE;87const CENTIUNIQUE = 10n * MILLIUNIQUE;88export const UNIQUE = 100n * CENTIUNIQUE;8990type GenericResult = {91  success: boolean,92};9394interface CreateCollectionResult {95  success: boolean;96  collectionId: number;97}9899interface CreateItemResult {100  success: boolean;101  collectionId: number;102  itemId: number;103  recipient?: CrossAccountId;104}105106interface TransferResult {107  collectionId: number;108  itemId: number;109  sender?: CrossAccountId;110  recipient?: CrossAccountId;111  value: bigint;112}113114interface IReFungibleOwner {115  fraction: BN;116  owner: number[];117}118119interface IGetMessage {120  checkMsgUnqMethod: string;121  checkMsgTrsMethod: string;122  checkMsgSysMethod: string;123}124125export interface IFungibleTokenDataType {126  value: number;127}128129export interface IChainLimits {130  collectionNumbersLimit: number;131  accountTokenOwnershipLimit: number;132  collectionsAdminsLimit: number;133  customDataLimit: number;134  nftSponsorTransferTimeout: number;135  fungibleSponsorTransferTimeout: number;136  refungibleSponsorTransferTimeout: number;137  //offchainSchemaLimit: number;138  //constOnChainSchemaLimit: number;139}140141export interface IReFungibleTokenDataType {142  owner: IReFungibleOwner[];143}144145export function uniqueEventMessage(events: EventRecord[]): IGetMessage {146  let checkMsgUnqMethod = '';147  let checkMsgTrsMethod = '';148  let checkMsgSysMethod = '';149  events.forEach(({event: {method, section}}) => {150    if (section === 'common') {151      checkMsgUnqMethod = method;152    } else if (section === 'treasury') {153      checkMsgTrsMethod = method;154    } else if (section === 'system') {155      checkMsgSysMethod = method;156    } else { return null; }157  });158  const result: IGetMessage = {159    checkMsgUnqMethod,160    checkMsgTrsMethod,161    checkMsgSysMethod,162  };163  return result;164}165166export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {167  const event = events.find(r => check(r.event));168  if (!event) return;169  return event.event as T;170}171172export function getGenericResult(events: EventRecord[]): GenericResult {173  const result: GenericResult = {174    success: false,175  };176  events.forEach(({event: {method}}) => {177    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);178    if (method === 'ExtrinsicSuccess') {179      result.success = true;180    }181  });182  return result;183}184185186187export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {188  let success = false;189  let collectionId = 0;190  events.forEach(({event: {data, method, section}}) => {191    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);192    if (method == 'ExtrinsicSuccess') {193      success = true;194    } else if ((section == 'common') && (method == 'CollectionCreated')) {195      collectionId = parseInt(data[0].toString(), 10);196    }197  });198  const result: CreateCollectionResult = {199    success,200    collectionId,201  };202  return result;203}204205export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {206  let success = false;207  let collectionId = 0;208  let itemId = 0;209  let recipient;210211  const results : CreateItemResult[]  = [];212213  events.forEach(({event: {data, method, section}}) => {214    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);215    if (method == 'ExtrinsicSuccess') {216      success = true;217    } else if ((section == 'common') && (method == 'ItemCreated')) {218      collectionId = parseInt(data[0].toString(), 10);219      itemId = parseInt(data[1].toString(), 10);220      recipient = normalizeAccountId(data[2].toJSON() as any);221222      const itemRes: CreateItemResult = {223        success,224        collectionId,225        itemId,226        recipient,227      };228229      results.push(itemRes);230    }231  });232233  return results;234}235236export function getCreateItemResult(events: EventRecord[]): CreateItemResult {237  let success = false;238  let collectionId = 0;239  let itemId = 0;240  let recipient;241  events.forEach(({event: {data, method, section}}) => {242    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);243    if (method == 'ExtrinsicSuccess') {244      success = true;245    } else if ((section == 'common') && (method == 'ItemCreated')) {246      collectionId = parseInt(data[0].toString(), 10);247      itemId = parseInt(data[1].toString(), 10);248      recipient = normalizeAccountId(data[2].toJSON() as any);249    }250  });251  const result: CreateItemResult = {252    success,253    collectionId,254    itemId,255    recipient,256  };257  return result;258}259260export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {261  for (const {event} of events) {262    if (api.events.common.Transfer.is(event)) {263      const [collection, token, sender, recipient, value] = event.data;264      return {265        collectionId: collection.toNumber(),266        itemId: token.toNumber(),267        sender: normalizeAccountId(sender.toJSON() as any),268        recipient: normalizeAccountId(recipient.toJSON() as any),269        value: value.toBigInt(),270      };271    }272  }273  throw new Error('no transfer event');274}275276interface Nft {277  type: 'NFT';278}279280interface Fungible {281  type: 'Fungible';282  decimalPoints: number;283}284285interface ReFungible {286  type: 'ReFungible';287}288289type CollectionMode = Nft | Fungible | ReFungible;290291export type Property = {292  key: any,293  value: any,294};295296type Permission = {297  mutable: boolean;298  collectionAdmin: boolean;299  tokenOwner: boolean;300}301302type PropertyPermission = {303  key: any;304  permission: Permission;305}306307export type CreateCollectionParams = {308  mode: CollectionMode,309  name: string,310  description: string,311  tokenPrefix: 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};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};325326  let collectionId = 0;327  await usingApi(async (api, privateKeyWrapper) => {328    // Get number of collections before the transaction329    const collectionCountBefore = await getCreatedCollectionCount(api);330331    // Run the CreateCollection transaction332    const alicePrivateKey = privateKeyWrapper('//Alice');333334    let modeprm = {};335    if (mode.type === 'NFT') {336      modeprm = {nft: null};337    } else if (mode.type === 'Fungible') {338      modeprm = {fungible: mode.decimalPoints};339    } else if (mode.type === 'ReFungible') {340      modeprm = {refungible: null};341    }342343    const tx = api.tx.unique.createCollectionEx({344      name: strToUTF16(name),345      description: strToUTF16(description),346      tokenPrefix: strToUTF16(tokenPrefix),347      mode: modeprm as any,348    });349    const events = await submitTransactionAsync(alicePrivateKey, tx);350    const result = getCreateCollectionResult(events);351352    // Get number of collections after the transaction353    const collectionCountAfter = await getCreatedCollectionCount(api);354355    // Get the collection356    const collection = await queryCollectionExpectSuccess(api, result.collectionId);357358    // What to expect359    // tslint:disable-next-line:no-unused-expression360    expect(result.success).to.be.true;361    expect(result.collectionId).to.be.equal(collectionCountAfter);362    // tslint:disable-next-line:no-unused-expression363    expect(collection).to.be.not.null;364    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');365    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));366    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);367    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);368    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);369370    collectionId = result.collectionId;371  });372373  return collectionId;374}375376export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {377  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};378379  let collectionId = 0;380  await usingApi(async (api, privateKeyWrapper) => {381    // Get number of collections before the transaction382    const collectionCountBefore = await getCreatedCollectionCount(api);383384    // Run the CreateCollection transaction385    const alicePrivateKey = privateKeyWrapper('//Alice');386387    let modeprm = {};388    if (mode.type === 'NFT') {389      modeprm = {nft: null};390    } else if (mode.type === 'Fungible') {391      modeprm = {fungible: mode.decimalPoints};392    } else if (mode.type === 'ReFungible') {393      modeprm = {refungible: null};394    }395396    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});397    const events = await submitTransactionAsync(alicePrivateKey, tx);398    const result = getCreateCollectionResult(events);399400    // Get number of collections after the transaction401    const collectionCountAfter = await getCreatedCollectionCount(api);402403    // Get the collection404    const collection = await queryCollectionExpectSuccess(api, result.collectionId);405406    // What to expect407    // tslint:disable-next-line:no-unused-expression408    expect(result.success).to.be.true;409    expect(result.collectionId).to.be.equal(collectionCountAfter);410    // tslint:disable-next-line:no-unused-expression411    expect(collection).to.be.not.null;412    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');413    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));414    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);415    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);416    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);417418419    collectionId = result.collectionId;420  });421422  return collectionId;423}424425export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {426  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};427428  await usingApi(async (api, privateKeyWrapper) => {429    // Get number of collections before the transaction430    const collectionCountBefore = await getCreatedCollectionCount(api);431432    // Run the CreateCollection transaction433    const alicePrivateKey = privateKeyWrapper('//Alice');434435    let modeprm = {};436    if (mode.type === 'NFT') {437      modeprm = {nft: null};438    } else if (mode.type === 'Fungible') {439      modeprm = {fungible: mode.decimalPoints};440    } else if (mode.type === 'ReFungible') {441      modeprm = {refungible: null};442    }443444    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});445    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;446447448    // Get number of collections after the transaction449    const collectionCountAfter = await getCreatedCollectionCount(api);450451    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');452  });453}454455export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {456  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};457458  let modeprm = {};459  if (mode.type === 'NFT') {460    modeprm = {nft: null};461  } else if (mode.type === 'Fungible') {462    modeprm = {fungible: mode.decimalPoints};463  } else if (mode.type === 'ReFungible') {464    modeprm = {refungible: null};465  }466467  await usingApi(async (api, privateKeyWrapper) => {468    // Get number of collections before the transaction469    const collectionCountBefore = await getCreatedCollectionCount(api);470471    // Run the CreateCollection transaction472    const alicePrivateKey = privateKeyWrapper('//Alice');473    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});474    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;475476    // Get number of collections after the transaction477    const collectionCountAfter = await getCreatedCollectionCount(api);478479    // What to expect480    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');481  });482}483484export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {485  let bal = 0n;486  let unused;487  do {488    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;489    const keyring = new Keyring({type: 'sr25519'});490    unused = keyring.addFromUri(`//${randomSeed}`);491    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();492  } while (bal !== 0n);493  return unused;494}495496export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {497  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();498}499500export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {501  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));502}503504export async function findNotExistingCollection(api: ApiPromise): Promise<number> {505  const totalNumber = await getCreatedCollectionCount(api);506  const newCollection: number = totalNumber + 1;507  return newCollection;508}509510function getDestroyResult(events: EventRecord[]): boolean {511  let success = false;512  events.forEach(({event: {method}}) => {513    if (method == 'ExtrinsicSuccess') {514      success = true;515    }516  });517  return success;518}519520export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {521  await usingApi(async (api, privateKeyWrapper) => {522    // Run the DestroyCollection transaction523    const alicePrivateKey = privateKeyWrapper(senderSeed);524    const tx = api.tx.unique.destroyCollection(collectionId);525    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;526  });527}528529export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {530  await usingApi(async (api, privateKeyWrapper) => {531    // Run the DestroyCollection transaction532    const alicePrivateKey = privateKeyWrapper(senderSeed);533    const tx = api.tx.unique.destroyCollection(collectionId);534    const events = await submitTransactionAsync(alicePrivateKey, tx);535    const result = getDestroyResult(events);536    expect(result).to.be.true;537538    // What to expect539    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;540  });541}542543export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {544  await usingApi(async (api) => {545    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);546    const events = await submitTransactionAsync(sender, tx);547    const result = getGenericResult(events);548549    expect(result.success).to.be.true;550  });551}552553export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {554  await usingApi(async(api) => {555    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561};562563export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {564  await usingApi(async (api) => {565    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {574  await usingApi(async (api, privateKeyWrapper) => {575576    // Run the transaction577    const senderPrivateKey = privateKeyWrapper(sender);578    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);579    const events = await submitTransactionAsync(senderPrivateKey, tx);580    const result = getGenericResult(events);581582    // Get the collection583    const collection = await queryCollectionExpectSuccess(api, collectionId);584585    // What to expect586    expect(result.success).to.be.true;587    expect(collection.sponsorship.toJSON()).to.deep.equal({588      unconfirmed: sponsor,589    });590  });591}592593export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {594  await usingApi(async (api, privateKeyWrapper) => {595596    // Run the transaction597    const alicePrivateKey = privateKeyWrapper(sender);598    const tx = api.tx.unique.removeCollectionSponsor(collectionId);599    const events = await submitTransactionAsync(alicePrivateKey, tx);600    const result = getGenericResult(events);601602    // Get the collection603    const collection = await queryCollectionExpectSuccess(api, collectionId);604605    // What to expect606    expect(result.success).to.be.true;607    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});608  });609}610611export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {612  await usingApi(async (api, privateKeyWrapper) => {613614    // Run the transaction615    const alicePrivateKey = privateKeyWrapper(senderSeed);616    const tx = api.tx.unique.removeCollectionSponsor(collectionId);617    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;618  });619}620621export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {622  await usingApi(async (api, privateKeyWrapper) => {623624    // Run the transaction625    const alicePrivateKey = privateKeyWrapper(senderSeed);626    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);627    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;628  });629}630631export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633634    // Run the transaction635    const sender = privateKeyWrapper(senderSeed);636    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);637  });638}639640export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {641  await usingApi(async (api, privateKeyWrapper) => {642643    // Run the transaction644    const tx = api.tx.unique.confirmSponsorship(collectionId);645    const events = await submitTransactionAsync(sender, tx);646    const result = getGenericResult(events);647648    // Get the collection649    const collection = await queryCollectionExpectSuccess(api, collectionId);650651    // What to expect652    expect(result.success).to.be.true;653    expect(collection.sponsorship.toJSON()).to.be.deep.equal({654      confirmed: sender.address,655    });656  });657}658659660export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {661  await usingApi(async (api, privateKeyWrapper) => {662663    // Run the transaction664    const sender = privateKeyWrapper(senderSeed);665    const tx = api.tx.unique.confirmSponsorship(collectionId);666    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;667  });668}669670export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {671  await usingApi(async (api) => {672    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);673    const events = await submitTransactionAsync(sender, tx);674    const result = getGenericResult(events);675676    expect(result.success).to.be.true;677  });678}679680export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681  await usingApi(async (api) => {682    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;684    const result = getGenericResult(events);685686    expect(result.success).to.be.false;687  });688}689690export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {691692  await usingApi(async (api) => {693694    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);695    const events = await submitTransactionAsync(sender, tx);696    const result = getGenericResult(events);697698    expect(result.success).to.be.true;699  });700}701702export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {703704  await usingApi(async (api) => {705706    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);707    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;708    const result = getGenericResult(events);709710    expect(result.success).to.be.false;711  });712}713714export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {715  await usingApi(async (api) => {716    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);717    const events = await submitTransactionAsync(sender, tx);718    const result = getGenericResult(events);719720    expect(result.success).to.be.true;721  });722}723724export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725  await usingApi(async (api) => {726    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;728    const result = getGenericResult(events);729730    expect(result.success).to.be.false;731  });732}733734export async function getNextSponsored(735  api: ApiPromise,736  collectionId: number,737  account: string | CrossAccountId,738  tokenId: number,739): Promise<number> {740  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));741}742743export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {744  await usingApi(async (api) => {745    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);746    const events = await submitTransactionAsync(sender, tx);747    const result = getGenericResult(events);748749    expect(result.success).to.be.true;750  });751}752753export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {754  let allowlisted = false;755  await usingApi(async (api) => {756    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;757  });758  return allowlisted;759}760761export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {762  await usingApi(async (api) => {763    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());764    const events = await submitTransactionAsync(sender, tx);765    const result = getGenericResult(events);766767    expect(result.success).to.be.true;768  });769}770771export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772  await usingApi(async (api) => {773    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());774    const events = await submitTransactionAsync(sender, tx);775    const result = getGenericResult(events);776777    expect(result.success).to.be.true;778  });779}780781export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;785    const result = getGenericResult(events);786787    expect(result.success).to.be.false;788  });789}790791export interface CreateFungibleData {792  readonly Value: bigint;793}794795export interface CreateReFungibleData { }796export interface CreateNftData { }797798export type CreateItemData = {799  NFT: CreateNftData;800} | {801  Fungible: CreateFungibleData;802} | {803  ReFungible: CreateReFungibleData;804};805806export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {807  await usingApi(async (api) => {808    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);809    // if burning token by admin - use adminButnItemExpectSuccess810    expect(balanceBefore >= BigInt(value)).to.be.true;811812    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);813    const events = await submitTransactionAsync(sender, tx);814    const result = getGenericResult(events);815    expect(result.success).to.be.true;816817    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);818    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);819  });820}821822export async function823approveExpectSuccess(824  collectionId: number,825  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,826) {827  await usingApi(async (api: ApiPromise) => {828    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);829    const events = await submitTransactionAsync(owner, approveUniqueTx);830    const result = getGenericResult(events);831    expect(result.success).to.be.true;832833    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));834  });835}836837export async function adminApproveFromExpectSuccess(838  collectionId: number,839  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,840) {841  await usingApi(async (api: ApiPromise) => {842    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);843    const events = await submitTransactionAsync(admin, approveUniqueTx);844    const result = getGenericResult(events);845    expect(result.success).to.be.true;846847    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));848  });849}850851export async function852transferFromExpectSuccess(853  collectionId: number,854  tokenId: number,855  accountApproved: IKeyringPair,856  accountFrom: IKeyringPair | CrossAccountId,857  accountTo: IKeyringPair | CrossAccountId,858  value: number | bigint = 1,859  type = 'NFT',860) {861  await usingApi(async (api: ApiPromise) => {862    const from = normalizeAccountId(accountFrom);863    const to = normalizeAccountId(accountTo);864    let balanceBefore = 0n;865    if (type === 'Fungible' || type === 'ReFungible') {866      balanceBefore = await getBalance(api, collectionId, to, tokenId);867    }868    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);869    const events = await submitTransactionAsync(accountApproved, transferFromTx);870    const result = getCreateItemResult(events);871    // tslint:disable-next-line:no-unused-expression872    expect(result.success).to.be.true;873    if (type === 'NFT') {874      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);875    }876    if (type === 'Fungible') {877      const balanceAfter = await getBalance(api, collectionId, to, tokenId);878      if (JSON.stringify(to) !== JSON.stringify(from)) {879        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));880      } else {881        expect(balanceAfter).to.be.equal(balanceBefore);882      }883    }884    if (type === 'ReFungible') {885      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));886    }887  });888}889890export async function891transferFromExpectFail(892  collectionId: number,893  tokenId: number,894  accountApproved: IKeyringPair,895  accountFrom: IKeyringPair,896  accountTo: IKeyringPair,897  value: number | bigint = 1,898) {899  await usingApi(async (api: ApiPromise) => {900    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);901    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;902    const result = getCreateCollectionResult(events);903    // tslint:disable-next-line:no-unused-expression904    expect(result.success).to.be.false;905  });906}907908/* eslint no-async-promise-executor: "off" */909export async function getBlockNumber(api: ApiPromise): Promise<number> {910  return new Promise<number>(async (resolve) => {911    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {912      unsubscribe();913      resolve(head.number.toNumber());914    });915  });916}917918export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {919  await usingApi(async (api) => {920    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));921    const events = await submitTransactionAsync(sender, changeAdminTx);922    const result = getCreateCollectionResult(events);923    expect(result.success).to.be.true;924  });925}926927export async function928getFreeBalance(account: IKeyringPair): Promise<bigint> {929  let balance = 0n;930  await usingApi(async (api) => {931    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());932  });933934  return balance;935}936937export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {938  const tx = api.tx.balances.transfer(target, amount);939  const events = await submitTransactionAsync(source, tx);940  const result = getGenericResult(events);941  expect(result.success).to.be.true;942}943944export async function945scheduleExpectSuccess(946  operationTx: any,947  sender: IKeyringPair,948  blockSchedule: number,949  scheduledId: string,950  period = 1,951  repetitions = 1,952) {953  await usingApi(async (api: ApiPromise) => {954    const blockNumber: number | undefined = await getBlockNumber(api);955    const expectedBlockNumber = blockNumber + blockSchedule;956957    expect(blockNumber).to.be.greaterThan(0);958    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule959      scheduledId,960      expectedBlockNumber, 961      repetitions > 1 ? [period, repetitions] : null, 962      0, 963      {value: operationTx as any},964    );965966    const events = await submitTransactionAsync(sender, scheduleTx);967    expect(getGenericResult(events).success).to.be.true;968  });969}970971export async function972scheduleExpectFailure(973  operationTx: any,974  sender: IKeyringPair,975  blockSchedule: number,976  scheduledId: string,977  period = 1,978  repetitions = 1,979) {980  await usingApi(async (api: ApiPromise) => {981    const blockNumber: number | undefined = await getBlockNumber(api);982    const expectedBlockNumber = blockNumber + blockSchedule;983984    expect(blockNumber).to.be.greaterThan(0);985    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule986      scheduledId,987      expectedBlockNumber, 988      repetitions <= 1 ? null : [period, repetitions], 989      0, 990      {value: operationTx as any},991    );992993    //const events = 994    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;995    //expect(getGenericResult(events).success).to.be.false;996  });997}998999export async function1000scheduleTransferAndWaitExpectSuccess(1001  collectionId: number,1002  tokenId: number,1003  sender: IKeyringPair,1004  recipient: IKeyringPair,1005  value: number | bigint = 1,1006  blockSchedule: number,1007  scheduledId: string,1008) {1009  await usingApi(async (api: ApiPromise) => {1010    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10111012    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10131014    // sleep for n + 1 blocks1015    await waitNewBlocks(blockSchedule + 1);10161017    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10181019    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1020    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1021  });1022}10231024export async function1025scheduleTransferExpectSuccess(1026  collectionId: number,1027  tokenId: number,1028  sender: IKeyringPair,1029  recipient: IKeyringPair,1030  value: number | bigint = 1,1031  blockSchedule: number,1032  scheduledId: string,1033) {1034  await usingApi(async (api: ApiPromise) => {1035    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10361037    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10381039    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1040  });1041}10421043export async function1044scheduleTransferFundsPeriodicExpectSuccess(1045  amount: bigint,1046  sender: IKeyringPair,1047  recipient: IKeyringPair,1048  blockSchedule: number,1049  scheduledId: string,1050  period: number,1051  repetitions: number,1052) {1053  await usingApi(async (api: ApiPromise) => {1054    const transferTx = api.tx.balances.transfer(recipient.address, amount);10551056    const balanceBefore = await getFreeBalance(recipient);1057    1058    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10591060    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1061  });1062}10631064export async function1065transferExpectSuccess(1066  collectionId: number,1067  tokenId: number,1068  sender: IKeyringPair,1069  recipient: IKeyringPair | CrossAccountId,1070  value: number | bigint = 1,1071  type = 'NFT',1072) {1073  await usingApi(async (api: ApiPromise) => {1074    const from = normalizeAccountId(sender);1075    const to = normalizeAccountId(recipient);10761077    let balanceBefore = 0n;1078    if (type === 'Fungible') {1079      balanceBefore = await getBalance(api, collectionId, to, tokenId);1080    }1081    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1082    const events = await executeTransaction(api, sender, transferTx);10831084    const result = getTransferResult(api, events);1085    expect(result.collectionId).to.be.equal(collectionId);1086    expect(result.itemId).to.be.equal(tokenId);1087    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1088    expect(result.recipient).to.be.deep.equal(to);1089    expect(result.value).to.be.equal(BigInt(value));10901091    if (type === 'NFT') {1092      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1093    }1094    if (type === 'Fungible') {1095      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1096      if (JSON.stringify(to) !== JSON.stringify(from)) {1097        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1098      } else {1099        expect(balanceAfter).to.be.equal(balanceBefore);1100      }1101    }1102    if (type === 'ReFungible') {1103      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1104    }1105  });1106}11071108export async function1109transferExpectFailure(1110  collectionId: number,1111  tokenId: number,1112  sender: IKeyringPair,1113  recipient: IKeyringPair | CrossAccountId,1114  value: number | bigint = 1,1115) {1116  await usingApi(async (api: ApiPromise) => {1117    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1118    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1119    const result = getGenericResult(events);1120    // if (events && Array.isArray(events)) {1121    //   const result = getCreateCollectionResult(events);1122    // tslint:disable-next-line:no-unused-expression1123    expect(result.success).to.be.false;1124    //}1125  });1126}11271128export async function1129approveExpectFail(1130  collectionId: number,1131  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1132) {1133  await usingApi(async (api: ApiPromise) => {1134    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1135    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function getBalance(1143  api: ApiPromise,1144  collectionId: number,1145  owner: string | CrossAccountId,1146  token: number,1147): Promise<bigint> {1148  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1149}1150export async function getTokenOwner(1151  api: ApiPromise,1152  collectionId: number,1153  token: number,1154): Promise<CrossAccountId> {1155  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1156  if (owner == null) throw new Error('owner == null');1157  return normalizeAccountId(owner);1158}1159export async function getTopmostTokenOwner(1160  api: ApiPromise,1161  collectionId: number,1162  token: number,1163): Promise<CrossAccountId> {1164  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1165  if (owner == null) throw new Error('owner == null');1166  return normalizeAccountId(owner);1167}1168export async function isTokenExists(1169  api: ApiPromise,1170  collectionId: number,1171  token: number,1172): Promise<boolean> {1173  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1174}1175export async function getLastTokenId(1176  api: ApiPromise,1177  collectionId: number,1178): Promise<number> {1179  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1180}1181export async function getAdminList(1182  api: ApiPromise,1183  collectionId: number,1184): Promise<string[]> {1185  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1186}1187export async function getTokenProperties(1188  api: ApiPromise,1189  collectionId: number,1190  tokenId: number,1191  propertyKeys: string[],1192): Promise<UpDataStructsProperty[]> {1193  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1194}11951196export async function createFungibleItemExpectSuccess(1197  sender: IKeyringPair,1198  collectionId: number,1199  data: CreateFungibleData,1200  owner: CrossAccountId | string = sender.address,1201) {1202  return await usingApi(async (api) => {1203    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12041205    const events = await submitTransactionAsync(sender, tx);1206    const result = getCreateItemResult(events);12071208    expect(result.success).to.be.true;1209    return result.itemId;1210  });1211}12121213export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1214  await usingApi(async (api) => {1215    const to = normalizeAccountId(owner);1216    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12171218    const events = await submitTransactionAsync(sender, tx);1219    const result = getCreateItemsResult(events);12201221    for (const res of result) {1222      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1223    }1224  });1225}12261227export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1228  await usingApi(async (api) => {1229    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12301231    const events = await submitTransactionAsync(sender, tx);1232    const result = getCreateItemsResult(events);12331234    for (const res of result) {1235      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1236    }1237  });1238}12391240export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1241  let newItemId = 0;1242  await usingApi(async (api) => {1243    const to = normalizeAccountId(owner);1244    const itemCountBefore = await getLastTokenId(api, collectionId);1245    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12461247    let tx;1248    if (createMode === 'Fungible') {1249      const createData = {fungible: {value: 10}};1250      tx = api.tx.unique.createItem(collectionId, to, createData as any);1251    } else if (createMode === 'ReFungible') {1252      const createData = {refungible: {pieces: 100}};1253      tx = api.tx.unique.createItem(collectionId, to, createData as any);1254    } else {1255      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1256      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1257    }12581259    const events = await submitTransactionAsync(sender, tx);1260    const result = getCreateItemResult(events);12611262    const itemCountAfter = await getLastTokenId(api, collectionId);1263    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12641265    if (createMode === 'NFT') {1266      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1267    }12681269    // What to expect1270    // tslint:disable-next-line:no-unused-expression1271    expect(result.success).to.be.true;1272    if (createMode === 'Fungible') {1273      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1274    } else {1275      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1276    }1277    expect(collectionId).to.be.equal(result.collectionId);1278    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1279    expect(to).to.be.deep.equal(result.recipient);1280    newItemId = result.itemId;1281  });1282  return newItemId;1283}12841285export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1286  await usingApi(async (api) => {12871288    let tx;1289    if (createMode === 'NFT') {1290      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1291      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1292    } else {1293      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1294    }129512961297    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1298    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1299    const result = getCreateItemResult(events);13001301    expect(result.success).to.be.false;1302  });1303}13041305export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1306  let newItemId = 0;1307  await usingApi(async (api) => {1308    const to = normalizeAccountId(owner);1309    const itemCountBefore = await getLastTokenId(api, collectionId);1310    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13111312    let tx;1313    if (createMode === 'Fungible') {1314      const createData = {fungible: {value: 10}};1315      tx = api.tx.unique.createItem(collectionId, to, createData as any);1316    } else if (createMode === 'ReFungible') {1317      const createData = {refungible: {pieces: 100}};1318      tx = api.tx.unique.createItem(collectionId, to, createData as any);1319    } else {1320      const createData = {nft: {}};1321      tx = api.tx.unique.createItem(collectionId, to, createData as any);1322    }13231324    const events = await submitTransactionAsync(sender, tx);1325    const result = getCreateItemResult(events);13261327    const itemCountAfter = await getLastTokenId(api, collectionId);1328    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13291330    // What to expect1331    // tslint:disable-next-line:no-unused-expression1332    expect(result.success).to.be.true;1333    if (createMode === 'Fungible') {1334      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1335    } else {1336      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1337    }1338    expect(collectionId).to.be.equal(result.collectionId);1339    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1340    expect(to).to.be.deep.equal(result.recipient);1341    newItemId = result.itemId;1342  });1343  return newItemId;1344}13451346export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1347  await usingApi(async (api) => {1348    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13491350    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1351    const result = getCreateItemResult(events);13521353    expect(result.success).to.be.false;1354  });1355}13561357export async function setPublicAccessModeExpectSuccess(1358  sender: IKeyringPair, collectionId: number,1359  accessMode: 'Normal' | 'AllowList',1360) {1361  await usingApi(async (api) => {13621363    // Run the transaction1364    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1365    const events = await submitTransactionAsync(sender, tx);1366    const result = getGenericResult(events);13671368    // Get the collection1369    const collection = await queryCollectionExpectSuccess(api, collectionId);13701371    // What to expect1372    // tslint:disable-next-line:no-unused-expression1373    expect(result.success).to.be.true;1374    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1375  });1376}13771378export async function setPublicAccessModeExpectFail(1379  sender: IKeyringPair, collectionId: number,1380  accessMode: 'Normal' | 'AllowList',1381) {1382  await usingApi(async (api) => {13831384    // Run the transaction1385    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1386    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1387    const result = getGenericResult(events);13881389    // What to expect1390    // tslint:disable-next-line:no-unused-expression1391    expect(result.success).to.be.false;1392  });1393}13941395export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1396  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1397}13981399export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1400  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1401}14021403export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1404  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1405}14061407export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1408  await usingApi(async (api) => {14091410    // Run the transaction1411    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1412    const events = await submitTransactionAsync(sender, tx);1413    const result = getGenericResult(events);1414    expect(result.success).to.be.true;14151416    // Get the collection1417    const collection = await queryCollectionExpectSuccess(api, collectionId);14181419    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1420  });1421}14221423export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1424  await setMintPermissionExpectSuccess(sender, collectionId, true);1425}14261427export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1428  await usingApi(async (api) => {1429    // Run the transaction1430    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1431    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1432    const result = getCreateCollectionResult(events);1433    // tslint:disable-next-line:no-unused-expression1434    expect(result.success).to.be.false;1435  });1436}14371438export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1439  await usingApi(async (api) => {1440    // Run the transaction1441    const tx = api.tx.unique.setChainLimits(limits);1442    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1443    const result = getCreateCollectionResult(events);1444    // tslint:disable-next-line:no-unused-expression1445    expect(result.success).to.be.false;1446  });1447}14481449export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1450  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1451}14521453export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1454  await usingApi(async (api) => {1455    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14561457    // Run the transaction1458    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1459    const events = await submitTransactionAsync(sender, tx);1460    const result = getGenericResult(events);1461    expect(result.success).to.be.true;14621463    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1464  });1465}14661467export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1468  await usingApi(async (api) => {14691470    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14711472    // Run the transaction1473    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1474    const events = await submitTransactionAsync(sender, tx);1475    const result = getGenericResult(events);1476    expect(result.success).to.be.true;14771478    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1479  });1480}14811482export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1483  await usingApi(async (api) => {14841485    // Run the transaction1486    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1487    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1488    const result = getGenericResult(events);14891490    // What to expect1491    // tslint:disable-next-line:no-unused-expression1492    expect(result.success).to.be.false;1493  });1494}14951496export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1497  await usingApi(async (api) => {1498    // Run the transaction1499    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1500    const events = await submitTransactionAsync(sender, tx);1501    const result = getGenericResult(events);15021503    // What to expect1504    // tslint:disable-next-line:no-unused-expression1505    expect(result.success).to.be.true;1506  });1507}15081509export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1510  await usingApi(async (api) => {1511    // Run the transaction1512    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1513    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1514    const result = getGenericResult(events);15151516    // What to expect1517    // tslint:disable-next-line:no-unused-expression1518    expect(result.success).to.be.false;1519  });1520}15211522export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1523  : Promise<UpDataStructsRpcCollection | null> => {1524  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1525};15261527export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1528  // set global object - collectionsCount1529  return (await api.rpc.unique.collectionStats()).created.toNumber();1530};15311532export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1533  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1534}15351536export async function waitNewBlocks(blocksCount = 1): Promise<void> {1537  await usingApi(async (api) => {1538    const promise = new Promise<void>(async (resolve) => {1539      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1540        if (blocksCount > 0) {1541          blocksCount--;1542        } else {1543          unsubscribe();1544          resolve();1545        }1546      });1547    });1548    return promise;1549  });1550}
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';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}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147  let checkMsgUnqMethod = '';148  let checkMsgTrsMethod = '';149  let checkMsgSysMethod = '';150  events.forEach(({event: {method, section}}) => {151    if (section === 'common') {152      checkMsgUnqMethod = method;153    } else if (section === 'treasury') {154      checkMsgTrsMethod = method;155    } else if (section === 'system') {156      checkMsgSysMethod = method;157    } else { return null; }158  });159  const result: IGetMessage = {160    checkMsgUnqMethod,161    checkMsgTrsMethod,162    checkMsgSysMethod,163  };164  return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168  const event = events.find(r => check(r.event));169  if (!event) return;170  return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174  const result: GenericResult = {175    success: false,176  };177  events.forEach(({event: {method}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method === 'ExtrinsicSuccess') {180      result.success = true;181    }182  });183  return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189  let success = false;190  let collectionId = 0;191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method == 'ExtrinsicSuccess') {194      success = true;195    } else if ((section == 'common') && (method == 'CollectionCreated')) {196      collectionId = parseInt(data[0].toString(), 10);197    }198  });199  const result: CreateCollectionResult = {200    success,201    collectionId,202  };203  return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207  let success = false;208  let collectionId = 0;209  let itemId = 0;210  let recipient;211212  const results : CreateItemResult[]  = [];213214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222223      const itemRes: CreateItemResult = {224        success,225        collectionId,226        itemId,227        recipient,228      };229230      results.push(itemRes);231    }232  });233234  return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238  let success = false;239  let collectionId = 0;240  let itemId = 0;241  let recipient;242  events.forEach(({event: {data, method, section}}) => {243    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);244    if (method == 'ExtrinsicSuccess') {245      success = true;246    } else if ((section == 'common') && (method == 'ItemCreated')) {247      collectionId = parseInt(data[0].toString(), 10);248      itemId = parseInt(data[1].toString(), 10);249      recipient = normalizeAccountId(data[2].toJSON() as any);250    }251  });252  const result: CreateItemResult = {253    success,254    collectionId,255    itemId,256    recipient,257  };258  return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262  for (const {event} of events) {263    if (api.events.common.Transfer.is(event)) {264      const [collection, token, sender, recipient, value] = event.data;265      return {266        collectionId: collection.toNumber(),267        itemId: token.toNumber(),268        sender: normalizeAccountId(sender.toJSON() as any),269        recipient: normalizeAccountId(recipient.toJSON() as any),270        value: value.toBigInt(),271      };272    }273  }274  throw new Error('no transfer event');275}276277interface Nft {278  type: 'NFT';279}280281interface Fungible {282  type: 'Fungible';283  decimalPoints: number;284}285286interface ReFungible {287  type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293  key: any,294  value: any,295};296297type Permission = {298  mutable: boolean;299  collectionAdmin: boolean;300  tokenOwner: boolean;301}302303type PropertyPermission = {304  key: any;305  permission: Permission;306}307308export type CreateCollectionParams = {309  mode: CollectionMode,310  name: string,311  description: string,312  tokenPrefix: 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};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api, privateKeyWrapper) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKeyWrapper('//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    });350    const events = await submitTransactionAsync(alicePrivateKey, tx);351    const result = getCreateCollectionResult(events);352353    // Get number of collections after the transaction354    const collectionCountAfter = await getCreatedCollectionCount(api);355356    // Get the collection357    const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359    // What to expect360    // tslint:disable-next-line:no-unused-expression361    expect(result.success).to.be.true;362    expect(result.collectionId).to.be.equal(collectionCountAfter);363    // tslint:disable-next-line:no-unused-expression364    expect(collection).to.be.not.null;365    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371    collectionId = result.collectionId;372  });373374  return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380  let collectionId = 0;381  await usingApi(async (api, privateKeyWrapper) => {382    // Get number of collections before the transaction383    const collectionCountBefore = await getCreatedCollectionCount(api);384385    // Run the CreateCollection transaction386    const alicePrivateKey = privateKeyWrapper('//Alice');387388    let modeprm = {};389    if (mode.type === 'NFT') {390      modeprm = {nft: null};391    } else if (mode.type === 'Fungible') {392      modeprm = {fungible: mode.decimalPoints};393    } else if (mode.type === 'ReFungible') {394      modeprm = {refungible: null};395    }396397    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getCreateCollectionResult(events);400401    // Get number of collections after the transaction402    const collectionCountAfter = await getCreatedCollectionCount(api);403404    // Get the collection405    const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407    // What to expect408    // tslint:disable-next-line:no-unused-expression409    expect(result.success).to.be.true;410    expect(result.collectionId).to.be.equal(collectionCountAfter);411    // tslint:disable-next-line:no-unused-expression412    expect(collection).to.be.not.null;413    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420    collectionId = result.collectionId;421  });422423  return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429  await usingApi(async (api, privateKeyWrapper) => {430    // Get number of collections before the transaction431    const collectionCountBefore = await getCreatedCollectionCount(api);432433    // Run the CreateCollection transaction434    const alicePrivateKey = privateKeyWrapper('//Alice');435436    let modeprm = {};437    if (mode.type === 'NFT') {438      modeprm = {nft: null};439    } else if (mode.type === 'Fungible') {440      modeprm = {fungible: mode.decimalPoints};441    } else if (mode.type === 'ReFungible') {442      modeprm = {refungible: null};443    }444445    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});446    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449    // Get number of collections after the transaction450    const collectionCountAfter = await getCreatedCollectionCount(api);451452    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453  });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459  let modeprm = {};460  if (mode.type === 'NFT') {461    modeprm = {nft: null};462  } else if (mode.type === 'Fungible') {463    modeprm = {fungible: mode.decimalPoints};464  } else if (mode.type === 'ReFungible') {465    modeprm = {refungible: null};466  }467468  await usingApi(async (api, privateKeyWrapper) => {469    // Get number of collections before the transaction470    const collectionCountBefore = await getCreatedCollectionCount(api);471472    // Run the CreateCollection transaction473    const alicePrivateKey = privateKeyWrapper('//Alice');474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477    // Get number of collections after the transaction478    const collectionCountAfter = await getCreatedCollectionCount(api);479480    // What to expect481    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482  });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486  let bal = 0n;487  let unused;488  do {489    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490    const keyring = new Keyring({type: 'sr25519'});491    unused = keyring.addFromUri(`//${randomSeed}`);492    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493  } while (bal !== 0n);494  return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506  const totalNumber = await getCreatedCollectionCount(api);507  const newCollection: number = totalNumber + 1;508  return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512  let success = false;513  events.forEach(({event: {method}}) => {514    if (method == 'ExtrinsicSuccess') {515      success = true;516    }517  });518  return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api, privateKeyWrapper) => {523    // Run the DestroyCollection transaction524    const alicePrivateKey = privateKeyWrapper(senderSeed);525    const tx = api.tx.unique.destroyCollection(collectionId);526    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527  });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531  await usingApi(async (api, privateKeyWrapper) => {532    // Run the DestroyCollection transaction533    const alicePrivateKey = privateKeyWrapper(senderSeed);534    const tx = api.tx.unique.destroyCollection(collectionId);535    const events = await submitTransactionAsync(alicePrivateKey, tx);536    const result = getDestroyResult(events);537    expect(result).to.be.true;538539    // What to expect540    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541  });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545  await usingApi(async (api) => {546    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547    const events = await submitTransactionAsync(sender, tx);548    const result = getGenericResult(events);549550    expect(result.success).to.be.true;551  });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555  await usingApi(async(api) => {556    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557    const events = await submitTransactionAsync(sender, tx);558    const result = getGenericResult(events);559560    expect(result.success).to.be.true;561  });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565  await usingApi(async (api) => {566    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568    const result = getGenericResult(events);569570    expect(result.success).to.be.false;571  });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575  await usingApi(async (api, privateKeyWrapper) => {576577    // Run the transaction578    const senderPrivateKey = privateKeyWrapper(sender);579    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580    const events = await submitTransactionAsync(senderPrivateKey, tx);581    const result = getGenericResult(events);582583    // Get the collection584    const collection = await queryCollectionExpectSuccess(api, collectionId);585586    // What to expect587    expect(result.success).to.be.true;588    expect(collection.sponsorship.toJSON()).to.deep.equal({589      unconfirmed: sponsor,590    });591  });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595  await usingApi(async (api, privateKeyWrapper) => {596597    // Run the transaction598    const alicePrivateKey = privateKeyWrapper(sender);599    const tx = api.tx.unique.removeCollectionSponsor(collectionId);600    const events = await submitTransactionAsync(alicePrivateKey, tx);601    const result = getGenericResult(events);602603    // Get the collection604    const collection = await queryCollectionExpectSuccess(api, collectionId);605606    // What to expect607    expect(result.success).to.be.true;608    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609  });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613  await usingApi(async (api, privateKeyWrapper) => {614615    // Run the transaction616    const alicePrivateKey = privateKeyWrapper(senderSeed);617    const tx = api.tx.unique.removeCollectionSponsor(collectionId);618    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619  });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623  await usingApi(async (api, privateKeyWrapper) => {624625    // Run the transaction626    const alicePrivateKey = privateKeyWrapper(senderSeed);627    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629  });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async (api, privateKeyWrapper) => {634635    // Run the transaction636    const sender = privateKeyWrapper(senderSeed);637    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);638  });639}640641export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {642  await usingApi(async (api, privateKeyWrapper) => {643644    // Run the transaction645    const tx = api.tx.unique.confirmSponsorship(collectionId);646    const events = await submitTransactionAsync(sender, tx);647    const result = getGenericResult(events);648649    // Get the collection650    const collection = await queryCollectionExpectSuccess(api, collectionId);651652    // What to expect653    expect(result.success).to.be.true;654    expect(collection.sponsorship.toJSON()).to.be.deep.equal({655      confirmed: sender.address,656    });657  });658}659660661export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {662  await usingApi(async (api, privateKeyWrapper) => {663664    // Run the transaction665    const sender = privateKeyWrapper(senderSeed);666    const tx = api.tx.unique.confirmSponsorship(collectionId);667    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668  });669}670671export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {672  await usingApi(async (api) => {673    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);674    const events = await submitTransactionAsync(sender, tx);675    const result = getGenericResult(events);676677    expect(result.success).to.be.true;678  });679}680681export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {682  await usingApi(async (api) => {683    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);684    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;685    const result = getGenericResult(events);686687    expect(result.success).to.be.false;688  });689}690691export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {692693  await usingApi(async (api) => {694695    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);696    const events = await submitTransactionAsync(sender, tx);697    const result = getGenericResult(events);698699    expect(result.success).to.be.true;700  });701}702703export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {704705  await usingApi(async (api) => {706707    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);708    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;709    const result = getGenericResult(events);710711    expect(result.success).to.be.false;712  });713}714715export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {716  await usingApi(async (api) => {717    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);718    const events = await submitTransactionAsync(sender, tx);719    const result = getGenericResult(events);720721    expect(result.success).to.be.true;722  });723}724725export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {726  await usingApi(async (api) => {727    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);728    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;729    const result = getGenericResult(events);730731    expect(result.success).to.be.false;732  });733}734735export async function getNextSponsored(736  api: ApiPromise,737  collectionId: number,738  account: string | CrossAccountId,739  tokenId: number,740): Promise<number> {741  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));742}743744export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {745  await usingApi(async (api) => {746    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);747    const events = await submitTransactionAsync(sender, tx);748    const result = getGenericResult(events);749750    expect(result.success).to.be.true;751  });752}753754export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {755  let allowlisted = false;756  await usingApi(async (api) => {757    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;758  });759  return allowlisted;760}761762export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {763  await usingApi(async (api) => {764    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());765    const events = await submitTransactionAsync(sender, tx);766    const result = getGenericResult(events);767768    expect(result.success).to.be.true;769  });770}771772export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {773  await usingApi(async (api) => {774    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());775    const events = await submitTransactionAsync(sender, tx);776    const result = getGenericResult(events);777778    expect(result.success).to.be.true;779  });780}781782export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {783  await usingApi(async (api) => {784    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());785    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;786    const result = getGenericResult(events);787788    expect(result.success).to.be.false;789  });790}791792export interface CreateFungibleData {793  readonly Value: bigint;794}795796export interface CreateReFungibleData { }797export interface CreateNftData { }798799export type CreateItemData = {800  NFT: CreateNftData;801} | {802  Fungible: CreateFungibleData;803} | {804  ReFungible: CreateReFungibleData;805};806807export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {808  await usingApi(async (api) => {809    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);810    // if burning token by admin - use adminButnItemExpectSuccess811    expect(balanceBefore >= BigInt(value)).to.be.true;812813    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);814    const events = await submitTransactionAsync(sender, tx);815    const result = getGenericResult(events);816    expect(result.success).to.be.true;817818    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);819    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);820  });821}822823export async function824approveExpectSuccess(825  collectionId: number,826  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,827) {828  await usingApi(async (api: ApiPromise) => {829    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);830    const events = await submitTransactionAsync(owner, approveUniqueTx);831    const result = getGenericResult(events);832    expect(result.success).to.be.true;833834    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));835  });836}837838export async function adminApproveFromExpectSuccess(839  collectionId: number,840  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,841) {842  await usingApi(async (api: ApiPromise) => {843    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);844    const events = await submitTransactionAsync(admin, approveUniqueTx);845    const result = getGenericResult(events);846    expect(result.success).to.be.true;847848    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));849  });850}851852export async function853transferFromExpectSuccess(854  collectionId: number,855  tokenId: number,856  accountApproved: IKeyringPair,857  accountFrom: IKeyringPair | CrossAccountId,858  accountTo: IKeyringPair | CrossAccountId,859  value: number | bigint = 1,860  type = 'NFT',861) {862  await usingApi(async (api: ApiPromise) => {863    const from = normalizeAccountId(accountFrom);864    const to = normalizeAccountId(accountTo);865    let balanceBefore = 0n;866    if (type === 'Fungible' || type === 'ReFungible') {867      balanceBefore = await getBalance(api, collectionId, to, tokenId);868    }869    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);870    const events = await submitTransactionAsync(accountApproved, transferFromTx);871    const result = getCreateItemResult(events);872    // tslint:disable-next-line:no-unused-expression873    expect(result.success).to.be.true;874    if (type === 'NFT') {875      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);876    }877    if (type === 'Fungible') {878      const balanceAfter = await getBalance(api, collectionId, to, tokenId);879      if (JSON.stringify(to) !== JSON.stringify(from)) {880        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));881      } else {882        expect(balanceAfter).to.be.equal(balanceBefore);883      }884    }885    if (type === 'ReFungible') {886      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));887    }888  });889}890891export async function892transferFromExpectFail(893  collectionId: number,894  tokenId: number,895  accountApproved: IKeyringPair,896  accountFrom: IKeyringPair,897  accountTo: IKeyringPair,898  value: number | bigint = 1,899) {900  await usingApi(async (api: ApiPromise) => {901    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);902    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;903    const result = getCreateCollectionResult(events);904    // tslint:disable-next-line:no-unused-expression905    expect(result.success).to.be.false;906  });907}908909/* eslint no-async-promise-executor: "off" */910export async function getBlockNumber(api: ApiPromise): Promise<number> {911  return new Promise<number>(async (resolve) => {912    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {913      unsubscribe();914      resolve(head.number.toNumber());915    });916  });917}918919export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {920  await usingApi(async (api) => {921    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));922    const events = await submitTransactionAsync(sender, changeAdminTx);923    const result = getCreateCollectionResult(events);924    expect(result.success).to.be.true;925  });926}927928export async function929getFreeBalance(account: IKeyringPair): Promise<bigint> {930  let balance = 0n;931  await usingApi(async (api) => {932    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());933  });934935  return balance;936}937938export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {939  const tx = api.tx.balances.transfer(target, amount);940  const events = await submitTransactionAsync(source, tx);941  const result = getGenericResult(events);942  expect(result.success).to.be.true;943}944945export async function946scheduleExpectSuccess(947  operationTx: any,948  sender: IKeyringPair,949  blockSchedule: number,950  scheduledId: string,951  period = 1,952  repetitions = 1,953) {954  await usingApi(async (api: ApiPromise) => {955    const blockNumber: number | undefined = await getBlockNumber(api);956    const expectedBlockNumber = blockNumber + blockSchedule;957958    expect(blockNumber).to.be.greaterThan(0);959    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule960      scheduledId,961      expectedBlockNumber, 962      repetitions > 1 ? [period, repetitions] : null, 963      0, 964      {value: operationTx as any},965    );966967    const events = await submitTransactionAsync(sender, scheduleTx);968    expect(getGenericResult(events).success).to.be.true;969  });970}971972export async function973scheduleExpectFailure(974  operationTx: any,975  sender: IKeyringPair,976  blockSchedule: number,977  scheduledId: string,978  period = 1,979  repetitions = 1,980) {981  await usingApi(async (api: ApiPromise) => {982    const blockNumber: number | undefined = await getBlockNumber(api);983    const expectedBlockNumber = blockNumber + blockSchedule;984985    expect(blockNumber).to.be.greaterThan(0);986    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule987      scheduledId,988      expectedBlockNumber, 989      repetitions <= 1 ? null : [period, repetitions], 990      0, 991      {value: operationTx as any},992    );993994    //const events = 995    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;996    //expect(getGenericResult(events).success).to.be.false;997  });998}9991000export async function1001scheduleTransferAndWaitExpectSuccess(1002  collectionId: number,1003  tokenId: number,1004  sender: IKeyringPair,1005  recipient: IKeyringPair,1006  value: number | bigint = 1,1007  blockSchedule: number,1008  scheduledId: string,1009) {1010  await usingApi(async (api: ApiPromise) => {1011    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10121013    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10141015    // sleep for n + 1 blocks1016    await waitNewBlocks(blockSchedule + 1);10171018    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10191020    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1021    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1022  });1023}10241025export async function1026scheduleTransferExpectSuccess(1027  collectionId: number,1028  tokenId: number,1029  sender: IKeyringPair,1030  recipient: IKeyringPair,1031  value: number | bigint = 1,1032  blockSchedule: number,1033  scheduledId: string,1034) {1035  await usingApi(async (api: ApiPromise) => {1036    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10371038    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10391040    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1041  });1042}10431044export async function1045scheduleTransferFundsPeriodicExpectSuccess(1046  amount: bigint,1047  sender: IKeyringPair,1048  recipient: IKeyringPair,1049  blockSchedule: number,1050  scheduledId: string,1051  period: number,1052  repetitions: number,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferTx = api.tx.balances.transfer(recipient.address, amount);10561057    const balanceBefore = await getFreeBalance(recipient);1058    1059    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10601061    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1062  });1063}10641065export async function1066transferExpectSuccess(1067  collectionId: number,1068  tokenId: number,1069  sender: IKeyringPair,1070  recipient: IKeyringPair | CrossAccountId,1071  value: number | bigint = 1,1072  type = 'NFT',1073) {1074  await usingApi(async (api: ApiPromise) => {1075    const from = normalizeAccountId(sender);1076    const to = normalizeAccountId(recipient);10771078    let balanceBefore = 0n;1079    if (type === 'Fungible') {1080      balanceBefore = await getBalance(api, collectionId, to, tokenId);1081    }1082    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1083    const events = await executeTransaction(api, sender, transferTx);10841085    const result = getTransferResult(api, events);1086    expect(result.collectionId).to.be.equal(collectionId);1087    expect(result.itemId).to.be.equal(tokenId);1088    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1089    expect(result.recipient).to.be.deep.equal(to);1090    expect(result.value).to.be.equal(BigInt(value));10911092    if (type === 'NFT') {1093      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1094    }1095    if (type === 'Fungible') {1096      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1097      if (JSON.stringify(to) !== JSON.stringify(from)) {1098        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1099      } else {1100        expect(balanceAfter).to.be.equal(balanceBefore);1101      }1102    }1103    if (type === 'ReFungible') {1104      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1105    }1106  });1107}11081109export async function1110transferExpectFailure(1111  collectionId: number,1112  tokenId: number,1113  sender: IKeyringPair,1114  recipient: IKeyringPair | CrossAccountId,1115  value: number | bigint = 1,1116) {1117  await usingApi(async (api: ApiPromise) => {1118    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1119    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1120    const result = getGenericResult(events);1121    // if (events && Array.isArray(events)) {1122    //   const result = getCreateCollectionResult(events);1123    // tslint:disable-next-line:no-unused-expression1124    expect(result.success).to.be.false;1125    //}1126  });1127}11281129export async function1130approveExpectFail(1131  collectionId: number,1132  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1133) {1134  await usingApi(async (api: ApiPromise) => {1135    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1136    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1137    const result = getCreateCollectionResult(events);1138    // tslint:disable-next-line:no-unused-expression1139    expect(result.success).to.be.false;1140  });1141}11421143export async function getBalance(1144  api: ApiPromise,1145  collectionId: number,1146  owner: string | CrossAccountId,1147  token: number,1148): Promise<bigint> {1149  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1150}1151export async function getTokenOwner(1152  api: ApiPromise,1153  collectionId: number,1154  token: number,1155): Promise<CrossAccountId> {1156  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1157  if (owner == null) throw new Error('owner == null');1158  return normalizeAccountId(owner);1159}1160export async function getTopmostTokenOwner(1161  api: ApiPromise,1162  collectionId: number,1163  token: number,1164): Promise<CrossAccountId> {1165  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1166  if (owner == null) throw new Error('owner == null');1167  return normalizeAccountId(owner);1168}1169export async function getTokenChildren(1170  api: ApiPromise,1171  collectionId: number,1172  tokenId: number,1173): Promise<UpDataStructsTokenChild[]> {1174  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1175}1176export async function isTokenExists(1177  api: ApiPromise,1178  collectionId: number,1179  token: number,1180): Promise<boolean> {1181  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1182}1183export async function getLastTokenId(1184  api: ApiPromise,1185  collectionId: number,1186): Promise<number> {1187  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1188}1189export async function getAdminList(1190  api: ApiPromise,1191  collectionId: number,1192): Promise<string[]> {1193  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1194}1195export async function getTokenProperties(1196  api: ApiPromise,1197  collectionId: number,1198  tokenId: number,1199  propertyKeys: string[],1200): Promise<UpDataStructsProperty[]> {1201  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1202}12031204export async function createFungibleItemExpectSuccess(1205  sender: IKeyringPair,1206  collectionId: number,1207  data: CreateFungibleData,1208  owner: CrossAccountId | string = sender.address,1209) {1210  return await usingApi(async (api) => {1211    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12121213    const events = await submitTransactionAsync(sender, tx);1214    const result = getCreateItemResult(events);12151216    expect(result.success).to.be.true;1217    return result.itemId;1218  });1219}12201221export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1222  await usingApi(async (api) => {1223    const to = normalizeAccountId(owner);1224    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12251226    const events = await submitTransactionAsync(sender, tx);1227    const result = getCreateItemsResult(events);12281229    for (const res of result) {1230      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1231    }1232  });1233}12341235export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1236  await usingApi(async (api) => {1237    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12381239    const events = await submitTransactionAsync(sender, tx);1240    const result = getCreateItemsResult(events);12411242    for (const res of result) {1243      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1244    }1245  });1246}12471248export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1249  let newItemId = 0;1250  await usingApi(async (api) => {1251    const to = normalizeAccountId(owner);1252    const itemCountBefore = await getLastTokenId(api, collectionId);1253    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12541255    let tx;1256    if (createMode === 'Fungible') {1257      const createData = {fungible: {value: 10}};1258      tx = api.tx.unique.createItem(collectionId, to, createData as any);1259    } else if (createMode === 'ReFungible') {1260      const createData = {refungible: {pieces: 100}};1261      tx = api.tx.unique.createItem(collectionId, to, createData as any);1262    } else {1263      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1264      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1265    }12661267    const events = await submitTransactionAsync(sender, tx);1268    const result = getCreateItemResult(events);12691270    const itemCountAfter = await getLastTokenId(api, collectionId);1271    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12721273    if (createMode === 'NFT') {1274      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1275    }12761277    // What to expect1278    // tslint:disable-next-line:no-unused-expression1279    expect(result.success).to.be.true;1280    if (createMode === 'Fungible') {1281      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1282    } else {1283      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1284    }1285    expect(collectionId).to.be.equal(result.collectionId);1286    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1287    expect(to).to.be.deep.equal(result.recipient);1288    newItemId = result.itemId;1289  });1290  return newItemId;1291}12921293export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1294  await usingApi(async (api) => {12951296    let tx;1297    if (createMode === 'NFT') {1298      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1299      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1300    } else {1301      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1302    }130313041305    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1306    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1307    const result = getCreateItemResult(events);13081309    expect(result.success).to.be.false;1310  });1311}13121313export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1314  let newItemId = 0;1315  await usingApi(async (api) => {1316    const to = normalizeAccountId(owner);1317    const itemCountBefore = await getLastTokenId(api, collectionId);1318    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13191320    let tx;1321    if (createMode === 'Fungible') {1322      const createData = {fungible: {value: 10}};1323      tx = api.tx.unique.createItem(collectionId, to, createData as any);1324    } else if (createMode === 'ReFungible') {1325      const createData = {refungible: {pieces: 100}};1326      tx = api.tx.unique.createItem(collectionId, to, createData as any);1327    } else {1328      const createData = {nft: {}};1329      tx = api.tx.unique.createItem(collectionId, to, createData as any);1330    }13311332    const events = await submitTransactionAsync(sender, tx);1333    const result = getCreateItemResult(events);13341335    const itemCountAfter = await getLastTokenId(api, collectionId);1336    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13371338    // What to expect1339    // tslint:disable-next-line:no-unused-expression1340    expect(result.success).to.be.true;1341    if (createMode === 'Fungible') {1342      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1343    } else {1344      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1345    }1346    expect(collectionId).to.be.equal(result.collectionId);1347    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1348    expect(to).to.be.deep.equal(result.recipient);1349    newItemId = result.itemId;1350  });1351  return newItemId;1352}13531354export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1355  await usingApi(async (api) => {1356    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13571358    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1359    const result = getCreateItemResult(events);13601361    expect(result.success).to.be.false;1362  });1363}13641365export async function setPublicAccessModeExpectSuccess(1366  sender: IKeyringPair, collectionId: number,1367  accessMode: 'Normal' | 'AllowList',1368) {1369  await usingApi(async (api) => {13701371    // Run the transaction1372    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1373    const events = await submitTransactionAsync(sender, tx);1374    const result = getGenericResult(events);13751376    // Get the collection1377    const collection = await queryCollectionExpectSuccess(api, collectionId);13781379    // What to expect1380    // tslint:disable-next-line:no-unused-expression1381    expect(result.success).to.be.true;1382    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1383  });1384}13851386export async function setPublicAccessModeExpectFail(1387  sender: IKeyringPair, collectionId: number,1388  accessMode: 'Normal' | 'AllowList',1389) {1390  await usingApi(async (api) => {13911392    // Run the transaction1393    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1394    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395    const result = getGenericResult(events);13961397    // What to expect1398    // tslint:disable-next-line:no-unused-expression1399    expect(result.success).to.be.false;1400  });1401}14021403export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1404  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1405}14061407export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1408  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1409}14101411export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1412  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1413}14141415export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1416  await usingApi(async (api) => {14171418    // Run the transaction1419    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1420    const events = await submitTransactionAsync(sender, tx);1421    const result = getGenericResult(events);1422    expect(result.success).to.be.true;14231424    // Get the collection1425    const collection = await queryCollectionExpectSuccess(api, collectionId);14261427    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1428  });1429}14301431export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1432  await setMintPermissionExpectSuccess(sender, collectionId, true);1433}14341435export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1436  await usingApi(async (api) => {1437    // Run the transaction1438    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1439    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1440    const result = getCreateCollectionResult(events);1441    // tslint:disable-next-line:no-unused-expression1442    expect(result.success).to.be.false;1443  });1444}14451446export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1447  await usingApi(async (api) => {1448    // Run the transaction1449    const tx = api.tx.unique.setChainLimits(limits);1450    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1451    const result = getCreateCollectionResult(events);1452    // tslint:disable-next-line:no-unused-expression1453    expect(result.success).to.be.false;1454  });1455}14561457export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1458  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1459}14601461export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1462  await usingApi(async (api) => {1463    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14641465    // Run the transaction1466    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1467    const events = await submitTransactionAsync(sender, tx);1468    const result = getGenericResult(events);1469    expect(result.success).to.be.true;14701471    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1472  });1473}14741475export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1476  await usingApi(async (api) => {14771478    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14791480    // Run the transaction1481    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1482    const events = await submitTransactionAsync(sender, tx);1483    const result = getGenericResult(events);1484    expect(result.success).to.be.true;14851486    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1487  });1488}14891490export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1491  await usingApi(async (api) => {14921493    // Run the transaction1494    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1495    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1496    const result = getGenericResult(events);14971498    // What to expect1499    // tslint:disable-next-line:no-unused-expression1500    expect(result.success).to.be.false;1501  });1502}15031504export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1505  await usingApi(async (api) => {1506    // Run the transaction1507    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1508    const events = await submitTransactionAsync(sender, tx);1509    const result = getGenericResult(events);15101511    // What to expect1512    // tslint:disable-next-line:no-unused-expression1513    expect(result.success).to.be.true;1514  });1515}15161517export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1518  await usingApi(async (api) => {1519    // Run the transaction1520    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1521    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1522    const result = getGenericResult(events);15231524    // What to expect1525    // tslint:disable-next-line:no-unused-expression1526    expect(result.success).to.be.false;1527  });1528}15291530export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1531  : Promise<UpDataStructsRpcCollection | null> => {1532  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1533};15341535export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1536  // set global object - collectionsCount1537  return (await api.rpc.unique.collectionStats()).created.toNumber();1538};15391540export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1541  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1542}15431544export async function waitNewBlocks(blocksCount = 1): Promise<void> {1545  await usingApi(async (api) => {1546    const promise = new Promise<void>(async (resolve) => {1547      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1548        if (blocksCount > 0) {1549          blocksCount--;1550        } else {1551          unsubscribe();1552          resolve();1553        }1554      });1555    });1556    return promise;1557  });1558}