difftreelog
fix disbaled pallets Rmrk, RFT, Scheduler for Quartz RFT, Scheduler for Unique Added the logic of checking the availability of pallets necessary for their execution in tests
in: master
27 files changed
runtime/common/Cargo.tomldiffbeforeafterboth--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -32,6 +32,8 @@
'frame-support/runtime-benchmarks',
'frame-system/runtime-benchmarks',
]
+unique-runtime = ['std']
+quartz-runtime = ['std']
[dependencies.sp-core]
default-features = false
runtime/common/src/dispatch.rsdiffbeforeafterboth--- a/runtime/common/src/dispatch.rs
+++ b/runtime/common/src/dispatch.rs
@@ -64,7 +64,12 @@
);
<PalletFungible<T>>::init_collection(sender, data)?
}
+ #[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,
+
+ CollectionMode::ReFungible => {
+ return Err(DispatchError::Other("Refunginle pallet is not supported"))
+ }
};
Ok(id)
}
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -25,6 +25,7 @@
};
use up_data_structs::{CreateItemExData, CreateItemData};
+#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
macro_rules! max_weight_of {
($method:ident ( $($args:tt)* )) => {
<FungibleWeights<T>>::$method($($args)*)
@@ -33,9 +34,21 @@
};
}
+#[cfg(any(feature = "unique-runtime", feature = "quartz-runtime"))]
+macro_rules! max_weight_of {
+ ($method:ident ( $($args:tt)* )) => {
+ <FungibleWeights<T>>::$method($($args)*)
+ .max(<NonfungibleWeights<T>>::$method($($args)*))
+
+ };
+}
+
+#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
pub struct CommonWeights<T>(PhantomData<T>)
where
T: FungibleConfig + NonfungibleConfig + RefungibleConfig;
+
+#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
impl<T> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T>
where
T: FungibleConfig + NonfungibleConfig + RefungibleConfig,
@@ -101,6 +114,7 @@
}
}
+#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
impl<T> RefungibleExtensionsWeightInfo for CommonWeights<T>
where
T: FungibleConfig + NonfungibleConfig + RefungibleConfig,
@@ -109,3 +123,84 @@
dispatch_weight::<T>() + <<T as RefungibleConfig>::WeightInfo>::repartition_item()
}
}
+
+#[cfg(any(feature = "unique-runtime", feature = "quartz-runtime"))]
+pub struct CommonWeights<T>(PhantomData<T>)
+where
+ T: FungibleConfig + NonfungibleConfig;
+
+#[cfg(any(feature = "unique-runtime", feature = "quartz-runtime"))]
+impl<T> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T>
+where
+ T: FungibleConfig + NonfungibleConfig,
+{
+ fn create_item() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_item())
+ }
+
+ fn create_multiple_items(data: &[CreateItemData]) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_multiple_items(data))
+ }
+
+ fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_multiple_items_ex(data))
+ }
+
+ fn burn_item() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(burn_item())
+ }
+
+ fn set_collection_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(set_collection_properties(amount))
+ }
+
+ fn delete_collection_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(delete_collection_properties(amount))
+ }
+
+ fn set_token_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(set_token_properties(amount))
+ }
+
+ fn delete_token_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(delete_token_properties(amount))
+ }
+
+ fn set_token_property_permissions(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(set_token_property_permissions(amount))
+ }
+
+ fn transfer() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(transfer())
+ }
+
+ fn approve() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(approve())
+ }
+
+ fn transfer_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(transfer_from())
+ }
+
+ fn burn_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(burn_from())
+ }
+
+ fn burn_recursively_self_raw() -> Weight {
+ max_weight_of!(burn_recursively_self_raw())
+ }
+
+ fn burn_recursively_breadth_raw(amount: u32) -> Weight {
+ max_weight_of!(burn_recursively_breadth_raw(amount))
+ }
+}
+
+#[cfg(any(feature = "unique-runtime", feature = "quartz-runtime"))]
+impl<T> RefungibleExtensionsWeightInfo for CommonWeights<T>
+where
+ T: FungibleConfig + NonfungibleConfig,
+{
+ fn repartition() -> Weight {
+ dispatch_weight::<T>()
+ }
+}
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -909,15 +909,15 @@
type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;
}
-impl pallet_proxy_rmrk_core::Config for Runtime {
- type WeightInfo = pallet_proxy_rmrk_core::weights::SubstrateWeight<Self>;
- type Event = Event;
-}
+// impl pallet_proxy_rmrk_core::Config for Runtime {
+// type WeightInfo = pallet_proxy_rmrk_core::weights::SubstrateWeight<Self>;
+// type Event = Event;
+// }
-impl pallet_proxy_rmrk_equip::Config for Runtime {
- type WeightInfo = pallet_proxy_rmrk_equip::weights::SubstrateWeight<Self>;
- type Event = Event;
-}
+// impl pallet_proxy_rmrk_equip::Config for Runtime {
+// type WeightInfo = pallet_proxy_rmrk_equip::weights::SubstrateWeight<Self>;
+// type Event = Event;
+// }
impl pallet_unique::Config for Runtime {
type Event = Event;
@@ -961,92 +961,92 @@
)
}
-pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
- DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
-where
- <T as frame_system::Config>::Call: Member
- + Dispatchable<Origin = Origin, Info = DispatchInfo>
- + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
- + GetDispatchInfo
- + From<frame_system::Call<Runtime>>,
- SelfContainedSignedInfo: Send + Sync + 'static,
- Call: From<<T as frame_system::Config>::Call>
- + From<<T as pallet_unique_scheduler::Config>::Call>
- + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
- sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
-{
- fn dispatch_call(
- signer: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- ) -> Result<
- Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
- TransactionValidityError,
- > {
- let dispatch_info = call.get_dispatch_info();
- let extrinsic = fp_self_contained::CheckedExtrinsic::<
- AccountId,
- Call,
- SignedExtraScheduler,
- SelfContainedSignedInfo,
- > {
- signed:
- CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
- signer.clone().into(),
- get_signed_extras(signer.into()),
- ),
- function: call.into(),
- };
+// pub struct SchedulerPaymentExecutor;
+// impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
+// DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+// where
+// <T as frame_system::Config>::Call: Member
+// + Dispatchable<Origin = Origin, Info = DispatchInfo>
+// + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+// + GetDispatchInfo
+// + From<frame_system::Call<Runtime>>,
+// SelfContainedSignedInfo: Send + Sync + 'static,
+// Call: From<<T as frame_system::Config>::Call>
+// + From<<T as pallet_unique_scheduler::Config>::Call>
+// + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+// sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+// {
+// fn dispatch_call(
+// signer: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// ) -> Result<
+// Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+// TransactionValidityError,
+// > {
+// let dispatch_info = call.get_dispatch_info();
+// let extrinsic = fp_self_contained::CheckedExtrinsic::<
+// AccountId,
+// Call,
+// SignedExtraScheduler,
+// SelfContainedSignedInfo,
+// > {
+// signed:
+// CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+// signer.clone().into(),
+// get_signed_extras(signer.into()),
+// ),
+// function: call.into(),
+// };
- extrinsic.apply::<Runtime>(&dispatch_info, 0)
- }
+// extrinsic.apply::<Runtime>(&dispatch_info, 0)
+// }
- fn reserve_balance(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- count: u32,
- ) -> Result<(), DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
- .saturating_mul(count.into());
+// fn reserve_balance(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// count: u32,
+// ) -> Result<(), DispatchError> {
+// let dispatch_info = call.get_dispatch_info();
+// let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+// .saturating_mul(count.into());
- <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
- &id,
- &(sponsor.into()),
- weight.into(),
- )
- }
+// <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+// &id,
+// &(sponsor.into()),
+// weight.into(),
+// )
+// }
- fn pay_for_call(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- ) -> Result<u128, DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- weight.into(),
- ),
- )
- }
+// fn pay_for_call(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// ) -> Result<u128, DispatchError> {
+// let dispatch_info = call.get_dispatch_info();
+// let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+// Ok(
+// <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+// &id,
+// &(sponsor.into()),
+// weight.into(),
+// ),
+// )
+// }
- fn cancel_reserve(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- ) -> Result<u128, DispatchError> {
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- u128::MAX,
- ),
- )
- }
-}
+// fn cancel_reserve(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// ) -> Result<u128, DispatchError> {
+// Ok(
+// <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+// &id,
+// &(sponsor.into()),
+// u128::MAX,
+// ),
+// )
+// }
+// }
parameter_types! {
pub const NoPreimagePostponement: Option<u32> = Some(10);
@@ -1062,21 +1062,21 @@
}
}
-impl pallet_unique_scheduler::Config for Runtime {
- type Event = Event;
- type Origin = Origin;
- type Currency = Balances;
- type PalletsOrigin = OriginCaller;
- type Call = Call;
- type MaximumWeight = MaximumSchedulerWeight;
- type ScheduleOrigin = EnsureSigned<AccountId>;
- type MaxScheduledPerBlock = MaxScheduledPerBlock;
- type WeightInfo = ();
- type CallExecutor = SchedulerPaymentExecutor;
- type OriginPrivilegeCmp = OriginPrivilegeCmp;
- type PreimageProvider = ();
- type NoPreimagePostponement = NoPreimagePostponement;
-}
+// impl pallet_unique_scheduler::Config for Runtime {
+// type Event = Event;
+// type Origin = Origin;
+// type Currency = Balances;
+// type PalletsOrigin = OriginCaller;
+// type Call = Call;
+// type MaximumWeight = MaximumSchedulerWeight;
+// type ScheduleOrigin = EnsureSigned<AccountId>;
+// type MaxScheduledPerBlock = MaxScheduledPerBlock;
+// type WeightInfo = ();
+// type CallExecutor = SchedulerPaymentExecutor;
+// type OriginPrivilegeCmp = OriginPrivilegeCmp;
+// type PreimageProvider = ();
+// type NoPreimagePostponement = NoPreimagePostponement;
+// }
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
@@ -1150,17 +1150,17 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ // Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
Common: pallet_common::{Pallet, Storage, Event<T>} = 66,
Fungible: pallet_fungible::{Pallet, Storage} = 67,
- Refungible: pallet_refungible::{Pallet, Storage} = 68,
+ // Refungible: pallet_refungible::{Pallet, Storage} = 68,
Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
- RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,
- RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,
+ // RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,
+ // RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,
// Frontier
EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
@@ -1323,57 +1323,112 @@
RmrkPartType,
RmrkTheme
> for Runtime {
+
+ // fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::last_collection_idx::<Runtime>()
+ // }
+
+ // fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::collection_by_id::<Runtime>(collection_id)
+ // }
+
+ // fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::nft_by_id::<Runtime>(collection_id, nft_by_id)
+ // }
+
+ // fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::account_tokens::<Runtime>(account_id, collection_id)
+ // }
+
+ // fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::nft_children::<Runtime>(collection_id, nft_id)
+ // }
+
+ // fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::collection_properties::<Runtime>(collection_id, filter_keys)
+ // }
+
+ // fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::nft_properties::<Runtime>(collection_id, nft_id, filter_keys)
+ // }
+
+ // fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::nft_resources::<Runtime>(collection_id, nft_id)
+ // }
+
+ // fn nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Result<Option<u32>, DispatchError> {
+ // pallet_proxy_rmrk_core::rpc::nft_resource_priority::<Runtime>(collection_id, nft_id, resource_id)
+ // }
+
+ // fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
+ // pallet_proxy_rmrk_equip::rpc::base::<Runtime>(base_id)
+ // }
+
+ // fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
+ // pallet_proxy_rmrk_equip::rpc::base_parts::<Runtime>(base_id)
+ // }
+
+ // fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
+ // pallet_proxy_rmrk_equip::rpc::theme_names::<Runtime>(base_id)
+ // }
+
+ // fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {
+ // pallet_proxy_rmrk_equip::rpc::theme::<Runtime>(base_id, theme_name, filter_keys)
+ // }
+
fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {
- pallet_proxy_rmrk_core::rpc::last_collection_idx::<Runtime>()
+ Ok(Default::default())
}
- fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::collection_by_id::<Runtime>(collection_id)
+ fn collection_by_id(_collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
+ Ok(Default::default())
}
- fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::nft_by_id::<Runtime>(collection_id, nft_by_id)
+ fn nft_by_id(_collection_id: RmrkCollectionId, _nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {
+ Ok(Default::default())
}
- fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::account_tokens::<Runtime>(account_id, collection_id)
+ fn account_tokens(_account_id: AccountId, _collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {
+ Ok(Default::default())
}
- fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::nft_children::<Runtime>(collection_id, nft_id)
+ fn nft_children(_collection_id: RmrkCollectionId, _nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {
+ Ok(Default::default())
}
- fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::collection_properties::<Runtime>(collection_id, filter_keys)
+ fn collection_properties(_collection_id: RmrkCollectionId, _filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
+ Ok(Default::default())
}
- fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::nft_properties::<Runtime>(collection_id, nft_id, filter_keys)
+ fn nft_properties(_collection_id: RmrkCollectionId, _nft_id: RmrkNftId, _filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {
+ Ok(Default::default())
}
- fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::nft_resources::<Runtime>(collection_id, nft_id)
+ fn nft_resources(_collection_id: RmrkCollectionId, _nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {
+ Ok(Default::default())
}
- fn nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Result<Option<u32>, DispatchError> {
- pallet_proxy_rmrk_core::rpc::nft_resource_priority::<Runtime>(collection_id, nft_id, resource_id)
+ fn nft_resource_priority(_collection_id: RmrkCollectionId, _nft_id: RmrkNftId, _resource_id: RmrkResourceId) -> Result<Option<u32>, DispatchError> {
+ Ok(Default::default())
}
- fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
- pallet_proxy_rmrk_equip::rpc::base::<Runtime>(base_id)
+ fn base(_base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
+ Ok(Default::default())
}
- fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
- pallet_proxy_rmrk_equip::rpc::base_parts::<Runtime>(base_id)
+ fn base_parts(_base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
+ Ok(Default::default())
}
- fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
- pallet_proxy_rmrk_equip::rpc::theme_names::<Runtime>(base_id)
+ fn theme_names(_base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
+ Ok(Default::default())
}
- fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {
- pallet_proxy_rmrk_equip::rpc::theme::<Runtime>(base_id, theme_name, filter_keys)
+ fn theme(_base_id: RmrkBaseId, _theme_name: RmrkThemeName, _filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {
+ Ok(Default::default())
}
+
+
}
}
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -901,9 +901,11 @@
impl pallet_fungible::Config for Runtime {
type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;
}
+
impl pallet_refungible::Config for Runtime {
type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;
}
+
impl pallet_nonfungible::Config for Runtime {
type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;
}
@@ -950,92 +952,92 @@
)
}
-pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
- DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
-where
- <T as frame_system::Config>::Call: Member
- + Dispatchable<Origin = Origin, Info = DispatchInfo>
- + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
- + GetDispatchInfo
- + From<frame_system::Call<Runtime>>,
- SelfContainedSignedInfo: Send + Sync + 'static,
- Call: From<<T as frame_system::Config>::Call>
- + From<<T as pallet_unique_scheduler::Config>::Call>
- + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
- sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
-{
- fn dispatch_call(
- signer: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- ) -> Result<
- Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
- TransactionValidityError,
- > {
- let dispatch_info = call.get_dispatch_info();
- let extrinsic = fp_self_contained::CheckedExtrinsic::<
- AccountId,
- Call,
- SignedExtraScheduler,
- SelfContainedSignedInfo,
- > {
- signed:
- CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
- signer.clone().into(),
- get_signed_extras(signer.into()),
- ),
- function: call.into(),
- };
+// pub struct SchedulerPaymentExecutor;
+// impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
+// DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+// where
+// <T as frame_system::Config>::Call: Member
+// + Dispatchable<Origin = Origin, Info = DispatchInfo>
+// + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+// + GetDispatchInfo
+// + From<frame_system::Call<Runtime>>,
+// SelfContainedSignedInfo: Send + Sync + 'static,
+// Call: From<<T as frame_system::Config>::Call>
+// + From<<T as pallet_unique_scheduler::Config>::Call>
+// + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+// sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+// {
+// fn dispatch_call(
+// signer: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// ) -> Result<
+// Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+// TransactionValidityError,
+// > {
+// let dispatch_info = call.get_dispatch_info();
+// let extrinsic = fp_self_contained::CheckedExtrinsic::<
+// AccountId,
+// Call,
+// SignedExtraScheduler,
+// SelfContainedSignedInfo,
+// > {
+// signed:
+// CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+// signer.clone().into(),
+// get_signed_extras(signer.into()),
+// ),
+// function: call.into(),
+// };
- extrinsic.apply::<Runtime>(&dispatch_info, 0)
- }
+// extrinsic.apply::<Runtime>(&dispatch_info, 0)
+// }
- fn reserve_balance(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- count: u32,
- ) -> Result<(), DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
- .saturating_mul(count.into());
+// fn reserve_balance(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// count: u32,
+// ) -> Result<(), DispatchError> {
+// let dispatch_info = call.get_dispatch_info();
+// let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+// .saturating_mul(count.into());
- <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
- &id,
- &(sponsor.into()),
- weight,
- )
- }
+// <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+// &id,
+// &(sponsor.into()),
+// weight,
+// )
+// }
- fn pay_for_call(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::Call,
- ) -> Result<u128, DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- weight,
- ),
- )
- }
+// fn pay_for_call(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// call: <T as pallet_unique_scheduler::Config>::Call,
+// ) -> Result<u128, DispatchError> {
+// let dispatch_info = call.get_dispatch_info();
+// let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+// Ok(
+// <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+// &id,
+// &(sponsor.into()),
+// weight,
+// ),
+// )
+// }
- fn cancel_reserve(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- ) -> Result<u128, DispatchError> {
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- u128::MAX,
- ),
- )
- }
-}
+// fn cancel_reserve(
+// id: [u8; 16],
+// sponsor: <T as frame_system::Config>::AccountId,
+// ) -> Result<u128, DispatchError> {
+// Ok(
+// <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+// &id,
+// &(sponsor.into()),
+// u128::MAX,
+// ),
+// )
+// }
+// }
parameter_types! {
pub const NoPreimagePostponement: Option<u32> = Some(10);
@@ -1051,21 +1053,21 @@
}
}
-impl pallet_unique_scheduler::Config for Runtime {
- type Event = Event;
- type Origin = Origin;
- type Currency = Balances;
- type PalletsOrigin = OriginCaller;
- type Call = Call;
- type MaximumWeight = MaximumSchedulerWeight;
- type ScheduleOrigin = EnsureSigned<AccountId>;
- type MaxScheduledPerBlock = MaxScheduledPerBlock;
- type WeightInfo = ();
- type CallExecutor = SchedulerPaymentExecutor;
- type OriginPrivilegeCmp = OriginPrivilegeCmp;
- type PreimageProvider = ();
- type NoPreimagePostponement = NoPreimagePostponement;
-}
+// impl pallet_unique_scheduler::Config for Runtime {
+// type Event = Event;
+// type Origin = Origin;
+// type Currency = Balances;
+// type PalletsOrigin = OriginCaller;
+// type Call = Call;
+// type MaximumWeight = MaximumSchedulerWeight;
+// type ScheduleOrigin = EnsureSigned<AccountId>;
+// type MaxScheduledPerBlock = MaxScheduledPerBlock;
+// type WeightInfo = ();
+// type CallExecutor = SchedulerPaymentExecutor;
+// type OriginPrivilegeCmp = OriginPrivilegeCmp;
+// type PreimageProvider = ();
+// type NoPreimagePostponement = NoPreimagePostponement;
+// }
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
@@ -1139,13 +1141,13 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ // Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
Common: pallet_common::{Pallet, Storage, Event<T>} = 66,
Fungible: pallet_fungible::{Pallet, Storage} = 67,
- Refungible: pallet_refungible::{Pallet, Storage} = 68,
+ // Refungible: pallet_refungible::{Pallet, Storage} = 68,
Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -36,6 +36,8 @@
CrossAccountId,
getCreateItemsResult,
getDestroyItemsResult,
+ getModuleNames,
+ Pallets,
} from './util/helpers';
import chai from 'chai';
@@ -46,14 +48,18 @@
let alice: IKeyringPair;
let bob: IKeyringPair;
-describe('integration test: Refungible functionality:', () => {
- before(async () => {
+
+
+describe('integration test: Refungible functionality:', async () => {
+ before(async function() {
await usingApi(async (api, privateKeyWrapper) => {
alice = privateKeyWrapper('//Alice');
bob = privateKeyWrapper('//Bob');
+ if (!getModuleNames(api).includes(Pallets.ReFungible)) this.skip();
});
+
});
-
+
it('Create refungible collection and token', async () => {
await usingApi(async api => {
const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
@@ -268,15 +274,6 @@
]);
});
});
-});
-
-describe('Test Refungible properties:', () => {
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- });
- });
it('Сreate new collection with properties', async () => {
await usingApi(async api => {
@@ -292,3 +289,4 @@
});
});
});
+
tests/src/rmrk/acceptNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/acceptNft.test.ts
+++ b/tests/src/rmrk/acceptNft.test.ts
@@ -8,14 +8,19 @@
} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
+import { getModuleNames, Pallets } from '../util/helpers';
describe('integration test: accept NFT', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
-
+ before(async function() {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
+
+
const alice = '//Alice';
const bob = '//Bob';
-
+
const createTestCollection = async (issuerUri: string) => {
return await createCollection(
api,
tests/src/rmrk/addResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addResource.test.ts
+++ b/tests/src/rmrk/addResource.test.ts
@@ -12,6 +12,7 @@
addNftComposableResource,
} from './util/tx';
import {RmrkTraitsResourceResourceInfo as ResourceInfo} from '@polkadot/types/lookup';
+import { getModuleNames, Pallets } from '../util/helpers';
describe('integration test: add NFT resource', () => {
const Alice = '//Alice';
@@ -24,8 +25,9 @@
const nonexistentId = 99999;
let api: any;
- before(async () => {
+ before(async function() {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
it('add resource', async () => {
tests/src/rmrk/addTheme.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addTheme.test.ts
+++ b/tests/src/rmrk/addTheme.test.ts
@@ -3,10 +3,14 @@
import {createBase, addTheme} from './util/tx';
import {expectTxFailure} from './util/helpers';
import {getThemeNames} from './util/fetch';
+import { getModuleNames, Pallets } from '../util/helpers';
describe('integration test: add Theme to Base', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function() {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const alice = '//Alice';
const bob = '//Bob';
tests/src/rmrk/burnNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/burnNft.test.ts
+++ b/tests/src/rmrk/burnNft.test.ts
@@ -5,6 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
+import { getModuleNames, Pallets } from '../util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -14,10 +15,12 @@
const Bob = '//Bob';
let api: any;
- before(async () => {
+ before(async function() {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
+
it('burn nft', async () => {
await createCollection(
api,
tests/src/rmrk/changeCollectionIssuer.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/changeCollectionIssuer.test.ts
+++ b/tests/src/rmrk/changeCollectionIssuer.test.ts
@@ -1,4 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {
changeIssuer,
@@ -10,10 +11,13 @@
const Bob = '//Bob';
let api: any;
- before(async () => {
+ before(async function() {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
+
+
it('change collection issuer', async () => {
await createCollection(
api,
tests/src/rmrk/createBase.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createBase.test.ts
+++ b/tests/src/rmrk/createBase.test.ts
@@ -1,9 +1,13 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {createCollection, createBase} from './util/tx';
describe('integration test: create new Base', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function() {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const alice = '//Alice';
tests/src/rmrk/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createCollection.test.ts
+++ b/tests/src/rmrk/createCollection.test.ts
@@ -1,9 +1,15 @@
import {getApiConnection} from '../substrate/substrate-api';
+import {getModuleNames, Pallets} from '../util/helpers';
import {createCollection} from './util/tx';
describe('Integration test: create new collection', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
+
+
const alice = '//Alice';
tests/src/rmrk/deleteCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/deleteCollection.test.ts
+++ b/tests/src/rmrk/deleteCollection.test.ts
@@ -1,11 +1,13 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, deleteCollection} from './util/tx';
describe('integration test: delete collection', () => {
let api: any;
- before(async () => {
+ before(async function () {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
const Alice = '//Alice';
tests/src/rmrk/equipNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/equipNft.test.ts
+++ b/tests/src/rmrk/equipNft.test.ts
@@ -1,6 +1,7 @@
import {ApiPromise} from '@polkadot/api';
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
+import {getModuleNames, Pallets} from '../util/helpers';
import {getNft, getParts, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
@@ -122,8 +123,10 @@
describe.skip('integration test: Equip NFT', () => {
let api: any;
- before(async () => {
+
+ before(async function () {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
it('equip nft', async () => {
tests/src/rmrk/getOwnedNfts.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/getOwnedNfts.test.ts
+++ b/tests/src/rmrk/getOwnedNfts.test.ts
@@ -1,11 +1,17 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {getOwnedNfts} from './util/fetch';
import {mintNft, createCollection} from './util/tx';
describe('integration test: get owned NFTs', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
+
const alice = '//Alice';
tests/src/rmrk/lockCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/lockCollection.test.ts
+++ b/tests/src/rmrk/lockCollection.test.ts
@@ -1,4 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, lockCollection, mintNft} from './util/tx';
@@ -8,8 +9,9 @@
const Max = 5;
let api: any;
- before(async () => {
+ before(async function () {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
it('lock collection', async () => {
tests/src/rmrk/mintNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/mintNft.test.ts
+++ b/tests/src/rmrk/mintNft.test.ts
@@ -1,12 +1,18 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {getNft} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft} from './util/tx';
describe('integration test: mint new NFT', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
+
const alice = '//Alice';
const bob = '//Bob';
tests/src/rmrk/rejectNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rejectNft.test.ts
+++ b/tests/src/rmrk/rejectNft.test.ts
@@ -8,10 +8,16 @@
} from './util/tx';
import {getChildren, NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
+import { getModuleNames, Pallets } from '../util/helpers';
describe('integration test: reject NFT', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
+
+
const alice = '//Alice';
const bob = '//Bob';
tests/src/rmrk/removeResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/removeResource.test.ts
+++ b/tests/src/rmrk/removeResource.test.ts
@@ -1,6 +1,7 @@
import {expect} from 'chai';
import privateKey from '../substrate/privateKey';
import {executeTransaction, getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {getNft, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
@@ -16,9 +17,10 @@
describe('Integration test: remove nft resource', () => {
let api: any;
let ss58Format: string;
- before(async () => {
+ before(async function() {
api = await getApiConnection();
ss58Format = api.registry.getChainProperties()!.toJSON().ss58Format;
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
const Alice = '//Alice';
tests/src/rmrk/rmrkIsolation.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rmrkIsolation.test.ts
+++ b/tests/src/rmrk/rmrkIsolation.test.ts
@@ -6,7 +6,9 @@
getCreateCollectionResult,
getDetailedCollectionInfo,
getGenericResult,
+ getModuleNames,
normalizeAccountId,
+ Pallets,
} from '../util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
import {ApiPromise} from '@polkadot/api';
@@ -59,11 +61,10 @@
describe('RMRK External Integration Test', async () => {
const it_rmrk = (await isUnique() ? it : it.skip);
- before(async () => {
+ before(async function() {
await usingApi(async (api, privateKeyWrapper) => {
alice = privateKeyWrapper('//Alice');
-
-
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
});
tests/src/rmrk/sendNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/sendNft.test.ts
+++ b/tests/src/rmrk/sendNft.test.ts
@@ -3,10 +3,14 @@
import {createCollection, mintNft, sendNft} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
+import { getModuleNames, Pallets } from '../util/helpers';
describe('integration test: send NFT', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const maxNftId = 0xFFFFFFFF;
tests/src/rmrk/setCollectionProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setCollectionProperty.test.ts
+++ b/tests/src/rmrk/setCollectionProperty.test.ts
@@ -1,4 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, setPropertyCollection} from './util/tx';
@@ -7,8 +8,9 @@
const Bob = '//Bob';
let api: any;
- before(async () => {
+ before(async function () {
api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
});
it('set collection property', async () => {
tests/src/rmrk/setEquippableList.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setEquippableList.test.ts
+++ b/tests/src/rmrk/setEquippableList.test.ts
@@ -1,10 +1,14 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, createBase, setEquippableList} from './util/tx';
describe("integration test: set slot's Equippable List", () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const alice = '//Alice';
const bob = '//Bob';
tests/src/rmrk/setNftProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setNftProperty.test.ts
+++ b/tests/src/rmrk/setNftProperty.test.ts
@@ -1,11 +1,15 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft, sendNft, setNftProperty} from './util/tx';
describe('integration test: set NFT property', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const alice = '//Alice';
const bob = '//Bob';
tests/src/rmrk/setResourcePriorities.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setResourcePriorities.test.ts
+++ b/tests/src/rmrk/setResourcePriorities.test.ts
@@ -1,10 +1,14 @@
import {getApiConnection} from '../substrate/substrate-api';
+import { getModuleNames, Pallets } from '../util/helpers';
import {expectTxFailure} from './util/helpers';
import {mintNft, createCollection, setResourcePriorities} from './util/tx';
describe('integration test: set NFT resource priorities', () => {
let api: any;
- before(async () => { api = await getApiConnection(); });
+ before(async function () {
+ api = await getApiConnection();
+ if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+ });
const alice = '//Alice';
const bob = '//Bob';
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';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 >= 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;9091interface GenericResult<T> {92 success: boolean;93 data: T | null;94}9596interface CreateCollectionResult {97 success: boolean;98 collectionId: number;99}100101interface CreateItemResult {102 success: boolean;103 collectionId: number;104 itemId: number;105 recipient?: CrossAccountId;106 amount?: number;107}108109interface DestroyItemResult {110 success: boolean;111 collectionId: number;112 itemId: number;113 owner: CrossAccountId;114 amount: number;115}116117interface TransferResult {118 collectionId: number;119 itemId: number;120 sender?: CrossAccountId;121 recipient?: CrossAccountId;122 value: bigint;123}124125interface IReFungibleOwner {126 fraction: BN;127 owner: number[];128}129130interface IGetMessage {131 checkMsgUnqMethod: string;132 checkMsgTrsMethod: string;133 checkMsgSysMethod: string;134}135136export interface IFungibleTokenDataType {137 value: number;138}139140export interface IChainLimits {141 collectionNumbersLimit: number;142 accountTokenOwnershipLimit: number;143 collectionsAdminsLimit: number;144 customDataLimit: number;145 nftSponsorTransferTimeout: number;146 fungibleSponsorTransferTimeout: number;147 refungibleSponsorTransferTimeout: number;148 //offchainSchemaLimit: number;149 //constOnChainSchemaLimit: number;150}151152export interface IReFungibleTokenDataType {153 owner: IReFungibleOwner[];154}155156export function uniqueEventMessage(events: EventRecord[]): IGetMessage {157 let checkMsgUnqMethod = '';158 let checkMsgTrsMethod = '';159 let checkMsgSysMethod = '';160 events.forEach(({event: {method, section}}) => {161 if (section === 'common') {162 checkMsgUnqMethod = method;163 } else if (section === 'treasury') {164 checkMsgTrsMethod = method;165 } else if (section === 'system') {166 checkMsgSysMethod = method;167 } else { return null; }168 });169 const result: IGetMessage = {170 checkMsgUnqMethod,171 checkMsgTrsMethod,172 checkMsgSysMethod,173 };174 return result;175}176177export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {178 const event = events.find(r => check(r.event));179 if (!event) return;180 return event.event as T;181}182183export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;184export function getGenericResult<T>(185 events: EventRecord[],186 expectSection: string,187 expectMethod: string,188 extractAction: (data: GenericEventData) => T189): GenericResult<T>;190191export function getGenericResult<T>(192 events: EventRecord[],193 expectSection?: string,194 expectMethod?: string,195 extractAction?: (data: GenericEventData) => T,196): GenericResult<T> {197 let success = false;198 let successData = null;199200 events.forEach(({event: {data, method, section}}) => {201 // console.log(` ${phase}: ${section}.${method}:: ${data}`);202 if (method === 'ExtrinsicSuccess') {203 success = true;204 } else if ((expectSection == section) && (expectMethod == method)) {205 successData = extractAction!(data as any);206 }207 });208209 const result: GenericResult<T> = {210 success,211 data: successData,212 };213 return result;214}215216export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {217 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));218 const result: CreateCollectionResult = {219 success: genericResult.success,220 collectionId: genericResult.data ?? 0,221 };222 return result;223}224225export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {226 const results: CreateItemResult[] = [];227 228 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {229 const collectionId = parseInt(data[0].toString(), 10);230 const itemId = parseInt(data[1].toString(), 10);231 const recipient = normalizeAccountId(data[2].toJSON() as any);232 const amount = parseInt(data[3].toString(), 10);233234 const itemRes: CreateItemResult = {235 success: true,236 collectionId,237 itemId,238 recipient,239 amount,240 };241242 results.push(itemRes);243 return results;244 });245246 if (!genericResult.success) return [];247 return results;248}249250export function getCreateItemResult(events: EventRecord[]): CreateItemResult {251 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));252 253 if (genericResult.data == null) 254 return {255 success: genericResult.success,256 collectionId: 0,257 itemId: 0,258 amount: 0,259 };260 else 261 return {262 success: genericResult.success,263 collectionId: genericResult.data[0] as number,264 itemId: genericResult.data[1] as number,265 recipient: normalizeAccountId(genericResult.data![2] as any),266 amount: genericResult.data[3] as number,267 };268}269270export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {271 const results: DestroyItemResult[] = [];272 273 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {274 const collectionId = parseInt(data[0].toString(), 10);275 const itemId = parseInt(data[1].toString(), 10);276 const owner = normalizeAccountId(data[2].toJSON() as any);277 const amount = parseInt(data[3].toString(), 10);278279 const itemRes: DestroyItemResult = {280 success: true,281 collectionId,282 itemId,283 owner,284 amount,285 };286287 results.push(itemRes);288 return results;289 });290291 if (!genericResult.success) return [];292 return results;293}294295export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {296 for (const {event} of events) {297 if (api.events.common.Transfer.is(event)) {298 const [collection, token, sender, recipient, value] = event.data;299 return {300 collectionId: collection.toNumber(),301 itemId: token.toNumber(),302 sender: normalizeAccountId(sender.toJSON() as any),303 recipient: normalizeAccountId(recipient.toJSON() as any),304 value: value.toBigInt(),305 };306 }307 }308 throw new Error('no transfer event');309}310311interface Nft {312 type: 'NFT';313}314315interface Fungible {316 type: 'Fungible';317 decimalPoints: number;318}319320interface ReFungible {321 type: 'ReFungible';322}323324export type CollectionMode = Nft | Fungible | ReFungible;325326export type Property = {327 key: any,328 value: any,329};330331type Permission = {332 mutable: boolean;333 collectionAdmin: boolean;334 tokenOwner: boolean;335}336337type PropertyPermission = {338 key: any;339 permission: Permission;340}341342export type CreateCollectionParams = {343 mode: CollectionMode,344 name: string,345 description: string,346 tokenPrefix: string,347 properties?: Array<Property>,348 propPerm?: Array<PropertyPermission>349};350351const defaultCreateCollectionParams: CreateCollectionParams = {352 description: 'description',353 mode: {type: 'NFT'},354 name: 'name',355 tokenPrefix: 'prefix',356};357358export async function359createCollection(360 api: ApiPromise,361 sender: IKeyringPair,362 params: Partial<CreateCollectionParams> = {},363): Promise<CreateCollectionResult> {364 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};365366 let modeprm = {};367 if (mode.type === 'NFT') {368 modeprm = {nft: null};369 } else if (mode.type === 'Fungible') {370 modeprm = {fungible: mode.decimalPoints};371 } else if (mode.type === 'ReFungible') {372 modeprm = {refungible: null};373 }374375 const tx = api.tx.unique.createCollectionEx({376 name: strToUTF16(name),377 description: strToUTF16(description),378 tokenPrefix: strToUTF16(tokenPrefix),379 mode: modeprm as any,380 });381 const events = await submitTransactionAsync(sender, tx);382 return getCreateCollectionResult(events);383}384385export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {386 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};387388 let collectionId = 0;389 await usingApi(async (api, privateKeyWrapper) => {390 // Get number of collections before the transaction391 const collectionCountBefore = await getCreatedCollectionCount(api);392393 // Run the CreateCollection transaction394 const alicePrivateKey = privateKeyWrapper('//Alice');395396 const result = await createCollection(api, alicePrivateKey, params);397398 // Get number of collections after the transaction399 const collectionCountAfter = await getCreatedCollectionCount(api);400401 // Get the collection402 const collection = await queryCollectionExpectSuccess(api, result.collectionId);403404 // What to expect405 // tslint:disable-next-line:no-unused-expression406 expect(result.success).to.be.true;407 expect(result.collectionId).to.be.equal(collectionCountAfter);408 // tslint:disable-next-line:no-unused-expression409 expect(collection).to.be.not.null;410 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');411 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));412 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);413 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);414 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);415416 collectionId = result.collectionId;417 });418419 return collectionId;420}421422export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {423 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};424425 let collectionId = 0;426 await usingApi(async (api, privateKeyWrapper) => {427 // Get number of collections before the transaction428 const collectionCountBefore = await getCreatedCollectionCount(api);429430 // Run the CreateCollection transaction431 const alicePrivateKey = privateKeyWrapper('//Alice');432433 let modeprm = {};434 if (mode.type === 'NFT') {435 modeprm = {nft: null};436 } else if (mode.type === 'Fungible') {437 modeprm = {fungible: mode.decimalPoints};438 } else if (mode.type === 'ReFungible') {439 modeprm = {refungible: null};440 }441442 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});443 const events = await submitTransactionAsync(alicePrivateKey, tx);444 const result = getCreateCollectionResult(events);445446 // Get number of collections after the transaction447 const collectionCountAfter = await getCreatedCollectionCount(api);448449 // Get the collection450 const collection = await queryCollectionExpectSuccess(api, result.collectionId);451452 // What to expect453 // tslint:disable-next-line:no-unused-expression454 expect(result.success).to.be.true;455 expect(result.collectionId).to.be.equal(collectionCountAfter);456 // tslint:disable-next-line:no-unused-expression457 expect(collection).to.be.not.null;458 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');459 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));460 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);461 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);462 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);463464465 collectionId = result.collectionId;466 });467468 return collectionId;469}470471export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {472 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};473474 await usingApi(async (api, privateKeyWrapper) => {475 // Get number of collections before the transaction476 const collectionCountBefore = await getCreatedCollectionCount(api);477478 // Run the CreateCollection transaction479 const alicePrivateKey = privateKeyWrapper('//Alice');480481 let modeprm = {};482 if (mode.type === 'NFT') {483 modeprm = {nft: null};484 } else if (mode.type === 'Fungible') {485 modeprm = {fungible: mode.decimalPoints};486 } else if (mode.type === 'ReFungible') {487 modeprm = {refungible: null};488 }489490 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});491 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;492493494 // Get number of collections after the transaction495 const collectionCountAfter = await getCreatedCollectionCount(api);496497 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');498 });499}500501export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {502 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};503504 let modeprm = {};505 if (mode.type === 'NFT') {506 modeprm = {nft: null};507 } else if (mode.type === 'Fungible') {508 modeprm = {fungible: mode.decimalPoints};509 } else if (mode.type === 'ReFungible') {510 modeprm = {refungible: null};511 }512513 await usingApi(async (api, privateKeyWrapper) => {514 // Get number of collections before the transaction515 const collectionCountBefore = await getCreatedCollectionCount(api);516517 // Run the CreateCollection transaction518 const alicePrivateKey = privateKeyWrapper('//Alice');519 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});520 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;521522 // Get number of collections after the transaction523 const collectionCountAfter = await getCreatedCollectionCount(api);524525 // What to expect526 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');527 });528}529530export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {531 let bal = 0n;532 let unused;533 do {534 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;535 unused = privateKeyWrapper(`//${randomSeed}`);536 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();537 } while (bal !== 0n);538 return unused;539}540541export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {542 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();543}544545export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {546 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));547}548549export async function findNotExistingCollection(api: ApiPromise): Promise<number> {550 const totalNumber = await getCreatedCollectionCount(api);551 const newCollection: number = totalNumber + 1;552 return newCollection;553}554555function getDestroyResult(events: EventRecord[]): boolean {556 let success = false;557 events.forEach(({event: {method}}) => {558 if (method == 'ExtrinsicSuccess') {559 success = true;560 }561 });562 return success;563}564565export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {566 await usingApi(async (api, privateKeyWrapper) => {567 // Run the DestroyCollection transaction568 const alicePrivateKey = privateKeyWrapper(senderSeed);569 const tx = api.tx.unique.destroyCollection(collectionId);570 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;571 });572}573574export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {575 await usingApi(async (api, privateKeyWrapper) => {576 // Run the DestroyCollection transaction577 const alicePrivateKey = privateKeyWrapper(senderSeed);578 const tx = api.tx.unique.destroyCollection(collectionId);579 const events = await submitTransactionAsync(alicePrivateKey, tx);580 const result = getDestroyResult(events);581 expect(result).to.be.true;582583 // What to expect584 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;585 });586}587588export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {589 await usingApi(async (api) => {590 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);591 const events = await submitTransactionAsync(sender, tx);592 const result = getGenericResult(events);593594 expect(result.success).to.be.true;595 });596}597598export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {599 await usingApi(async(api) => {600 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);601 const events = await submitTransactionAsync(sender, tx);602 const result = getGenericResult(events);603604 expect(result.success).to.be.true;605 });606};607608export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {609 await usingApi(async (api) => {610 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);611 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;612 const result = getGenericResult(events);613614 expect(result.success).to.be.false;615 });616}617618export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {619 await usingApi(async (api, privateKeyWrapper) => {620621 // Run the transaction622 const senderPrivateKey = privateKeyWrapper(sender);623 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);624 const events = await submitTransactionAsync(senderPrivateKey, tx);625 const result = getGenericResult(events);626627 // Get the collection628 const collection = await queryCollectionExpectSuccess(api, collectionId);629630 // What to expect631 expect(result.success).to.be.true;632 expect(collection.sponsorship.toJSON()).to.deep.equal({633 unconfirmed: sponsor,634 });635 });636}637638export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {639 await usingApi(async (api, privateKeyWrapper) => {640641 // Run the transaction642 const alicePrivateKey = privateKeyWrapper(sender);643 const tx = api.tx.unique.removeCollectionSponsor(collectionId);644 const events = await submitTransactionAsync(alicePrivateKey, tx);645 const result = getGenericResult(events);646647 // Get the collection648 const collection = await queryCollectionExpectSuccess(api, collectionId);649650 // What to expect651 expect(result.success).to.be.true;652 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});653 });654}655656export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {657 await usingApi(async (api, privateKeyWrapper) => {658659 // Run the transaction660 const alicePrivateKey = privateKeyWrapper(senderSeed);661 const tx = api.tx.unique.removeCollectionSponsor(collectionId);662 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;663 });664}665666export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {667 await usingApi(async (api, privateKeyWrapper) => {668669 // Run the transaction670 const alicePrivateKey = privateKeyWrapper(senderSeed);671 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);672 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;673 });674}675676export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {677 await usingApi(async (api, privateKeyWrapper) => {678679 // Run the transaction680 const sender = privateKeyWrapper(senderSeed);681 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);682 });683}684685export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {686 await usingApi(async (api, privateKeyWrapper) => {687688 // Run the transaction689 const tx = api.tx.unique.confirmSponsorship(collectionId);690 const events = await submitTransactionAsync(sender, tx);691 const result = getGenericResult(events);692693 // Get the collection694 const collection = await queryCollectionExpectSuccess(api, collectionId);695696 // What to expect697 expect(result.success).to.be.true;698 expect(collection.sponsorship.toJSON()).to.be.deep.equal({699 confirmed: sender.address,700 });701 });702}703704705export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {706 await usingApi(async (api, privateKeyWrapper) => {707708 // Run the transaction709 const sender = privateKeyWrapper(senderSeed);710 const tx = api.tx.unique.confirmSponsorship(collectionId);711 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;712 });713}714715export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {716 await usingApi(async (api) => {717 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);718 const events = await submitTransactionAsync(sender, tx);719 const result = getGenericResult(events);720721 expect(result.success).to.be.true;722 });723}724725export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {726 await usingApi(async (api) => {727 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);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 setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {736737 await usingApi(async (api) => {738739 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);740 const events = await submitTransactionAsync(sender, tx);741 const result = getGenericResult(events);742743 expect(result.success).to.be.true;744 });745}746747export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {748749 await usingApi(async (api) => {750751 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);752 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;753 const result = getGenericResult(events);754755 expect(result.success).to.be.false;756 });757}758759export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {760 await usingApi(async (api) => {761 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);762 const events = await submitTransactionAsync(sender, tx);763 const result = getGenericResult(events);764765 expect(result.success).to.be.true;766 });767}768769export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {770 await usingApi(async (api) => {771 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);772 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773 const result = getGenericResult(events);774775 expect(result.success).to.be.false;776 });777}778779export async function getNextSponsored(780 api: ApiPromise,781 collectionId: number,782 account: string | CrossAccountId,783 tokenId: number,784): Promise<number> {785 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));786}787788export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {789 await usingApi(async (api) => {790 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);791 const events = await submitTransactionAsync(sender, tx);792 const result = getGenericResult(events);793794 expect(result.success).to.be.true;795 });796}797798export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {799 let allowlisted = false;800 await usingApi(async (api) => {801 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;802 });803 return allowlisted;804}805806export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {807 await usingApi(async (api) => {808 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());809 const events = await submitTransactionAsync(sender, tx);810 const result = getGenericResult(events);811812 expect(result.success).to.be.true;813 });814}815816export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {817 await usingApi(async (api) => {818 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());819 const events = await submitTransactionAsync(sender, tx);820 const result = getGenericResult(events);821822 expect(result.success).to.be.true;823 });824}825826export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {827 await usingApi(async (api) => {828 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());829 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;830 const result = getGenericResult(events);831832 expect(result.success).to.be.false;833 });834}835836export interface CreateFungibleData {837 readonly Value: bigint;838}839840export interface CreateReFungibleData { }841export interface CreateNftData { }842843export type CreateItemData = {844 NFT: CreateNftData;845} | {846 Fungible: CreateFungibleData;847} | {848 ReFungible: CreateReFungibleData;849};850851export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {852 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);853 const events = await submitTransactionAsync(sender, tx);854 return getGenericResult(events).success;855}856857export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {858 await usingApi(async (api) => {859 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);860 // if burning token by admin - use adminButnItemExpectSuccess861 expect(balanceBefore >= BigInt(value)).to.be.true;862863 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;864865 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);866 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);867 });868}869870export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {871 await usingApi(async (api) => {872 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);873874 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;875 const result = getCreateCollectionResult(events);876 // tslint:disable-next-line:no-unused-expression877 expect(result.success).to.be.false;878 });879}880881export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {882 await usingApi(async (api) => {883 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);884 const events = await submitTransactionAsync(sender, tx);885 return getGenericResult(events).success;886 });887}888889export async function890approve(891 api: ApiPromise,892 collectionId: number,893 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,894) {895 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);896 const events = await submitTransactionAsync(owner, approveUniqueTx);897 return getGenericResult(events).success;898}899900export async function901approveExpectSuccess(902 collectionId: number,903 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,904) {905 await usingApi(async (api: ApiPromise) => {906 const result = await approve(api, collectionId, tokenId, owner, approved, amount);907 expect(result).to.be.true;908909 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));910 });911}912913export async function adminApproveFromExpectSuccess(914 collectionId: number,915 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,916) {917 await usingApi(async (api: ApiPromise) => {918 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);919 const events = await submitTransactionAsync(admin, approveUniqueTx);920 const result = getGenericResult(events);921 expect(result.success).to.be.true;922923 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));924 });925}926927export async function928transferFrom(929 api: ApiPromise,930 collectionId: number,931 tokenId: number,932 accountApproved: IKeyringPair,933 accountFrom: IKeyringPair | CrossAccountId,934 accountTo: IKeyringPair | CrossAccountId,935 value: number | bigint,936) {937 const from = normalizeAccountId(accountFrom);938 const to = normalizeAccountId(accountTo);939 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);940 const events = await submitTransactionAsync(accountApproved, transferFromTx);941 return getGenericResult(events).success;942}943944export async function945transferFromExpectSuccess(946 collectionId: number,947 tokenId: number,948 accountApproved: IKeyringPair,949 accountFrom: IKeyringPair | CrossAccountId,950 accountTo: IKeyringPair | CrossAccountId,951 value: number | bigint = 1,952 type = 'NFT',953) {954 await usingApi(async (api: ApiPromise) => {955 const from = normalizeAccountId(accountFrom);956 const to = normalizeAccountId(accountTo);957 let balanceBefore = 0n;958 if (type === 'Fungible' || type === 'ReFungible') {959 balanceBefore = await getBalance(api, collectionId, to, tokenId);960 }961 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;962 if (type === 'NFT') {963 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);964 }965 if (type === 'Fungible') {966 const balanceAfter = await getBalance(api, collectionId, to, tokenId);967 if (JSON.stringify(to) !== JSON.stringify(from)) {968 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));969 } else {970 expect(balanceAfter).to.be.equal(balanceBefore);971 }972 }973 if (type === 'ReFungible') {974 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));975 }976 });977}978979export async function980transferFromExpectFail(981 collectionId: number,982 tokenId: number,983 accountApproved: IKeyringPair,984 accountFrom: IKeyringPair,985 accountTo: IKeyringPair,986 value: number | bigint = 1,987) {988 await usingApi(async (api: ApiPromise) => {989 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);990 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;991 const result = getCreateCollectionResult(events);992 // tslint:disable-next-line:no-unused-expression993 expect(result.success).to.be.false;994 });995}996997/* eslint no-async-promise-executor: "off" */998export async function getBlockNumber(api: ApiPromise): Promise<number> {999 return new Promise<number>(async (resolve) => {1000 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1001 unsubscribe();1002 resolve(head.number.toNumber());1003 });1004 });1005}10061007export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1008 await usingApi(async (api) => {1009 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1010 const events = await submitTransactionAsync(sender, changeAdminTx);1011 const result = getCreateCollectionResult(events);1012 expect(result.success).to.be.true;1013 });1014}10151016export async function adminApproveFromExpectFail(1017 collectionId: number,1018 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1019) {1020 await usingApi(async (api: ApiPromise) => {1021 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1022 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1023 const result = getGenericResult(events);1024 expect(result.success).to.be.false;1025 });1026}10271028export async function1029getFreeBalance(account: IKeyringPair): Promise<bigint> {1030 let balance = 0n;1031 await usingApi(async (api) => {1032 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1033 });10341035 return balance;1036}10371038export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1039 const tx = api.tx.balances.transfer(target, amount);1040 const events = await submitTransactionAsync(source, tx);1041 const result = getGenericResult(events);1042 expect(result.success).to.be.true;1043}10441045export async function1046scheduleExpectSuccess(1047 operationTx: any,1048 sender: IKeyringPair,1049 blockSchedule: number,1050 scheduledId: string,1051 period = 1,1052 repetitions = 1,1053) {1054 await usingApi(async (api: ApiPromise) => {1055 const blockNumber: number | undefined = await getBlockNumber(api);1056 const expectedBlockNumber = blockNumber + blockSchedule;10571058 expect(blockNumber).to.be.greaterThan(0);1059 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1060 scheduledId,1061 expectedBlockNumber, 1062 repetitions > 1 ? [period, repetitions] : null, 1063 0, 1064 {Value: operationTx as any},1065 );10661067 const events = await submitTransactionAsync(sender, scheduleTx);1068 expect(getGenericResult(events).success).to.be.true;1069 });1070}10711072export async function1073scheduleExpectFailure(1074 operationTx: any,1075 sender: IKeyringPair,1076 blockSchedule: number,1077 scheduledId: string,1078 period = 1,1079 repetitions = 1,1080) {1081 await usingApi(async (api: ApiPromise) => {1082 const blockNumber: number | undefined = await getBlockNumber(api);1083 const expectedBlockNumber = blockNumber + blockSchedule;10841085 expect(blockNumber).to.be.greaterThan(0);1086 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1087 scheduledId,1088 expectedBlockNumber, 1089 repetitions <= 1 ? null : [period, repetitions], 1090 0, 1091 {Value: operationTx as any},1092 );10931094 //const events = 1095 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1096 //expect(getGenericResult(events).success).to.be.false;1097 });1098}10991100export async function1101scheduleTransferAndWaitExpectSuccess(1102 collectionId: number,1103 tokenId: number,1104 sender: IKeyringPair,1105 recipient: IKeyringPair,1106 value: number | bigint = 1,1107 blockSchedule: number,1108 scheduledId: string,1109) {1110 await usingApi(async (api: ApiPromise) => {1111 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11121113 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11141115 // sleep for n + 1 blocks1116 await waitNewBlocks(blockSchedule + 1);11171118 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11191120 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1121 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1122 });1123}11241125export async function1126scheduleTransferExpectSuccess(1127 collectionId: number,1128 tokenId: number,1129 sender: IKeyringPair,1130 recipient: IKeyringPair,1131 value: number | bigint = 1,1132 blockSchedule: number,1133 scheduledId: string,1134) {1135 await usingApi(async (api: ApiPromise) => {1136 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11371138 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11391140 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1141 });1142}11431144export async function1145scheduleTransferFundsPeriodicExpectSuccess(1146 amount: bigint,1147 sender: IKeyringPair,1148 recipient: IKeyringPair,1149 blockSchedule: number,1150 scheduledId: string,1151 period: number,1152 repetitions: number,1153) {1154 await usingApi(async (api: ApiPromise) => {1155 const transferTx = api.tx.balances.transfer(recipient.address, amount);11561157 const balanceBefore = await getFreeBalance(recipient);1158 1159 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11601161 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1162 });1163}11641165export async function1166transfer(1167 api: ApiPromise,1168 collectionId: number,1169 tokenId: number,1170 sender: IKeyringPair,1171 recipient: IKeyringPair | CrossAccountId,1172 value: number | bigint,1173) : Promise<boolean> {1174 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1175 const events = await executeTransaction(api, sender, transferTx);1176 return getGenericResult(events).success;1177}11781179export async function1180transferExpectSuccess(1181 collectionId: number,1182 tokenId: number,1183 sender: IKeyringPair,1184 recipient: IKeyringPair | CrossAccountId,1185 value: number | bigint = 1,1186 type = 'NFT',1187) {1188 await usingApi(async (api: ApiPromise) => {1189 const from = normalizeAccountId(sender);1190 const to = normalizeAccountId(recipient);11911192 let balanceBefore = 0n;1193 if (type === 'Fungible' || type === 'ReFungible') {1194 balanceBefore = await getBalance(api, collectionId, to, tokenId);1195 }11961197 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1198 const events = await executeTransaction(api, sender, transferTx);1199 const result = getTransferResult(api, events);12001201 expect(result.collectionId).to.be.equal(collectionId);1202 expect(result.itemId).to.be.equal(tokenId);1203 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1204 expect(result.recipient).to.be.deep.equal(to);1205 expect(result.value).to.be.equal(BigInt(value));12061207 if (type === 'NFT') {1208 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1209 }1210 if (type === 'Fungible' || type === 'ReFungible') {1211 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1212 if (JSON.stringify(to) !== JSON.stringify(from)) {1213 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1214 } else {1215 expect(balanceAfter).to.be.equal(balanceBefore);1216 }1217 }1218 });1219}12201221export async function1222transferExpectFailure(1223 collectionId: number,1224 tokenId: number,1225 sender: IKeyringPair,1226 recipient: IKeyringPair | CrossAccountId,1227 value: number | bigint = 1,1228) {1229 await usingApi(async (api: ApiPromise) => {1230 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1231 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1232 const result = getGenericResult(events);1233 // if (events && Array.isArray(events)) {1234 // const result = getCreateCollectionResult(events);1235 // tslint:disable-next-line:no-unused-expression1236 expect(result.success).to.be.false;1237 //}1238 });1239}12401241export async function1242approveExpectFail(1243 collectionId: number,1244 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1245) {1246 await usingApi(async (api: ApiPromise) => {1247 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1248 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1249 const result = getCreateCollectionResult(events);1250 // tslint:disable-next-line:no-unused-expression1251 expect(result.success).to.be.false;1252 });1253}12541255export async function getBalance(1256 api: ApiPromise,1257 collectionId: number,1258 owner: string | CrossAccountId | IKeyringPair,1259 token: number,1260): Promise<bigint> {1261 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1262}1263export async function getTokenOwner(1264 api: ApiPromise,1265 collectionId: number,1266 token: number,1267): Promise<CrossAccountId> {1268 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1269 if (owner == null) throw new Error('owner == null');1270 return normalizeAccountId(owner);1271}1272export async function getTopmostTokenOwner(1273 api: ApiPromise,1274 collectionId: number,1275 token: number,1276): Promise<CrossAccountId> {1277 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1278 if (owner == null) throw new Error('owner == null');1279 return normalizeAccountId(owner);1280}1281export async function getTokenChildren(1282 api: ApiPromise,1283 collectionId: number,1284 tokenId: number,1285): Promise<UpDataStructsTokenChild[]> {1286 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1287}1288export async function isTokenExists(1289 api: ApiPromise,1290 collectionId: number,1291 token: number,1292): Promise<boolean> {1293 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1294}1295export async function getLastTokenId(1296 api: ApiPromise,1297 collectionId: number,1298): Promise<number> {1299 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1300}1301export async function getAdminList(1302 api: ApiPromise,1303 collectionId: number,1304): Promise<string[]> {1305 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1306}1307export async function getTokenProperties(1308 api: ApiPromise,1309 collectionId: number,1310 tokenId: number,1311 propertyKeys: string[],1312): Promise<UpDataStructsProperty[]> {1313 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1314}13151316export async function createFungibleItemExpectSuccess(1317 sender: IKeyringPair,1318 collectionId: number,1319 data: CreateFungibleData,1320 owner: CrossAccountId | string = sender.address,1321) {1322 return await usingApi(async (api) => {1323 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13241325 const events = await submitTransactionAsync(sender, tx);1326 const result = getCreateItemResult(events);13271328 expect(result.success).to.be.true;1329 return result.itemId;1330 });1331}13321333export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1334 await usingApi(async (api) => {1335 const to = normalizeAccountId(owner);1336 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13371338 const events = await submitTransactionAsync(sender, tx);1339 expect(getGenericResult(events).success).to.be.true;1340 });1341}13421343export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1344 await usingApi(async (api) => {1345 const to = normalizeAccountId(owner);1346 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13471348 const events = await submitTransactionAsync(sender, tx);1349 const result = getCreateItemsResult(events);13501351 for (const res of result) {1352 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1353 }1354 });1355}13561357export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1358 await usingApi(async (api) => {1359 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13601361 const events = await submitTransactionAsync(sender, tx);1362 const result = getCreateItemsResult(events);13631364 for (const res of result) {1365 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1366 }1367 });1368}13691370export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1371 let newItemId = 0;1372 await usingApi(async (api) => {1373 const to = normalizeAccountId(owner);1374 const itemCountBefore = await getLastTokenId(api, collectionId);1375 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13761377 let tx;1378 if (createMode === 'Fungible') {1379 const createData = {fungible: {value: 10}};1380 tx = api.tx.unique.createItem(collectionId, to, createData as any);1381 } else if (createMode === 'ReFungible') {1382 const createData = {refungible: {pieces: 100}};1383 tx = api.tx.unique.createItem(collectionId, to, createData as any);1384 } else {1385 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1386 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1387 }13881389 const events = await submitTransactionAsync(sender, tx);1390 const result = getCreateItemResult(events);13911392 const itemCountAfter = await getLastTokenId(api, collectionId);1393 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13941395 if (createMode === 'NFT') {1396 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1397 }13981399 // What to expect1400 // tslint:disable-next-line:no-unused-expression1401 expect(result.success).to.be.true;1402 if (createMode === 'Fungible') {1403 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1404 } else {1405 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1406 }1407 expect(collectionId).to.be.equal(result.collectionId);1408 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1409 expect(to).to.be.deep.equal(result.recipient);1410 newItemId = result.itemId;1411 });1412 return newItemId;1413}14141415export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1416 await usingApi(async (api) => {14171418 let tx;1419 if (createMode === 'NFT') {1420 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1421 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1422 } else {1423 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1424 }142514261427 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1428 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1429 const result = getCreateItemResult(events);14301431 expect(result.success).to.be.false;1432 });1433}14341435export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1436 let newItemId = 0;1437 await usingApi(async (api) => {1438 const to = normalizeAccountId(owner);1439 const itemCountBefore = await getLastTokenId(api, collectionId);1440 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14411442 let tx;1443 if (createMode === 'Fungible') {1444 const createData = {fungible: {value: 10}};1445 tx = api.tx.unique.createItem(collectionId, to, createData as any);1446 } else if (createMode === 'ReFungible') {1447 const createData = {refungible: {pieces: 100}};1448 tx = api.tx.unique.createItem(collectionId, to, createData as any);1449 } else {1450 const createData = {nft: {}};1451 tx = api.tx.unique.createItem(collectionId, to, createData as any);1452 }14531454 const events = await executeTransaction(api, sender, tx);1455 const result = getCreateItemResult(events);14561457 const itemCountAfter = await getLastTokenId(api, collectionId);1458 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14591460 // What to expect1461 // tslint:disable-next-line:no-unused-expression1462 expect(result.success).to.be.true;1463 if (createMode === 'Fungible') {1464 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1465 } else {1466 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1467 }1468 expect(collectionId).to.be.equal(result.collectionId);1469 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1470 expect(to).to.be.deep.equal(result.recipient);1471 newItemId = result.itemId;1472 });1473 return newItemId;1474}14751476export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1477 const createData = {refungible: {pieces: amount}};1478 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14791480 const events = await submitTransactionAsync(sender, tx);1481 return getCreateItemResult(events);1482}14831484export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1485 await usingApi(async (api) => {1486 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14871488 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1489 const result = getCreateItemResult(events);14901491 expect(result.success).to.be.false;1492 });1493}14941495export async function setPublicAccessModeExpectSuccess(1496 sender: IKeyringPair, collectionId: number,1497 accessMode: 'Normal' | 'AllowList',1498) {1499 await usingApi(async (api) => {15001501 // Run the transaction1502 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1503 const events = await submitTransactionAsync(sender, tx);1504 const result = getGenericResult(events);15051506 // Get the collection1507 const collection = await queryCollectionExpectSuccess(api, collectionId);15081509 // What to expect1510 // tslint:disable-next-line:no-unused-expression1511 expect(result.success).to.be.true;1512 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1513 });1514}15151516export async function setPublicAccessModeExpectFail(1517 sender: IKeyringPair, collectionId: number,1518 accessMode: 'Normal' | 'AllowList',1519) {1520 await usingApi(async (api) => {15211522 // Run the transaction1523 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1524 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1525 const result = getGenericResult(events);15261527 // What to expect1528 // tslint:disable-next-line:no-unused-expression1529 expect(result.success).to.be.false;1530 });1531}15321533export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1534 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1535}15361537export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1538 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1539}15401541export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1542 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1543}15441545export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1546 await usingApi(async (api) => {15471548 // Run the transaction1549 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1550 const events = await submitTransactionAsync(sender, tx);1551 const result = getGenericResult(events);1552 expect(result.success).to.be.true;15531554 // Get the collection1555 const collection = await queryCollectionExpectSuccess(api, collectionId);15561557 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1558 });1559}15601561export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1562 await setMintPermissionExpectSuccess(sender, collectionId, true);1563}15641565export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1566 await usingApi(async (api) => {1567 // Run the transaction1568 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1569 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1570 const result = getCreateCollectionResult(events);1571 // tslint:disable-next-line:no-unused-expression1572 expect(result.success).to.be.false;1573 });1574}15751576export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1577 await usingApi(async (api) => {1578 // Run the transaction1579 const tx = api.tx.unique.setChainLimits(limits);1580 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1581 const result = getCreateCollectionResult(events);1582 // tslint:disable-next-line:no-unused-expression1583 expect(result.success).to.be.false;1584 });1585}15861587export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1588 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1589}15901591export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1592 await usingApi(async (api) => {1593 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15941595 // Run the transaction1596 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1597 const events = await submitTransactionAsync(sender, tx);1598 const result = getGenericResult(events);1599 expect(result.success).to.be.true;16001601 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1602 });1603}16041605export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1606 await usingApi(async (api) => {16071608 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16091610 // Run the transaction1611 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1612 const events = await submitTransactionAsync(sender, tx);1613 const result = getGenericResult(events);1614 expect(result.success).to.be.true;16151616 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1617 });1618}16191620export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1621 await usingApi(async (api) => {16221623 // Run the transaction1624 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1625 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1626 const result = getGenericResult(events);16271628 // What to expect1629 // tslint:disable-next-line:no-unused-expression1630 expect(result.success).to.be.false;1631 });1632}16331634export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1635 await usingApi(async (api) => {1636 // Run the transaction1637 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1638 const events = await submitTransactionAsync(sender, tx);1639 const result = getGenericResult(events);16401641 // What to expect1642 // tslint:disable-next-line:no-unused-expression1643 expect(result.success).to.be.true;1644 });1645}16461647export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1648 await usingApi(async (api) => {1649 // Run the transaction1650 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1651 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1652 const result = getGenericResult(events);16531654 // What to expect1655 // tslint:disable-next-line:no-unused-expression1656 expect(result.success).to.be.false;1657 });1658}16591660export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1661 : Promise<UpDataStructsRpcCollection | null> => {1662 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1663};16641665export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1666 // set global object - collectionsCount1667 return (await api.rpc.unique.collectionStats()).created.toNumber();1668};16691670export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1671 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1672}16731674export async function waitNewBlocks(blocksCount = 1): Promise<void> {1675 await usingApi(async (api) => {1676 const promise = new Promise<void>(async (resolve) => {1677 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1678 if (blocksCount > 0) {1679 blocksCount--;1680 } else {1681 unsubscribe();1682 resolve();1683 }1684 });1685 });1686 return promise;1687 });1688}16891690export async function repartitionRFT(1691 api: ApiPromise,1692 collectionId: number,1693 sender: IKeyringPair,1694 tokenId: number,1695 amount: bigint,1696): Promise<boolean> {1697 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1698 const events = await submitTransactionAsync(sender, tx);1699 const result = getGenericResult(events);17001701 return result.success;1702}17031704export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1705 let i: any = it;1706 if (opts.only) i = i.only;1707 else if (opts.skip) i = i.skip;1708 i(name, async () => {1709 await usingApi(async (api, privateKeyWrapper) => {1710 await cb({api, privateKeyWrapper});1711 });1712 });1713}17141715itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1716itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});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} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';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};404142export enum Pallets {43 Inflation = 'inflation',44 RmrkCore = 'rmrkcore',45 ReFungible = 'refungible',46 Fungible = 'fungible',47 NFT = 'nonfungible',48}4950export async function isUnique(): Promise<boolean> {51 return usingApi(async api => {52 const chain = await api.rpc.system.chain();5354 return chain.eq('UNIQUE');55 });56}5758export async function isQuartz(): Promise<boolean> {59 return usingApi(async api => {60 const chain = await api.rpc.system.chain();61 62 return chain.eq('QUARTZ');63 });64}6566let modulesNames: any;67export function getModuleNames(api: ApiPromise): string[] {68 if (typeof modulesNames === 'undefined') 69 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());70 return modulesNames;71}7273export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {74 if (typeof input === 'string') {75 if (input.length >= 47) {76 return {Substrate: input};77 } else if (input.length === 42 && input.startsWith('0x')) {78 return {Ethereum: input.toLowerCase()};79 } else if (input.length === 40 && !input.startsWith('0x')) {80 return {Ethereum: '0x' + input.toLowerCase()};81 } else {82 throw new Error(`Unknown address format: "${input}"`);83 }84 }85 if ('address' in input) {86 return {Substrate: input.address};87 }88 if ('Ethereum' in input) {89 return {90 Ethereum: input.Ethereum.toLowerCase(),91 };92 } else if ('ethereum' in input) {93 return {94 Ethereum: (input as any).ethereum.toLowerCase(),95 };96 } else if ('Substrate' in input) {97 return input;98 } else if ('substrate' in input) {99 return {100 Substrate: (input as any).substrate,101 };102 }103104 // AccountId105 return {Substrate: input.toString()};106}107export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {108 input = normalizeAccountId(input);109 if ('Substrate' in input) {110 return input.Substrate;111 } else {112 return evmToAddress(input.Ethereum);113 }114}115116export const U128_MAX = (1n << 128n) - 1n;117118const MICROUNIQUE = 1_000_000_000_000n;119const MILLIUNIQUE = 1_000n * MICROUNIQUE;120const CENTIUNIQUE = 10n * MILLIUNIQUE;121export const UNIQUE = 100n * CENTIUNIQUE;122123interface GenericResult<T> {124 success: boolean;125 data: T | null;126}127128interface CreateCollectionResult {129 success: boolean;130 collectionId: number;131}132133interface CreateItemResult {134 success: boolean;135 collectionId: number;136 itemId: number;137 recipient?: CrossAccountId;138 amount?: number;139}140141interface DestroyItemResult {142 success: boolean;143 collectionId: number;144 itemId: number;145 owner: CrossAccountId;146 amount: number;147}148149interface TransferResult {150 collectionId: number;151 itemId: number;152 sender?: CrossAccountId;153 recipient?: CrossAccountId;154 value: bigint;155}156157interface IReFungibleOwner {158 fraction: BN;159 owner: number[];160}161162interface IGetMessage {163 checkMsgUnqMethod: string;164 checkMsgTrsMethod: string;165 checkMsgSysMethod: string;166}167168export interface IFungibleTokenDataType {169 value: number;170}171172export interface IChainLimits {173 collectionNumbersLimit: number;174 accountTokenOwnershipLimit: number;175 collectionsAdminsLimit: number;176 customDataLimit: number;177 nftSponsorTransferTimeout: number;178 fungibleSponsorTransferTimeout: number;179 refungibleSponsorTransferTimeout: number;180 //offchainSchemaLimit: number;181 //constOnChainSchemaLimit: number;182}183184export interface IReFungibleTokenDataType {185 owner: IReFungibleOwner[];186}187188export function uniqueEventMessage(events: EventRecord[]): IGetMessage {189 let checkMsgUnqMethod = '';190 let checkMsgTrsMethod = '';191 let checkMsgSysMethod = '';192 events.forEach(({event: {method, section}}) => {193 if (section === 'common') {194 checkMsgUnqMethod = method;195 } else if (section === 'treasury') {196 checkMsgTrsMethod = method;197 } else if (section === 'system') {198 checkMsgSysMethod = method;199 } else { return null; }200 });201 const result: IGetMessage = {202 checkMsgUnqMethod,203 checkMsgTrsMethod,204 checkMsgSysMethod,205 };206 return result;207}208209export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {210 const event = events.find(r => check(r.event));211 if (!event) return;212 return event.event as T;213}214215export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;216export function getGenericResult<T>(217 events: EventRecord[],218 expectSection: string,219 expectMethod: string,220 extractAction: (data: GenericEventData) => T221): GenericResult<T>;222223export function getGenericResult<T>(224 events: EventRecord[],225 expectSection?: string,226 expectMethod?: string,227 extractAction?: (data: GenericEventData) => T,228): GenericResult<T> {229 let success = false;230 let successData = null;231232 events.forEach(({event: {data, method, section}}) => {233 // console.log(` ${phase}: ${section}.${method}:: ${data}`);234 if (method === 'ExtrinsicSuccess') {235 success = true;236 } else if ((expectSection == section) && (expectMethod == method)) {237 successData = extractAction!(data as any);238 }239 });240241 const result: GenericResult<T> = {242 success,243 data: successData,244 };245 return result;246}247248export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {249 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));250 const result: CreateCollectionResult = {251 success: genericResult.success,252 collectionId: genericResult.data ?? 0,253 };254 return result;255}256257export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {258 const results: CreateItemResult[] = [];259 260 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {261 const collectionId = parseInt(data[0].toString(), 10);262 const itemId = parseInt(data[1].toString(), 10);263 const recipient = normalizeAccountId(data[2].toJSON() as any);264 const amount = parseInt(data[3].toString(), 10);265266 const itemRes: CreateItemResult = {267 success: true,268 collectionId,269 itemId,270 recipient,271 amount,272 };273274 results.push(itemRes);275 return results;276 });277278 if (!genericResult.success) return [];279 return results;280}281282export function getCreateItemResult(events: EventRecord[]): CreateItemResult {283 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));284 285 if (genericResult.data == null) 286 return {287 success: genericResult.success,288 collectionId: 0,289 itemId: 0,290 amount: 0,291 };292 else 293 return {294 success: genericResult.success,295 collectionId: genericResult.data[0] as number,296 itemId: genericResult.data[1] as number,297 recipient: normalizeAccountId(genericResult.data![2] as any),298 amount: genericResult.data[3] as number,299 };300}301302export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {303 const results: DestroyItemResult[] = [];304 305 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {306 const collectionId = parseInt(data[0].toString(), 10);307 const itemId = parseInt(data[1].toString(), 10);308 const owner = normalizeAccountId(data[2].toJSON() as any);309 const amount = parseInt(data[3].toString(), 10);310311 const itemRes: DestroyItemResult = {312 success: true,313 collectionId,314 itemId,315 owner,316 amount,317 };318319 results.push(itemRes);320 return results;321 });322323 if (!genericResult.success) return [];324 return results;325}326327export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {328 for (const {event} of events) {329 if (api.events.common.Transfer.is(event)) {330 const [collection, token, sender, recipient, value] = event.data;331 return {332 collectionId: collection.toNumber(),333 itemId: token.toNumber(),334 sender: normalizeAccountId(sender.toJSON() as any),335 recipient: normalizeAccountId(recipient.toJSON() as any),336 value: value.toBigInt(),337 };338 }339 }340 throw new Error('no transfer event');341}342343interface Nft {344 type: 'NFT';345}346347interface Fungible {348 type: 'Fungible';349 decimalPoints: number;350}351352interface ReFungible {353 type: 'ReFungible';354}355356export type CollectionMode = Nft | Fungible | ReFungible;357358export type Property = {359 key: any,360 value: any,361};362363type Permission = {364 mutable: boolean;365 collectionAdmin: boolean;366 tokenOwner: boolean;367}368369type PropertyPermission = {370 key: any;371 permission: Permission;372}373374export type CreateCollectionParams = {375 mode: CollectionMode,376 name: string,377 description: string,378 tokenPrefix: string,379 properties?: Array<Property>,380 propPerm?: Array<PropertyPermission>381};382383const defaultCreateCollectionParams: CreateCollectionParams = {384 description: 'description',385 mode: {type: 'NFT'},386 name: 'name',387 tokenPrefix: 'prefix',388};389390export async function391createCollection(392 api: ApiPromise,393 sender: IKeyringPair,394 params: Partial<CreateCollectionParams> = {},395): Promise<CreateCollectionResult> {396 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};397398 let modeprm = {};399 if (mode.type === 'NFT') {400 modeprm = {nft: null};401 } else if (mode.type === 'Fungible') {402 modeprm = {fungible: mode.decimalPoints};403 } else if (mode.type === 'ReFungible') {404 modeprm = {refungible: null};405 }406407 const tx = api.tx.unique.createCollectionEx({408 name: strToUTF16(name),409 description: strToUTF16(description),410 tokenPrefix: strToUTF16(tokenPrefix),411 mode: modeprm as any,412 });413 const events = await submitTransactionAsync(sender, tx);414 return getCreateCollectionResult(events);415}416417export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {418 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};419420 let collectionId = 0;421 await usingApi(async (api, privateKeyWrapper) => {422 // Get number of collections before the transaction423 const collectionCountBefore = await getCreatedCollectionCount(api);424425 // Run the CreateCollection transaction426 const alicePrivateKey = privateKeyWrapper('//Alice');427428 const result = await createCollection(api, alicePrivateKey, params);429430 // Get number of collections after the transaction431 const collectionCountAfter = await getCreatedCollectionCount(api);432433 // Get the collection434 const collection = await queryCollectionExpectSuccess(api, result.collectionId);435436 // What to expect437 // tslint:disable-next-line:no-unused-expression438 expect(result.success).to.be.true;439 expect(result.collectionId).to.be.equal(collectionCountAfter);440 // tslint:disable-next-line:no-unused-expression441 expect(collection).to.be.not.null;442 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');443 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));444 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);445 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);446 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);447448 collectionId = result.collectionId;449 });450451 return collectionId;452}453454export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {455 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};456457 let collectionId = 0;458 await usingApi(async (api, privateKeyWrapper) => {459 // Get number of collections before the transaction460 const collectionCountBefore = await getCreatedCollectionCount(api);461462 // Run the CreateCollection transaction463 const alicePrivateKey = privateKeyWrapper('//Alice');464465 let modeprm = {};466 if (mode.type === 'NFT') {467 modeprm = {nft: null};468 } else if (mode.type === 'Fungible') {469 modeprm = {fungible: mode.decimalPoints};470 } else if (mode.type === 'ReFungible') {471 modeprm = {refungible: null};472 }473474 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});475 const events = await submitTransactionAsync(alicePrivateKey, tx);476 const result = getCreateCollectionResult(events);477478 // Get number of collections after the transaction479 const collectionCountAfter = await getCreatedCollectionCount(api);480481 // Get the collection482 const collection = await queryCollectionExpectSuccess(api, result.collectionId);483484 // What to expect485 // tslint:disable-next-line:no-unused-expression486 expect(result.success).to.be.true;487 expect(result.collectionId).to.be.equal(collectionCountAfter);488 // tslint:disable-next-line:no-unused-expression489 expect(collection).to.be.not.null;490 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');491 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));492 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);493 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);494 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);495496497 collectionId = result.collectionId;498 });499500 return collectionId;501}502503export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {504 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};505506 await usingApi(async (api, privateKeyWrapper) => {507 // Get number of collections before the transaction508 const collectionCountBefore = await getCreatedCollectionCount(api);509510 // Run the CreateCollection transaction511 const alicePrivateKey = privateKeyWrapper('//Alice');512513 let modeprm = {};514 if (mode.type === 'NFT') {515 modeprm = {nft: null};516 } else if (mode.type === 'Fungible') {517 modeprm = {fungible: mode.decimalPoints};518 } else if (mode.type === 'ReFungible') {519 modeprm = {refungible: null};520 }521522 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});523 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;524525526 // Get number of collections after the transaction527 const collectionCountAfter = await getCreatedCollectionCount(api);528529 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');530 });531}532533export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {534 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};535536 let modeprm = {};537 if (mode.type === 'NFT') {538 modeprm = {nft: null};539 } else if (mode.type === 'Fungible') {540 modeprm = {fungible: mode.decimalPoints};541 } else if (mode.type === 'ReFungible') {542 modeprm = {refungible: null};543 }544545 await usingApi(async (api, privateKeyWrapper) => {546 // Get number of collections before the transaction547 const collectionCountBefore = await getCreatedCollectionCount(api);548549 // Run the CreateCollection transaction550 const alicePrivateKey = privateKeyWrapper('//Alice');551 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});552 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;553554 // Get number of collections after the transaction555 const collectionCountAfter = await getCreatedCollectionCount(api);556557 // What to expect558 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');559 });560}561562export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {563 let bal = 0n;564 let unused;565 do {566 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;567 unused = privateKeyWrapper(`//${randomSeed}`);568 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();569 } while (bal !== 0n);570 return unused;571}572573export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {574 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();575}576577export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {578 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));579}580581export async function findNotExistingCollection(api: ApiPromise): Promise<number> {582 const totalNumber = await getCreatedCollectionCount(api);583 const newCollection: number = totalNumber + 1;584 return newCollection;585}586587function getDestroyResult(events: EventRecord[]): boolean {588 let success = false;589 events.forEach(({event: {method}}) => {590 if (method == 'ExtrinsicSuccess') {591 success = true;592 }593 });594 return success;595}596597export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {598 await usingApi(async (api, privateKeyWrapper) => {599 // Run the DestroyCollection transaction600 const alicePrivateKey = privateKeyWrapper(senderSeed);601 const tx = api.tx.unique.destroyCollection(collectionId);602 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;603 });604}605606export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {607 await usingApi(async (api, privateKeyWrapper) => {608 // Run the DestroyCollection transaction609 const alicePrivateKey = privateKeyWrapper(senderSeed);610 const tx = api.tx.unique.destroyCollection(collectionId);611 const events = await submitTransactionAsync(alicePrivateKey, tx);612 const result = getDestroyResult(events);613 expect(result).to.be.true;614615 // What to expect616 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;617 });618}619620export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {621 await usingApi(async (api) => {622 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);623 const events = await submitTransactionAsync(sender, tx);624 const result = getGenericResult(events);625626 expect(result.success).to.be.true;627 });628}629630export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {631 await usingApi(async(api) => {632 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);633 const events = await submitTransactionAsync(sender, tx);634 const result = getGenericResult(events);635636 expect(result.success).to.be.true;637 });638};639640export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {641 await usingApi(async (api) => {642 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);643 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;644 const result = getGenericResult(events);645646 expect(result.success).to.be.false;647 });648}649650export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {651 await usingApi(async (api, privateKeyWrapper) => {652653 // Run the transaction654 const senderPrivateKey = privateKeyWrapper(sender);655 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);656 const events = await submitTransactionAsync(senderPrivateKey, tx);657 const result = getGenericResult(events);658659 // Get the collection660 const collection = await queryCollectionExpectSuccess(api, collectionId);661662 // What to expect663 expect(result.success).to.be.true;664 expect(collection.sponsorship.toJSON()).to.deep.equal({665 unconfirmed: sponsor,666 });667 });668}669670export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {671 await usingApi(async (api, privateKeyWrapper) => {672673 // Run the transaction674 const alicePrivateKey = privateKeyWrapper(sender);675 const tx = api.tx.unique.removeCollectionSponsor(collectionId);676 const events = await submitTransactionAsync(alicePrivateKey, tx);677 const result = getGenericResult(events);678679 // Get the collection680 const collection = await queryCollectionExpectSuccess(api, collectionId);681682 // What to expect683 expect(result.success).to.be.true;684 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});685 });686}687688export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {689 await usingApi(async (api, privateKeyWrapper) => {690691 // Run the transaction692 const alicePrivateKey = privateKeyWrapper(senderSeed);693 const tx = api.tx.unique.removeCollectionSponsor(collectionId);694 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;695 });696}697698export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {699 await usingApi(async (api, privateKeyWrapper) => {700701 // Run the transaction702 const alicePrivateKey = privateKeyWrapper(senderSeed);703 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);704 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;705 });706}707708export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {709 await usingApi(async (api, privateKeyWrapper) => {710711 // Run the transaction712 const sender = privateKeyWrapper(senderSeed);713 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);714 });715}716717export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {718 await usingApi(async (api, privateKeyWrapper) => {719720 // Run the transaction721 const tx = api.tx.unique.confirmSponsorship(collectionId);722 const events = await submitTransactionAsync(sender, tx);723 const result = getGenericResult(events);724725 // Get the collection726 const collection = await queryCollectionExpectSuccess(api, collectionId);727728 // What to expect729 expect(result.success).to.be.true;730 expect(collection.sponsorship.toJSON()).to.be.deep.equal({731 confirmed: sender.address,732 });733 });734}735736737export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {738 await usingApi(async (api, privateKeyWrapper) => {739740 // Run the transaction741 const sender = privateKeyWrapper(senderSeed);742 const tx = api.tx.unique.confirmSponsorship(collectionId);743 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;744 });745}746747export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {748 await usingApi(async (api) => {749 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);750 const events = await submitTransactionAsync(sender, tx);751 const result = getGenericResult(events);752753 expect(result.success).to.be.true;754 });755}756757export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {758 await usingApi(async (api) => {759 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);760 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;761 const result = getGenericResult(events);762763 expect(result.success).to.be.false;764 });765}766767export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {768769 await usingApi(async (api) => {770771 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 expect(result.success).to.be.true;776 });777}778779export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {780781 await usingApi(async (api) => {782783 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);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 async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {792 await usingApi(async (api) => {793 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);794 const events = await submitTransactionAsync(sender, tx);795 const result = getGenericResult(events);796797 expect(result.success).to.be.true;798 });799}800801export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {802 await usingApi(async (api) => {803 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);804 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;805 const result = getGenericResult(events);806807 expect(result.success).to.be.false;808 });809}810811export async function getNextSponsored(812 api: ApiPromise,813 collectionId: number,814 account: string | CrossAccountId,815 tokenId: number,816): Promise<number> {817 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));818}819820export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {821 await usingApi(async (api) => {822 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);823 const events = await submitTransactionAsync(sender, tx);824 const result = getGenericResult(events);825826 expect(result.success).to.be.true;827 });828}829830export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {831 let allowlisted = false;832 await usingApi(async (api) => {833 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;834 });835 return allowlisted;836}837838export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {839 await usingApi(async (api) => {840 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());841 const events = await submitTransactionAsync(sender, tx);842 const result = getGenericResult(events);843844 expect(result.success).to.be.true;845 });846}847848export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {849 await usingApi(async (api) => {850 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());851 const events = await submitTransactionAsync(sender, tx);852 const result = getGenericResult(events);853854 expect(result.success).to.be.true;855 });856}857858export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {859 await usingApi(async (api) => {860 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());861 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;862 const result = getGenericResult(events);863864 expect(result.success).to.be.false;865 });866}867868export interface CreateFungibleData {869 readonly Value: bigint;870}871872export interface CreateReFungibleData { }873export interface CreateNftData { }874875export type CreateItemData = {876 NFT: CreateNftData;877} | {878 Fungible: CreateFungibleData;879} | {880 ReFungible: CreateReFungibleData;881};882883export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {884 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);885 const events = await submitTransactionAsync(sender, tx);886 return getGenericResult(events).success;887}888889export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {890 await usingApi(async (api) => {891 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);892 // if burning token by admin - use adminButnItemExpectSuccess893 expect(balanceBefore >= BigInt(value)).to.be.true;894895 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;896897 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);898 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);899 });900}901902export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {903 await usingApi(async (api) => {904 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);905906 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;907 const result = getCreateCollectionResult(events);908 // tslint:disable-next-line:no-unused-expression909 expect(result.success).to.be.false;910 });911}912913export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {914 await usingApi(async (api) => {915 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);916 const events = await submitTransactionAsync(sender, tx);917 return getGenericResult(events).success;918 });919}920921export async function922approve(923 api: ApiPromise,924 collectionId: number,925 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,926) {927 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);928 const events = await submitTransactionAsync(owner, approveUniqueTx);929 return getGenericResult(events).success;930}931932export async function933approveExpectSuccess(934 collectionId: number,935 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,936) {937 await usingApi(async (api: ApiPromise) => {938 const result = await approve(api, collectionId, tokenId, owner, approved, amount);939 expect(result).to.be.true;940941 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));942 });943}944945export async function adminApproveFromExpectSuccess(946 collectionId: number,947 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,948) {949 await usingApi(async (api: ApiPromise) => {950 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);951 const events = await submitTransactionAsync(admin, approveUniqueTx);952 const result = getGenericResult(events);953 expect(result.success).to.be.true;954955 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));956 });957}958959export async function960transferFrom(961 api: ApiPromise,962 collectionId: number,963 tokenId: number,964 accountApproved: IKeyringPair,965 accountFrom: IKeyringPair | CrossAccountId,966 accountTo: IKeyringPair | CrossAccountId,967 value: number | bigint,968) {969 const from = normalizeAccountId(accountFrom);970 const to = normalizeAccountId(accountTo);971 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);972 const events = await submitTransactionAsync(accountApproved, transferFromTx);973 return getGenericResult(events).success;974}975976export async function977transferFromExpectSuccess(978 collectionId: number,979 tokenId: number,980 accountApproved: IKeyringPair,981 accountFrom: IKeyringPair | CrossAccountId,982 accountTo: IKeyringPair | CrossAccountId,983 value: number | bigint = 1,984 type = 'NFT',985) {986 await usingApi(async (api: ApiPromise) => {987 const from = normalizeAccountId(accountFrom);988 const to = normalizeAccountId(accountTo);989 let balanceBefore = 0n;990 if (type === 'Fungible' || type === 'ReFungible') {991 balanceBefore = await getBalance(api, collectionId, to, tokenId);992 }993 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;994 if (type === 'NFT') {995 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);996 }997 if (type === 'Fungible') {998 const balanceAfter = await getBalance(api, collectionId, to, tokenId);999 if (JSON.stringify(to) !== JSON.stringify(from)) {1000 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1001 } else {1002 expect(balanceAfter).to.be.equal(balanceBefore);1003 }1004 }1005 if (type === 'ReFungible') {1006 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1007 }1008 });1009}10101011export async function1012transferFromExpectFail(1013 collectionId: number,1014 tokenId: number,1015 accountApproved: IKeyringPair,1016 accountFrom: IKeyringPair,1017 accountTo: IKeyringPair,1018 value: number | bigint = 1,1019) {1020 await usingApi(async (api: ApiPromise) => {1021 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1022 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1023 const result = getCreateCollectionResult(events);1024 // tslint:disable-next-line:no-unused-expression1025 expect(result.success).to.be.false;1026 });1027}10281029/* eslint no-async-promise-executor: "off" */1030export async function getBlockNumber(api: ApiPromise): Promise<number> {1031 return new Promise<number>(async (resolve) => {1032 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1033 unsubscribe();1034 resolve(head.number.toNumber());1035 });1036 });1037}10381039export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1040 await usingApi(async (api) => {1041 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1042 const events = await submitTransactionAsync(sender, changeAdminTx);1043 const result = getCreateCollectionResult(events);1044 expect(result.success).to.be.true;1045 });1046}10471048export async function adminApproveFromExpectFail(1049 collectionId: number,1050 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1051) {1052 await usingApi(async (api: ApiPromise) => {1053 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1054 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1055 const result = getGenericResult(events);1056 expect(result.success).to.be.false;1057 });1058}10591060export async function1061getFreeBalance(account: IKeyringPair): Promise<bigint> {1062 let balance = 0n;1063 await usingApi(async (api) => {1064 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1065 });10661067 return balance;1068}10691070export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1071 const tx = api.tx.balances.transfer(target, amount);1072 const events = await submitTransactionAsync(source, tx);1073 const result = getGenericResult(events);1074 expect(result.success).to.be.true;1075}10761077export async function1078scheduleExpectSuccess(1079 operationTx: any,1080 sender: IKeyringPair,1081 blockSchedule: number,1082 scheduledId: string,1083 period = 1,1084 repetitions = 1,1085) {1086 await usingApi(async (api: ApiPromise) => {1087 const blockNumber: number | undefined = await getBlockNumber(api);1088 const expectedBlockNumber = blockNumber + blockSchedule;10891090 expect(blockNumber).to.be.greaterThan(0);1091 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1092 scheduledId,1093 expectedBlockNumber, 1094 repetitions > 1 ? [period, repetitions] : null, 1095 0, 1096 {Value: operationTx as any},1097 );10981099 const events = await submitTransactionAsync(sender, scheduleTx);1100 expect(getGenericResult(events).success).to.be.true;1101 });1102}11031104export async function1105scheduleExpectFailure(1106 operationTx: any,1107 sender: IKeyringPair,1108 blockSchedule: number,1109 scheduledId: string,1110 period = 1,1111 repetitions = 1,1112) {1113 await usingApi(async (api: ApiPromise) => {1114 const blockNumber: number | undefined = await getBlockNumber(api);1115 const expectedBlockNumber = blockNumber + blockSchedule;11161117 expect(blockNumber).to.be.greaterThan(0);1118 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1119 scheduledId,1120 expectedBlockNumber, 1121 repetitions <= 1 ? null : [period, repetitions], 1122 0, 1123 {Value: operationTx as any},1124 );11251126 //const events = 1127 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1128 //expect(getGenericResult(events).success).to.be.false;1129 });1130}11311132export async function1133scheduleTransferAndWaitExpectSuccess(1134 collectionId: number,1135 tokenId: number,1136 sender: IKeyringPair,1137 recipient: IKeyringPair,1138 value: number | bigint = 1,1139 blockSchedule: number,1140 scheduledId: string,1141) {1142 await usingApi(async (api: ApiPromise) => {1143 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11441145 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11461147 // sleep for n + 1 blocks1148 await waitNewBlocks(blockSchedule + 1);11491150 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11511152 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1153 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1154 });1155}11561157export async function1158scheduleTransferExpectSuccess(1159 collectionId: number,1160 tokenId: number,1161 sender: IKeyringPair,1162 recipient: IKeyringPair,1163 value: number | bigint = 1,1164 blockSchedule: number,1165 scheduledId: string,1166) {1167 await usingApi(async (api: ApiPromise) => {1168 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11691170 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11711172 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1173 });1174}11751176export async function1177scheduleTransferFundsPeriodicExpectSuccess(1178 amount: bigint,1179 sender: IKeyringPair,1180 recipient: IKeyringPair,1181 blockSchedule: number,1182 scheduledId: string,1183 period: number,1184 repetitions: number,1185) {1186 await usingApi(async (api: ApiPromise) => {1187 const transferTx = api.tx.balances.transfer(recipient.address, amount);11881189 const balanceBefore = await getFreeBalance(recipient);1190 1191 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11921193 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1194 });1195}11961197export async function1198transfer(1199 api: ApiPromise,1200 collectionId: number,1201 tokenId: number,1202 sender: IKeyringPair,1203 recipient: IKeyringPair | CrossAccountId,1204 value: number | bigint,1205) : Promise<boolean> {1206 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1207 const events = await executeTransaction(api, sender, transferTx);1208 return getGenericResult(events).success;1209}12101211export async function1212transferExpectSuccess(1213 collectionId: number,1214 tokenId: number,1215 sender: IKeyringPair,1216 recipient: IKeyringPair | CrossAccountId,1217 value: number | bigint = 1,1218 type = 'NFT',1219) {1220 await usingApi(async (api: ApiPromise) => {1221 const from = normalizeAccountId(sender);1222 const to = normalizeAccountId(recipient);12231224 let balanceBefore = 0n;1225 if (type === 'Fungible' || type === 'ReFungible') {1226 balanceBefore = await getBalance(api, collectionId, to, tokenId);1227 }12281229 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1230 const events = await executeTransaction(api, sender, transferTx);1231 const result = getTransferResult(api, events);12321233 expect(result.collectionId).to.be.equal(collectionId);1234 expect(result.itemId).to.be.equal(tokenId);1235 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1236 expect(result.recipient).to.be.deep.equal(to);1237 expect(result.value).to.be.equal(BigInt(value));12381239 if (type === 'NFT') {1240 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1241 }1242 if (type === 'Fungible' || type === 'ReFungible') {1243 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1244 if (JSON.stringify(to) !== JSON.stringify(from)) {1245 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1246 } else {1247 expect(balanceAfter).to.be.equal(balanceBefore);1248 }1249 }1250 });1251}12521253export async function1254transferExpectFailure(1255 collectionId: number,1256 tokenId: number,1257 sender: IKeyringPair,1258 recipient: IKeyringPair | CrossAccountId,1259 value: number | bigint = 1,1260) {1261 await usingApi(async (api: ApiPromise) => {1262 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1263 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1264 const result = getGenericResult(events);1265 // if (events && Array.isArray(events)) {1266 // const result = getCreateCollectionResult(events);1267 // tslint:disable-next-line:no-unused-expression1268 expect(result.success).to.be.false;1269 //}1270 });1271}12721273export async function1274approveExpectFail(1275 collectionId: number,1276 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1277) {1278 await usingApi(async (api: ApiPromise) => {1279 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1280 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1281 const result = getCreateCollectionResult(events);1282 // tslint:disable-next-line:no-unused-expression1283 expect(result.success).to.be.false;1284 });1285}12861287export async function getBalance(1288 api: ApiPromise,1289 collectionId: number,1290 owner: string | CrossAccountId | IKeyringPair,1291 token: number,1292): Promise<bigint> {1293 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1294}1295export async function getTokenOwner(1296 api: ApiPromise,1297 collectionId: number,1298 token: number,1299): Promise<CrossAccountId> {1300 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1301 if (owner == null) throw new Error('owner == null');1302 return normalizeAccountId(owner);1303}1304export async function getTopmostTokenOwner(1305 api: ApiPromise,1306 collectionId: number,1307 token: number,1308): Promise<CrossAccountId> {1309 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1310 if (owner == null) throw new Error('owner == null');1311 return normalizeAccountId(owner);1312}1313export async function getTokenChildren(1314 api: ApiPromise,1315 collectionId: number,1316 tokenId: number,1317): Promise<UpDataStructsTokenChild[]> {1318 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1319}1320export async function isTokenExists(1321 api: ApiPromise,1322 collectionId: number,1323 token: number,1324): Promise<boolean> {1325 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1326}1327export async function getLastTokenId(1328 api: ApiPromise,1329 collectionId: number,1330): Promise<number> {1331 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1332}1333export async function getAdminList(1334 api: ApiPromise,1335 collectionId: number,1336): Promise<string[]> {1337 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1338}1339export async function getTokenProperties(1340 api: ApiPromise,1341 collectionId: number,1342 tokenId: number,1343 propertyKeys: string[],1344): Promise<UpDataStructsProperty[]> {1345 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1346}13471348export async function createFungibleItemExpectSuccess(1349 sender: IKeyringPair,1350 collectionId: number,1351 data: CreateFungibleData,1352 owner: CrossAccountId | string = sender.address,1353) {1354 return await usingApi(async (api) => {1355 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13561357 const events = await submitTransactionAsync(sender, tx);1358 const result = getCreateItemResult(events);13591360 expect(result.success).to.be.true;1361 return result.itemId;1362 });1363}13641365export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1366 await usingApi(async (api) => {1367 const to = normalizeAccountId(owner);1368 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13691370 const events = await submitTransactionAsync(sender, tx);1371 expect(getGenericResult(events).success).to.be.true;1372 });1373}13741375export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1376 await usingApi(async (api) => {1377 const to = normalizeAccountId(owner);1378 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13791380 const events = await submitTransactionAsync(sender, tx);1381 const result = getCreateItemsResult(events);13821383 for (const res of result) {1384 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1385 }1386 });1387}13881389export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1390 await usingApi(async (api) => {1391 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13921393 const events = await submitTransactionAsync(sender, tx);1394 const result = getCreateItemsResult(events);13951396 for (const res of result) {1397 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1398 }1399 });1400}14011402export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1403 let newItemId = 0;1404 await usingApi(async (api) => {1405 const to = normalizeAccountId(owner);1406 const itemCountBefore = await getLastTokenId(api, collectionId);1407 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14081409 let tx;1410 if (createMode === 'Fungible') {1411 const createData = {fungible: {value: 10}};1412 tx = api.tx.unique.createItem(collectionId, to, createData as any);1413 } else if (createMode === 'ReFungible') {1414 const createData = {refungible: {pieces: 100}};1415 tx = api.tx.unique.createItem(collectionId, to, createData as any);1416 } else {1417 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1418 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1419 }14201421 const events = await submitTransactionAsync(sender, tx);1422 const result = getCreateItemResult(events);14231424 const itemCountAfter = await getLastTokenId(api, collectionId);1425 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14261427 if (createMode === 'NFT') {1428 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1429 }14301431 // What to expect1432 // tslint:disable-next-line:no-unused-expression1433 expect(result.success).to.be.true;1434 if (createMode === 'Fungible') {1435 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1436 } else {1437 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1438 }1439 expect(collectionId).to.be.equal(result.collectionId);1440 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1441 expect(to).to.be.deep.equal(result.recipient);1442 newItemId = result.itemId;1443 });1444 return newItemId;1445}14461447export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1448 await usingApi(async (api) => {14491450 let tx;1451 if (createMode === 'NFT') {1452 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1453 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1454 } else {1455 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1456 }145714581459 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1460 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1461 const result = getCreateItemResult(events);14621463 expect(result.success).to.be.false;1464 });1465}14661467export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1468 let newItemId = 0;1469 await usingApi(async (api) => {1470 const to = normalizeAccountId(owner);1471 const itemCountBefore = await getLastTokenId(api, collectionId);1472 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14731474 let tx;1475 if (createMode === 'Fungible') {1476 const createData = {fungible: {value: 10}};1477 tx = api.tx.unique.createItem(collectionId, to, createData as any);1478 } else if (createMode === 'ReFungible') {1479 const createData = {refungible: {pieces: 100}};1480 tx = api.tx.unique.createItem(collectionId, to, createData as any);1481 } else {1482 const createData = {nft: {}};1483 tx = api.tx.unique.createItem(collectionId, to, createData as any);1484 }14851486 const events = await executeTransaction(api, sender, tx);1487 const result = getCreateItemResult(events);14881489 const itemCountAfter = await getLastTokenId(api, collectionId);1490 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14911492 // What to expect1493 // tslint:disable-next-line:no-unused-expression1494 expect(result.success).to.be.true;1495 if (createMode === 'Fungible') {1496 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1497 } else {1498 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1499 }1500 expect(collectionId).to.be.equal(result.collectionId);1501 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1502 expect(to).to.be.deep.equal(result.recipient);1503 newItemId = result.itemId;1504 });1505 return newItemId;1506}15071508export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1509 const createData = {refungible: {pieces: amount}};1510 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15111512 const events = await submitTransactionAsync(sender, tx);1513 return getCreateItemResult(events);1514}15151516export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1517 await usingApi(async (api) => {1518 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15191520 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521 const result = getCreateItemResult(events);15221523 expect(result.success).to.be.false;1524 });1525}15261527export async function setPublicAccessModeExpectSuccess(1528 sender: IKeyringPair, collectionId: number,1529 accessMode: 'Normal' | 'AllowList',1530) {1531 await usingApi(async (api) => {15321533 // Run the transaction1534 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1535 const events = await submitTransactionAsync(sender, tx);1536 const result = getGenericResult(events);15371538 // Get the collection1539 const collection = await queryCollectionExpectSuccess(api, collectionId);15401541 // What to expect1542 // tslint:disable-next-line:no-unused-expression1543 expect(result.success).to.be.true;1544 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1545 });1546}15471548export async function setPublicAccessModeExpectFail(1549 sender: IKeyringPair, collectionId: number,1550 accessMode: 'Normal' | 'AllowList',1551) {1552 await usingApi(async (api) => {15531554 // Run the transaction1555 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1556 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1557 const result = getGenericResult(events);15581559 // What to expect1560 // tslint:disable-next-line:no-unused-expression1561 expect(result.success).to.be.false;1562 });1563}15641565export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1566 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1567}15681569export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1570 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1571}15721573export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1574 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1575}15761577export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1578 await usingApi(async (api) => {15791580 // Run the transaction1581 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1582 const events = await submitTransactionAsync(sender, tx);1583 const result = getGenericResult(events);1584 expect(result.success).to.be.true;15851586 // Get the collection1587 const collection = await queryCollectionExpectSuccess(api, collectionId);15881589 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1590 });1591}15921593export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1594 await setMintPermissionExpectSuccess(sender, collectionId, true);1595}15961597export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1598 await usingApi(async (api) => {1599 // Run the transaction1600 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1601 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1602 const result = getCreateCollectionResult(events);1603 // tslint:disable-next-line:no-unused-expression1604 expect(result.success).to.be.false;1605 });1606}16071608export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1609 await usingApi(async (api) => {1610 // Run the transaction1611 const tx = api.tx.unique.setChainLimits(limits);1612 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1613 const result = getCreateCollectionResult(events);1614 // tslint:disable-next-line:no-unused-expression1615 expect(result.success).to.be.false;1616 });1617}16181619export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1620 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1621}16221623export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1624 await usingApi(async (api) => {1625 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16261627 // Run the transaction1628 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1629 const events = await submitTransactionAsync(sender, tx);1630 const result = getGenericResult(events);1631 expect(result.success).to.be.true;16321633 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1634 });1635}16361637export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1638 await usingApi(async (api) => {16391640 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16411642 // Run the transaction1643 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1644 const events = await submitTransactionAsync(sender, tx);1645 const result = getGenericResult(events);1646 expect(result.success).to.be.true;16471648 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1649 });1650}16511652export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1653 await usingApi(async (api) => {16541655 // Run the transaction1656 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1657 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1658 const result = getGenericResult(events);16591660 // What to expect1661 // tslint:disable-next-line:no-unused-expression1662 expect(result.success).to.be.false;1663 });1664}16651666export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1667 await usingApi(async (api) => {1668 // Run the transaction1669 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1670 const events = await submitTransactionAsync(sender, tx);1671 const result = getGenericResult(events);16721673 // What to expect1674 // tslint:disable-next-line:no-unused-expression1675 expect(result.success).to.be.true;1676 });1677}16781679export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1680 await usingApi(async (api) => {1681 // Run the transaction1682 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1683 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1684 const result = getGenericResult(events);16851686 // What to expect1687 // tslint:disable-next-line:no-unused-expression1688 expect(result.success).to.be.false;1689 });1690}16911692export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1693 : Promise<UpDataStructsRpcCollection | null> => {1694 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1695};16961697export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1698 // set global object - collectionsCount1699 return (await api.rpc.unique.collectionStats()).created.toNumber();1700};17011702export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1703 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1704}17051706export async function waitNewBlocks(blocksCount = 1): Promise<void> {1707 await usingApi(async (api) => {1708 const promise = new Promise<void>(async (resolve) => {1709 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1710 if (blocksCount > 0) {1711 blocksCount--;1712 } else {1713 unsubscribe();1714 resolve();1715 }1716 });1717 });1718 return promise;1719 });1720}17211722export async function repartitionRFT(1723 api: ApiPromise,1724 collectionId: number,1725 sender: IKeyringPair,1726 tokenId: number,1727 amount: bigint,1728): Promise<boolean> {1729 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1730 const events = await submitTransactionAsync(sender, tx);1731 const result = getGenericResult(events);17321733 return result.success;1734}17351736export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1737 let i: any = it;1738 if (opts.only) i = i.only;1739 else if (opts.skip) i = i.skip;1740 i(name, async () => {1741 await usingApi(async (api, privateKeyWrapper) => {1742 await cb({api, privateKeyWrapper});1743 });1744 });1745}17461747itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1748itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});